Tags scan: Also find the first line in a buffer
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org.el
blob7021cd3b44d0e972cf59bfe30c14c098c1829dd9
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.25
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.25"
98 "The version number of the file org.el.")
100 (defun org-version (&optional here)
101 "Show the org-mode version in the echo area.
102 With prefix arg HERE, insert it at point."
103 (interactive "P")
104 (let ((version (format "Org-mode version %s" org-version)))
105 (message version)
106 (if here
107 (insert version))))
109 ;;; Compatibility constants
111 ;;; The custom variables
113 (defgroup org nil
114 "Outline-based notes management and organizer."
115 :tag "Org"
116 :group 'outlines
117 :group 'hypermedia
118 :group 'calendar)
120 (defcustom org-load-hook nil
121 "Hook that is run after org.el has been loaded."
122 :group 'org
123 :type 'hook)
125 (defvar org-modules) ; defined below
126 (defvar org-modules-loaded nil
127 "Have the modules been loaded already?")
129 (defun org-load-modules-maybe (&optional force)
130 "Load all extensions listed in `org-modules'."
131 (when (or force (not org-modules-loaded))
132 (mapc (lambda (ext)
133 (condition-case nil (require ext)
134 (error (message "Problems while trying to load feature `%s'" ext))))
135 org-modules)
136 (setq org-modules-loaded t)))
138 (defun org-set-modules (var value)
139 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
140 (set var value)
141 (when (featurep 'org)
142 (org-load-modules-maybe 'force)))
144 (when (org-bound-and-true-p org-modules)
145 (let ((a (member 'org-infojs org-modules)))
146 (and a (setcar a 'org-jsinfo))))
148 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
149 "Modules that should always be loaded together with org.el.
150 If a description starts with <C>, the file is not part of Emacs
151 and loading it will require that you have downloaded and properly installed
152 the org-mode distribution.
154 You can also use this system to load external packages (i.e. neither Org
155 core modules, not modules from the CONTRIB directory). Just add symbols
156 to the end of the list. If the package is called org-xyz.el, then you need
157 to add the symbol `xyz', and the package must have a call to
159 (provide 'org-xyz)"
160 :group 'org
161 :set 'org-set-modules
162 :type
163 '(set :greedy t
164 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
165 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
166 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
167 (const :tag " id: Global IDs for identifying entries" org-id)
168 (const :tag " info: Links to Info nodes" org-info)
169 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
170 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
171 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
172 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
173 (const :tag " mew Links to Mew folders/messages" org-mew)
174 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
175 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
176 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
177 (const :tag " vm: Links to VM folders/messages" org-vm)
178 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
179 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
180 (const :tag " mouse: Additional mouse support" org-mouse)
182 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
183 (const :tag "C annotation-helper: Call Remember directly from Browser" org-annotation-helper)
184 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
185 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
186 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
187 (const :tag "C collector: Collect properties into tables" org-collector)
188 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
189 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
190 (const :tag "C eval: Include command output as text" org-eval)
191 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
192 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
193 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
194 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
195 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
196 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
197 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
198 (const :tag "C mtags: Support for muse-like tags" org-mtags)
199 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
200 (const :tag "C R: Computation using the R language" org-R)
201 (const :tag "C registry: A registry for Org links" org-registry)
202 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
203 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
204 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
205 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
206 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
208 (defcustom org-support-shift-select nil
209 "Non-nil means, make shift-cursor commands select text when possible.
211 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
212 selecting a region, or enlarge thusly regions started in this way.
213 In Org-mode, in special contexts, these same keys are used for other
214 purposes, important enough to compete with shift selection. Org tries
215 to balance these needs by supporting `shift-select-mode' outside these
216 special contexts, under control of this variable.
218 The default of this variable is nil, to avoid confusing behavior. Shifted
219 cursor keys will then execute Org commands in the following contexts:
220 - on a headline, changing TODO state (left/right) and priority (up/down)
221 - on a time stamp, changing the time
222 - in a plain list item, changing the bullet type
223 - in a property definition line, switching between allowed values
224 - in the BEGIN line of a clock table (changing the time block).
225 Outside these contexts, the commands will throw an error.
227 When this variable is t and the cursor is not in a special context,
228 Org-mode will support shift-selection for making and enlarging regions.
229 To make this more effective, the bullet cycling will no longer happen
230 anywhere in an item line, but only if the cursor is exactly on the bullet.
232 If you set this variable to the symbol `always', then the keys
233 will not be special in headlines, property lines, and item lines, to make
234 shift selection work there as well. If this is what you want, you can
235 use the following alternative commands: `C-c C-t' and `C-c ,' to
236 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
237 TODO sets, `C-c -' to cycle item bullet types, and properties can be
238 edited by hand or in column view.
240 However, when the cursor is on a timestamp, shift-cursor commands
241 will still edit the time stamp - this is just too good to give up.
243 XEmacs user should have this variable set to nil, because shift-select-mode
244 is Emacs 23 only."
245 :group 'org
246 :type '(choice
247 (const :tag "Never" nil)
248 (const :tag "When outside special context" t)
249 (const :tag "Everywhere except timestamps" always)))
251 (defgroup org-startup nil
252 "Options concerning startup of Org-mode."
253 :tag "Org Startup"
254 :group 'org)
256 (defcustom org-startup-folded t
257 "Non-nil means, entering Org-mode will switch to OVERVIEW.
258 This can also be configured on a per-file basis by adding one of
259 the following lines anywhere in the buffer:
261 #+STARTUP: fold
262 #+STARTUP: nofold
263 #+STARTUP: content"
264 :group 'org-startup
265 :type '(choice
266 (const :tag "nofold: show all" nil)
267 (const :tag "fold: overview" t)
268 (const :tag "content: all headlines" content)))
270 (defcustom org-startup-truncated t
271 "Non-nil means, entering Org-mode will set `truncate-lines'.
272 This is useful since some lines containing links can be very long and
273 uninteresting. Also tables look terrible when wrapped."
274 :group 'org-startup
275 :type 'boolean)
277 (defcustom org-startup-align-all-tables nil
278 "Non-nil means, align all tables when visiting a file.
279 This is useful when the column width in tables is forced with <N> cookies
280 in table fields. Such tables will look correct only after the first re-align.
281 This can also be configured on a per-file basis by adding one of
282 the following lines anywhere in the buffer:
283 #+STARTUP: align
284 #+STARTUP: noalign"
285 :group 'org-startup
286 :type 'boolean)
288 (defcustom org-insert-mode-line-in-empty-file nil
289 "Non-nil means insert the first line setting Org-mode in empty files.
290 When the function `org-mode' is called interactively in an empty file, this
291 normally means that the file name does not automatically trigger Org-mode.
292 To ensure that the file will always be in Org-mode in the future, a
293 line enforcing Org-mode will be inserted into the buffer, if this option
294 has been set."
295 :group 'org-startup
296 :type 'boolean)
298 (defcustom org-replace-disputed-keys nil
299 "Non-nil means use alternative key bindings for some keys.
300 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
301 These keys are also used by other packages like shift-selection-mode'
302 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
303 If you want to use Org-mode together with one of these other modes,
304 or more generally if you would like to move some Org-mode commands to
305 other keys, set this variable and configure the keys with the variable
306 `org-disputed-keys'.
308 This option is only relevant at load-time of Org-mode, and must be set
309 *before* org.el is loaded. Changing it requires a restart of Emacs to
310 become effective."
311 :group 'org-startup
312 :type 'boolean)
314 (defcustom org-use-extra-keys nil
315 "Non-nil means use extra key sequence definitions for certain
316 commands. This happens automatically if you run XEmacs or if
317 window-system is nil. This variable lets you do the same
318 manually. You must set it before loading org.
320 Example: on Carbon Emacs 22 running graphically, with an external
321 keyboard on a Powerbook, the default way of setting M-left might
322 not work for either Alt or ESC. Setting this variable will make
323 it work for ESC."
324 :group 'org-startup
325 :type 'boolean)
327 (if (fboundp 'defvaralias)
328 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
330 (defcustom org-disputed-keys
331 '(([(shift up)] . [(meta p)])
332 ([(shift down)] . [(meta n)])
333 ([(shift left)] . [(meta -)])
334 ([(shift right)] . [(meta +)])
335 ([(control shift right)] . [(meta shift +)])
336 ([(control shift left)] . [(meta shift -)]))
337 "Keys for which Org-mode and other modes compete.
338 This is an alist, cars are the default keys, second element specifies
339 the alternative to use when `org-replace-disputed-keys' is t.
341 Keys can be specified in any syntax supported by `define-key'.
342 The value of this option takes effect only at Org-mode's startup,
343 therefore you'll have to restart Emacs to apply it after changing."
344 :group 'org-startup
345 :type 'alist)
347 (defun org-key (key)
348 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
349 Or return the original if not disputed."
350 (if org-replace-disputed-keys
351 (let* ((nkey (key-description key))
352 (x (org-find-if (lambda (x)
353 (equal (key-description (car x)) nkey))
354 org-disputed-keys)))
355 (if x (cdr x) key))
356 key))
358 (defun org-find-if (predicate seq)
359 (catch 'exit
360 (while seq
361 (if (funcall predicate (car seq))
362 (throw 'exit (car seq))
363 (pop seq)))))
365 (defun org-defkey (keymap key def)
366 "Define a key, possibly translated, as returned by `org-key'."
367 (define-key keymap (org-key key) def))
369 (defcustom org-ellipsis nil
370 "The ellipsis to use in the Org-mode outline.
371 When nil, just use the standard three dots. When a string, use that instead,
372 When a face, use the standard 3 dots, but with the specified face.
373 The change affects only Org-mode (which will then use its own display table).
374 Changing this requires executing `M-x org-mode' in a buffer to become
375 effective."
376 :group 'org-startup
377 :type '(choice (const :tag "Default" nil)
378 (face :tag "Face" :value org-warning)
379 (string :tag "String" :value "...#")))
381 (defvar org-display-table nil
382 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
384 (defgroup org-keywords nil
385 "Keywords in Org-mode."
386 :tag "Org Keywords"
387 :group 'org)
389 (defcustom org-deadline-string "DEADLINE:"
390 "String to mark deadline entries.
391 A deadline is this string, followed by a time stamp. Should be a word,
392 terminated by a colon. You can insert a schedule keyword and
393 a timestamp with \\[org-deadline].
394 Changes become only effective after restarting Emacs."
395 :group 'org-keywords
396 :type 'string)
398 (defcustom org-scheduled-string "SCHEDULED:"
399 "String to mark scheduled TODO entries.
400 A schedule is this string, followed by a time stamp. Should be a word,
401 terminated by a colon. You can insert a schedule keyword and
402 a timestamp with \\[org-schedule].
403 Changes become only effective after restarting Emacs."
404 :group 'org-keywords
405 :type 'string)
407 (defcustom org-closed-string "CLOSED:"
408 "String used as the prefix for timestamps logging closing a TODO entry."
409 :group 'org-keywords
410 :type 'string)
412 (defcustom org-clock-string "CLOCK:"
413 "String used as prefix for timestamps clocking work hours on an item."
414 :group 'org-keywords
415 :type 'string)
417 (defcustom org-comment-string "COMMENT"
418 "Entries starting with this keyword will never be exported.
419 An entry can be toggled between COMMENT and normal with
420 \\[org-toggle-comment].
421 Changes become only effective after restarting Emacs."
422 :group 'org-keywords
423 :type 'string)
425 (defcustom org-quote-string "QUOTE"
426 "Entries starting with this keyword will be exported in fixed-width font.
427 Quoting applies only to the text in the entry following the headline, and does
428 not extend beyond the next headline, even if that is lower level.
429 An entry can be toggled between QUOTE and normal with
430 \\[org-toggle-fixed-width-section]."
431 :group 'org-keywords
432 :type 'string)
434 (defconst org-repeat-re
435 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
436 "Regular expression for specifying repeated events.
437 After a match, group 1 contains the repeat expression.")
439 (defgroup org-structure nil
440 "Options concerning the general structure of Org-mode files."
441 :tag "Org Structure"
442 :group 'org)
444 (defgroup org-reveal-location nil
445 "Options about how to make context of a location visible."
446 :tag "Org Reveal Location"
447 :group 'org-structure)
449 (defconst org-context-choice
450 '(choice
451 (const :tag "Always" t)
452 (const :tag "Never" nil)
453 (repeat :greedy t :tag "Individual contexts"
454 (cons
455 (choice :tag "Context"
456 (const agenda)
457 (const org-goto)
458 (const occur-tree)
459 (const tags-tree)
460 (const link-search)
461 (const mark-goto)
462 (const bookmark-jump)
463 (const isearch)
464 (const default))
465 (boolean))))
466 "Contexts for the reveal options.")
468 (defcustom org-show-hierarchy-above '((default . t))
469 "Non-nil means, show full hierarchy when revealing a location.
470 Org-mode often shows locations in an org-mode file which might have
471 been invisible before. When this is set, the hierarchy of headings
472 above the exposed location is shown.
473 Turning this off for example for sparse trees makes them very compact.
474 Instead of t, this can also be an alist specifying this option for different
475 contexts. Valid contexts are
476 agenda when exposing an entry from the agenda
477 org-goto when using the command `org-goto' on key C-c C-j
478 occur-tree when using the command `org-occur' on key C-c /
479 tags-tree when constructing a sparse tree based on tags matches
480 link-search when exposing search matches associated with a link
481 mark-goto when exposing the jump goal of a mark
482 bookmark-jump when exposing a bookmark location
483 isearch when exiting from an incremental search
484 default default for all contexts not set explicitly"
485 :group 'org-reveal-location
486 :type org-context-choice)
488 (defcustom org-show-following-heading '((default . nil))
489 "Non-nil means, show following heading when revealing a location.
490 Org-mode often shows locations in an org-mode file which might have
491 been invisible before. When this is set, the heading following the
492 match is shown.
493 Turning this off for example for sparse trees makes them very compact,
494 but makes it harder to edit the location of the match. In such a case,
495 use the command \\[org-reveal] to show more context.
496 Instead of t, this can also be an alist specifying this option for different
497 contexts. See `org-show-hierarchy-above' for valid contexts."
498 :group 'org-reveal-location
499 :type org-context-choice)
501 (defcustom org-show-siblings '((default . nil) (isearch t))
502 "Non-nil means, show all sibling heading when revealing a location.
503 Org-mode often shows locations in an org-mode file which might have
504 been invisible before. When this is set, the sibling of the current entry
505 heading are all made visible. If `org-show-hierarchy-above' is t,
506 the same happens on each level of the hierarchy above the current entry.
508 By default this is on for the isearch context, off for all other contexts.
509 Turning this off for example for sparse trees makes them very compact,
510 but makes it harder to edit the location of the match. In such a case,
511 use the command \\[org-reveal] to show more context.
512 Instead of t, this can also be an alist specifying this option for different
513 contexts. See `org-show-hierarchy-above' for valid contexts."
514 :group 'org-reveal-location
515 :type org-context-choice)
517 (defcustom org-show-entry-below '((default . nil))
518 "Non-nil means, show the entry below a headline when revealing a location.
519 Org-mode often shows locations in an org-mode file which might have
520 been invisible before. When this is set, the text below the headline that is
521 exposed is also shown.
523 By default this is off for all contexts.
524 Instead of t, this can also be an alist specifying this option for different
525 contexts. See `org-show-hierarchy-above' for valid contexts."
526 :group 'org-reveal-location
527 :type org-context-choice)
529 (defcustom org-indirect-buffer-display 'other-window
530 "How should indirect tree buffers be displayed?
531 This applies to indirect buffers created with the commands
532 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
533 Valid values are:
534 current-window Display in the current window
535 other-window Just display in another window.
536 dedicated-frame Create one new frame, and re-use it each time.
537 new-frame Make a new frame each time. Note that in this case
538 previously-made indirect buffers are kept, and you need to
539 kill these buffers yourself."
540 :group 'org-structure
541 :group 'org-agenda-windows
542 :type '(choice
543 (const :tag "In current window" current-window)
544 (const :tag "In current frame, other window" other-window)
545 (const :tag "Each time a new frame" new-frame)
546 (const :tag "One dedicated frame" dedicated-frame)))
548 (defgroup org-cycle nil
549 "Options concerning visibility cycling in Org-mode."
550 :tag "Org Cycle"
551 :group 'org-structure)
553 (defcustom org-cycle-max-level nil
554 "Maximum level which should still be subject to visibility cycling.
555 Levels higher than this will, for cycling, be treated as text, not a headline.
556 When `org-odd-levels-only' is set, a value of N in this variable actually
557 means 2N-1 stars as the limiting headline.
558 When nil, cycle all levels.
559 Note that the limiting level of cycling is also influenced by
560 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
561 `org-inlinetask-min-level' is, cycling will be limited to levels one less
562 than its value."
563 :group 'org-cycle
564 :type '(choice
565 (const :tag "No limit" nil)
566 (integer :tag "Maximum level")))
568 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
569 "Names of drawers. Drawers are not opened by cycling on the headline above.
570 Drawers only open with a TAB on the drawer line itself. A drawer looks like
571 this:
572 :DRAWERNAME:
573 .....
574 :END:
575 The drawer \"PROPERTIES\" is special for capturing properties through
576 the property API.
578 Drawers can be defined on the per-file basis with a line like:
580 #+DRAWERS: HIDDEN STATE PROPERTIES"
581 :group 'org-structure
582 :group 'org-cycle
583 :type '(repeat (string :tag "Drawer Name")))
585 (defcustom org-cycle-global-at-bob nil
586 "Cycle globally if cursor is at beginning of buffer and not at a headline.
587 This makes it possible to do global cycling without having to use S-TAB or
588 C-u TAB. For this special case to work, the first line of the buffer
589 must not be a headline - it may be empty or some other text. When used in
590 this way, `org-cycle-hook' is disables temporarily, to make sure the
591 cursor stays at the beginning of the buffer.
592 When this option is nil, don't do anything special at the beginning
593 of the buffer."
594 :group 'org-cycle
595 :type 'boolean)
597 (defcustom org-cycle-emulate-tab t
598 "Where should `org-cycle' emulate TAB.
599 nil Never
600 white Only in completely white lines
601 whitestart Only at the beginning of lines, before the first non-white char
602 t Everywhere except in headlines
603 exc-hl-bol Everywhere except at the start of a headline
604 If TAB is used in a place where it does not emulate TAB, the current subtree
605 visibility is cycled."
606 :group 'org-cycle
607 :type '(choice (const :tag "Never" nil)
608 (const :tag "Only in completely white lines" white)
609 (const :tag "Before first char in a line" whitestart)
610 (const :tag "Everywhere except in headlines" t)
611 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
614 (defcustom org-cycle-separator-lines 2
615 "Number of empty lines needed to keep an empty line between collapsed trees.
616 If you leave an empty line between the end of a subtree and the following
617 headline, this empty line is hidden when the subtree is folded.
618 Org-mode will leave (exactly) one empty line visible if the number of
619 empty lines is equal or larger to the number given in this variable.
620 So the default 2 means, at least 2 empty lines after the end of a subtree
621 are needed to produce free space between a collapsed subtree and the
622 following headline.
624 Special case: when 0, never leave empty lines in collapsed view."
625 :group 'org-cycle
626 :type 'integer)
627 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
629 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
630 org-cycle-hide-drawers
631 org-cycle-show-empty-lines
632 org-optimize-window-after-visibility-change)
633 "Hook that is run after `org-cycle' has changed the buffer visibility.
634 The function(s) in this hook must accept a single argument which indicates
635 the new state that was set by the most recent `org-cycle' command. The
636 argument is a symbol. After a global state change, it can have the values
637 `overview', `content', or `all'. After a local state change, it can have
638 the values `folded', `children', or `subtree'."
639 :group 'org-cycle
640 :type 'hook)
642 (defgroup org-edit-structure nil
643 "Options concerning structure editing in Org-mode."
644 :tag "Org Edit Structure"
645 :group 'org-structure)
647 (defcustom org-odd-levels-only nil
648 "Non-nil means, skip even levels and only use odd levels for the outline.
649 This has the effect that two stars are being added/taken away in
650 promotion/demotion commands. It also influences how levels are
651 handled by the exporters.
652 Changing it requires restart of `font-lock-mode' to become effective
653 for fontification also in regions already fontified.
654 You may also set this on a per-file basis by adding one of the following
655 lines to the buffer:
657 #+STARTUP: odd
658 #+STARTUP: oddeven"
659 :group 'org-edit-structure
660 :group 'org-font-lock
661 :type 'boolean)
663 (defcustom org-adapt-indentation t
664 "Non-nil means, adapt indentation when promoting and demoting.
665 When this is set and the *entire* text in an entry is indented, the
666 indentation is increased by one space in a demotion command, and
667 decreased by one in a promotion command. If any line in the entry
668 body starts at column 0, indentation is not changed at all."
669 :group 'org-edit-structure
670 :type 'boolean)
672 (defcustom org-special-ctrl-a/e nil
673 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
675 When t, `C-a' will bring back the cursor to the beginning of the
676 headline text, i.e. after the stars and after a possible TODO keyword.
677 In an item, this will be the position after the bullet.
678 When the cursor is already at that position, another `C-a' will bring
679 it to the beginning of the line.
681 `C-e' will jump to the end of the headline, ignoring the presence of tags
682 in the headline. A second `C-e' will then jump to the true end of the
683 line, after any tags.
685 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
686 and only a directly following, identical keypress will bring the cursor
687 to the special positions.
689 This may also be a cons cell where the behavior for `C-a' and `C-e' is
690 set separately."
691 :group 'org-edit-structure
692 :type '(choice
693 (const :tag "off" nil)
694 (const :tag "after stars/bullet and before tags first" t)
695 (const :tag "true line boundary first" reversed)
696 (cons :tag "Set C-a and C-e separately"
697 (choice :tag "Special C-a"
698 (const :tag "off" nil)
699 (const :tag "after stars/bullet first" t)
700 (const :tag "before stars/bullet first" reversed))
701 (choice :tag "Special C-e"
702 (const :tag "off" nil)
703 (const :tag "before tags first" t)
704 (const :tag "after tags first" reversed)))))
705 (if (fboundp 'defvaralias)
706 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
708 (defcustom org-special-ctrl-k nil
709 "Non-nil means `C-k' will behave specially in headlines.
710 When nil, `C-k' will call the default `kill-line' command.
711 When t, the following will happen while the cursor is in the headline:
713 - When the cursor is at the beginning of a headline, kill the entire
714 line and possible the folded subtree below the line.
715 - When in the middle of the headline text, kill the headline up to the tags.
716 - When after the headline text, kill the tags."
717 :group 'org-edit-structure
718 :type 'boolean)
720 (defcustom org-yank-folded-subtrees t
721 "Non-nil means, when yanking subtrees, fold them.
722 If the kill is a single subtree, or a sequence of subtrees, i.e. if
723 it starts with a heading and all other headings in it are either children
724 or siblings, then fold all the subtrees. However, do this only if no
725 text after the yank would be swallowed into a folded tree by this action."
726 :group 'org-edit-structure
727 :type 'boolean)
729 (defcustom org-yank-adjusted-subtrees nil
730 "Non-nil means, when yanking subtrees, adjust the level.
731 With this setting, `org-paste-subtree' is used to insert the subtree, see
732 this function for details."
733 :group 'org-edit-structure
734 :type 'boolean)
736 (defcustom org-M-RET-may-split-line '((default . t))
737 "Non-nil means, M-RET will split the line at the cursor position.
738 When nil, it will go to the end of the line before making a
739 new line.
740 You may also set this option in a different way for different
741 contexts. Valid contexts are:
743 headline when creating a new headline
744 item when creating a new item
745 table in a table field
746 default the value to be used for all contexts not explicitly
747 customized"
748 :group 'org-structure
749 :group 'org-table
750 :type '(choice
751 (const :tag "Always" t)
752 (const :tag "Never" nil)
753 (repeat :greedy t :tag "Individual contexts"
754 (cons
755 (choice :tag "Context"
756 (const headline)
757 (const item)
758 (const table)
759 (const default))
760 (boolean)))))
763 (defcustom org-insert-heading-respect-content nil
764 "Non-nil means, insert new headings after the current subtree.
765 When nil, the new heading is created directly after the current line.
766 The commands \\[org-insert-heading-respect-content] and
767 \\[org-insert-todo-heading-respect-content] turn this variable on
768 for the duration of the command."
769 :group 'org-structure
770 :type 'boolean)
772 (defcustom org-blank-before-new-entry '((heading . auto)
773 (plain-list-item . auto))
774 "Should `org-insert-heading' leave a blank line before new heading/item?
775 The value is an alist, with `heading' and `plain-list-item' as car,
776 and a boolean flag as cdr. For plain lists, if the variable
777 `org-empty-line-terminates-plain-lists' is set, the setting here
778 is ignored and no empty line is inserted, to keep the list in tact."
779 :group 'org-edit-structure
780 :type '(list
781 (cons (const heading)
782 (choice (const :tag "Never" nil)
783 (const :tag "Always" t)
784 (const :tag "Auto" auto)))
785 (cons (const plain-list-item)
786 (choice (const :tag "Never" nil)
787 (const :tag "Always" t)
788 (const :tag "Auto" auto)))))
790 (defcustom org-insert-heading-hook nil
791 "Hook being run after inserting a new heading."
792 :group 'org-edit-structure
793 :type 'hook)
795 (defcustom org-enable-fixed-width-editor t
796 "Non-nil means, lines starting with \":\" are treated as fixed-width.
797 This currently only means, they are never auto-wrapped.
798 When nil, such lines will be treated like ordinary lines.
799 See also the QUOTE keyword."
800 :group 'org-edit-structure
801 :type 'boolean)
803 (defcustom org-edit-src-region-extra nil
804 "Additional regexps to identify regions for editing with `org-edit-src-code'.
805 For examples see the function `org-edit-src-find-region-and-lang'.
806 The regular expression identifying the begin marker should end with a newline,
807 and the regexp marking the end line should start with a newline, to make sure
808 there are kept outside the narrowed region."
809 :group 'org-edit-structure
810 :type '(repeat
811 (list
812 (regexp :tag "begin regexp")
813 (regexp :tag "end regexp")
814 (choice :tag "language"
815 (string :tag "specify")
816 (integer :tag "from match group")
817 (const :tag "from `lang' element")
818 (const :tag "from `style' element")))))
820 (defcustom org-coderef-label-format "(ref:%s)"
821 "The default coderef format.
822 This format string will be used to search for coderef labels in literal
823 examples (EXAMPLE and SRC blocks). The format can be overwritten
824 an individual literal example with the -f option, like
826 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
828 #+END_SRC
830 If you want to use this for HTML export, make sure that the format does
831 not introduce special font-locking, and avoid the HTML special
832 characters `<', `>', and `&'. The reason for this restriction is that
833 the labels are searched for only after htmlize has done its job."
834 :group 'org-edit-structure ; FIXME this is not in the right group
835 :type 'string)
837 (defcustom org-edit-fixed-width-region-mode 'artist-mode
838 "The mode that should be used to edit fixed-width regions.
839 These are the regions where each line starts with a colon."
840 :group 'org-edit-structure
841 :type '(choice
842 (const artist-mode)
843 (const picture-mode)
844 (const fundamental-mode)
845 (function :tag "Other (specify)")))
847 (defcustom org-goto-auto-isearch t
848 "Non-nil means, typing characters in org-goto starts incremental search."
849 :group 'org-edit-structure
850 :type 'boolean)
852 (defgroup org-sparse-trees nil
853 "Options concerning sparse trees in Org-mode."
854 :tag "Org Sparse Trees"
855 :group 'org-structure)
857 (defcustom org-highlight-sparse-tree-matches t
858 "Non-nil means, highlight all matches that define a sparse tree.
859 The highlights will automatically disappear the next time the buffer is
860 changed by an edit command."
861 :group 'org-sparse-trees
862 :type 'boolean)
864 (defcustom org-remove-highlights-with-change t
865 "Non-nil means, any change to the buffer will remove temporary highlights.
866 Such highlights are created by `org-occur' and `org-clock-display'.
867 When nil, `C-c C-c needs to be used to get rid of the highlights.
868 The highlights created by `org-preview-latex-fragment' always need
869 `C-c C-c' to be removed."
870 :group 'org-sparse-trees
871 :group 'org-time
872 :type 'boolean)
875 (defcustom org-occur-hook '(org-first-headline-recenter)
876 "Hook that is run after `org-occur' has constructed a sparse tree.
877 This can be used to recenter the window to show as much of the structure
878 as possible."
879 :group 'org-sparse-trees
880 :type 'hook)
882 (defgroup org-imenu-and-speedbar nil
883 "Options concerning imenu and speedbar in Org-mode."
884 :tag "Org Imenu and Speedbar"
885 :group 'org-structure)
887 (defcustom org-imenu-depth 2
888 "The maximum level for Imenu access to Org-mode headlines.
889 This also applied for speedbar access."
890 :group 'org-imenu-and-speedbar
891 :type 'integer)
893 (defgroup org-table nil
894 "Options concerning tables in Org-mode."
895 :tag "Org Table"
896 :group 'org)
898 (defcustom org-enable-table-editor 'optimized
899 "Non-nil means, lines starting with \"|\" are handled by the table editor.
900 When nil, such lines will be treated like ordinary lines.
902 When equal to the symbol `optimized', the table editor will be optimized to
903 do the following:
904 - Automatic overwrite mode in front of whitespace in table fields.
905 This makes the structure of the table stay in tact as long as the edited
906 field does not exceed the column width.
907 - Minimize the number of realigns. Normally, the table is aligned each time
908 TAB or RET are pressed to move to another field. With optimization this
909 happens only if changes to a field might have changed the column width.
910 Optimization requires replacing the functions `self-insert-command',
911 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
912 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
913 very good at guessing when a re-align will be necessary, but you can always
914 force one with \\[org-ctrl-c-ctrl-c].
916 If you would like to use the optimized version in Org-mode, but the
917 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
919 This variable can be used to turn on and off the table editor during a session,
920 but in order to toggle optimization, a restart is required.
922 See also the variable `org-table-auto-blank-field'."
923 :group 'org-table
924 :type '(choice
925 (const :tag "off" nil)
926 (const :tag "on" t)
927 (const :tag "on, optimized" optimized)))
929 (defcustom org-self-insert-cluster-for-undo t
930 "Non-nil means cluster self-insert commands for undo when possible.
931 If this is set, then, like in the Emacs command loop, 20 consequtive
932 characters will be undone together.
933 This is configurable, because there is some impact on typing performance."
934 :group 'org-table
935 :type 'boolean)
937 (defcustom org-table-tab-recognizes-table.el t
938 "Non-nil means, TAB will automatically notice a table.el table.
939 When it sees such a table, it moves point into it and - if necessary -
940 calls `table-recognize-table'."
941 :group 'org-table-editing
942 :type 'boolean)
944 (defgroup org-link nil
945 "Options concerning links in Org-mode."
946 :tag "Org Link"
947 :group 'org)
949 (defvar org-link-abbrev-alist-local nil
950 "Buffer-local version of `org-link-abbrev-alist', which see.
951 The value of this is taken from the #+LINK lines.")
952 (make-variable-buffer-local 'org-link-abbrev-alist-local)
954 (defcustom org-link-abbrev-alist nil
955 "Alist of link abbreviations.
956 The car of each element is a string, to be replaced at the start of a link.
957 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
958 links in Org-mode buffers can have an optional tag after a double colon, e.g.
960 [[linkkey:tag][description]]
962 The 'linkkey' must be a word word, starting with a letter, followed
963 by letters, numbers, '-' or '_'.
965 If REPLACE is a string, the tag will simply be appended to create the link.
966 If the string contains \"%s\", the tag will be inserted there. Alternatively,
967 the placeholder \"%h\" will cause a url-encoded version of the tag to
968 be inserted at that point (see the function `url-hexify-string').
970 REPLACE may also be a function that will be called with the tag as the
971 only argument to create the link, which should be returned as a string.
973 See the manual for examples."
974 :group 'org-link
975 :type '(repeat
976 (cons
977 (string :tag "Protocol")
978 (choice
979 (string :tag "Format")
980 (function)))))
982 (defcustom org-descriptive-links t
983 "Non-nil means, hide link part and only show description of bracket links.
984 Bracket links are like [[link][description]]. This variable sets the initial
985 state in new org-mode buffers. The setting can then be toggled on a
986 per-buffer basis from the Org->Hyperlinks menu."
987 :group 'org-link
988 :type 'boolean)
990 (defcustom org-link-file-path-type 'adaptive
991 "How the path name in file links should be stored.
992 Valid values are:
994 relative Relative to the current directory, i.e. the directory of the file
995 into which the link is being inserted.
996 absolute Absolute path, if possible with ~ for home directory.
997 noabbrev Absolute path, no abbreviation of home directory.
998 adaptive Use relative path for files in the current directory and sub-
999 directories of it. For other files, use an absolute path."
1000 :group 'org-link
1001 :type '(choice
1002 (const relative)
1003 (const absolute)
1004 (const noabbrev)
1005 (const adaptive)))
1007 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1008 "Types of links that should be activated in Org-mode files.
1009 This is a list of symbols, each leading to the activation of a certain link
1010 type. In principle, it does not hurt to turn on most link types - there may
1011 be a small gain when turning off unused link types. The types are:
1013 bracket The recommended [[link][description]] or [[link]] links with hiding.
1014 angular Links in angular brackets that may contain whitespace like
1015 <bbdb:Carsten Dominik>.
1016 plain Plain links in normal text, no whitespace, like http://google.com.
1017 radio Text that is matched by a radio target, see manual for details.
1018 tag Tag settings in a headline (link to tag search).
1019 date Time stamps (link to calendar).
1020 footnote Footnote labels.
1022 Changing this variable requires a restart of Emacs to become effective."
1023 :group 'org-link
1024 :type '(set :greedy t
1025 (const :tag "Double bracket links (new style)" bracket)
1026 (const :tag "Angular bracket links (old style)" angular)
1027 (const :tag "Plain text links" plain)
1028 (const :tag "Radio target matches" radio)
1029 (const :tag "Tags" tag)
1030 (const :tag "Timestamps" date)
1031 (const :tag "Footnotes" footnote)))
1033 (defcustom org-make-link-description-function nil
1034 "Function to use to generate link descriptions from links. If
1035 nil the link location will be used. This function must take two
1036 parameters; the first is the link and the second the description
1037 org-insert-link has generated, and should return the description
1038 to use."
1039 :group 'org-link
1040 :type 'function)
1042 (defgroup org-link-store nil
1043 "Options concerning storing links in Org-mode."
1044 :tag "Org Store Link"
1045 :group 'org-link)
1047 (defcustom org-email-link-description-format "Email %c: %.30s"
1048 "Format of the description part of a link to an email or usenet message.
1049 The following %-escapes will be replaced by corresponding information:
1051 %F full \"From\" field
1052 %f name, taken from \"From\" field, address if no name
1053 %T full \"To\" field
1054 %t first name in \"To\" field, address if no name
1055 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1056 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1057 %s subject
1058 %m message-id.
1060 You may use normal field width specification between the % and the letter.
1061 This is for example useful to limit the length of the subject.
1063 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1064 :group 'org-link-store
1065 :type 'string)
1067 (defcustom org-from-is-user-regexp
1068 (let (r1 r2)
1069 (when (and user-mail-address (not (string= user-mail-address "")))
1070 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1071 (when (and user-full-name (not (string= user-full-name "")))
1072 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1073 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1074 "Regexp matched against the \"From:\" header of an email or usenet message.
1075 It should match if the message is from the user him/herself."
1076 :group 'org-link-store
1077 :type 'regexp)
1079 (defcustom org-link-to-org-use-id 'create-if-interactive
1080 "Non-nil means, storing a link to an Org file will use entry IDs.
1082 Note that before this variable is even considered, org-id must be loaded,
1083 to please customize `org-modules' and turn it on.
1085 The variable can have the following values:
1087 t Create an ID if needed to make a link to the current entry.
1089 create-if-interactive
1090 If `org-store-link' is called directly (interactively, as a user
1091 command), do create an ID to support the link. But when doing the
1092 job for remember, only use the ID if it already exists. The
1093 purpose of this setting is to avoid proliferation of unwanted
1094 IDs, just because you happen to be in an Org file when you
1095 call `org-remember' that automatically and preemptively
1096 creates a link. If you do want to get an ID link in a remember
1097 template to an entry not having an ID, create it first by
1098 explicitly creating a link to it, using `C-c C-l' first.
1100 use-existing
1101 Use existing ID, do not create one.
1103 nil Never use an ID to make a link, instead link using a text search for
1104 the headline text."
1105 :group 'org-link-store
1106 :type '(choice
1107 (const :tag "Create ID to make link" t)
1108 (const :tag "Create if string link interactively"
1109 'create-if-interactive)
1110 (const :tag "Only use existing" 'use-existing)
1111 (const :tag "Do not use ID to create link" nil)))
1113 (defcustom org-context-in-file-links t
1114 "Non-nil means, file links from `org-store-link' contain context.
1115 A search string will be added to the file name with :: as separator and
1116 used to find the context when the link is activated by the command
1117 `org-open-at-point'.
1118 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1119 negates this setting for the duration of the command."
1120 :group 'org-link-store
1121 :type 'boolean)
1123 (defcustom org-keep-stored-link-after-insertion nil
1124 "Non-nil means, keep link in list for entire session.
1126 The command `org-store-link' adds a link pointing to the current
1127 location to an internal list. These links accumulate during a session.
1128 The command `org-insert-link' can be used to insert links into any
1129 Org-mode file (offering completion for all stored links). When this
1130 option is nil, every link which has been inserted once using \\[org-insert-link]
1131 will be removed from the list, to make completing the unused links
1132 more efficient."
1133 :group 'org-link-store
1134 :type 'boolean)
1136 (defgroup org-link-follow nil
1137 "Options concerning following links in Org-mode."
1138 :tag "Org Follow Link"
1139 :group 'org-link)
1141 (defcustom org-link-translation-function nil
1142 "Function to translate links with different syntax to Org syntax.
1143 This can be used to translate links created for example by the Planner
1144 or emacs-wiki packages to Org syntax.
1145 The function must accept two parameters, a TYPE containing the link
1146 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1147 which is everything after the link protocol. It should return a cons
1148 with possibly modified values of type and path.
1149 Org contains a function for this, so if you set this variable to
1150 `org-translate-link-from-planner', you should be able follow many
1151 links created by planner."
1152 :group 'org-link-follow
1153 :type 'function)
1155 (defcustom org-follow-link-hook nil
1156 "Hook that is run after a link has been followed."
1157 :group 'org-link-follow
1158 :type 'hook)
1160 (defcustom org-tab-follows-link nil
1161 "Non-nil means, on links TAB will follow the link.
1162 Needs to be set before org.el is loaded.
1163 This really should not be used, it does not make sense, and the
1164 implementation is bad."
1165 :group 'org-link-follow
1166 :type 'boolean)
1168 (defcustom org-return-follows-link nil
1169 "Non-nil means, on links RET will follow the link.
1170 Needs to be set before org.el is loaded."
1171 :group 'org-link-follow
1172 :type 'boolean)
1174 (defcustom org-mouse-1-follows-link
1175 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1176 "Non-nil means, mouse-1 on a link will follow the link.
1177 A longer mouse click will still set point. Does not work on XEmacs.
1178 Needs to be set before org.el is loaded."
1179 :group 'org-link-follow
1180 :type 'boolean)
1182 (defcustom org-mark-ring-length 4
1183 "Number of different positions to be recorded in the ring
1184 Changing this requires a restart of Emacs to work correctly."
1185 :group 'org-link-follow
1186 :type 'integer)
1188 (defcustom org-link-frame-setup
1189 '((vm . vm-visit-folder-other-frame)
1190 (gnus . gnus-other-frame)
1191 (file . find-file-other-window))
1192 "Setup the frame configuration for following links.
1193 When following a link with Emacs, it may often be useful to display
1194 this link in another window or frame. This variable can be used to
1195 set this up for the different types of links.
1196 For VM, use any of
1197 `vm-visit-folder'
1198 `vm-visit-folder-other-frame'
1199 For Gnus, use any of
1200 `gnus'
1201 `gnus-other-frame'
1202 `org-gnus-no-new-news'
1203 For FILE, use any of
1204 `find-file'
1205 `find-file-other-window'
1206 `find-file-other-frame'
1207 For the calendar, use the variable `calendar-setup'.
1208 For BBDB, it is currently only possible to display the matches in
1209 another window."
1210 :group 'org-link-follow
1211 :type '(list
1212 (cons (const vm)
1213 (choice
1214 (const vm-visit-folder)
1215 (const vm-visit-folder-other-window)
1216 (const vm-visit-folder-other-frame)))
1217 (cons (const gnus)
1218 (choice
1219 (const gnus)
1220 (const gnus-other-frame)
1221 (const org-gnus-no-new-news)))
1222 (cons (const file)
1223 (choice
1224 (const find-file)
1225 (const find-file-other-window)
1226 (const find-file-other-frame)))))
1228 (defcustom org-display-internal-link-with-indirect-buffer nil
1229 "Non-nil means, use indirect buffer to display infile links.
1230 Activating internal links (from one location in a file to another location
1231 in the same file) normally just jumps to the location. When the link is
1232 activated with a C-u prefix (or with mouse-3), the link is displayed in
1233 another window. When this option is set, the other window actually displays
1234 an indirect buffer clone of the current buffer, to avoid any visibility
1235 changes to the current buffer."
1236 :group 'org-link-follow
1237 :type 'boolean)
1239 (defcustom org-open-non-existing-files nil
1240 "Non-nil means, `org-open-file' will open non-existing files.
1241 When nil, an error will be generated."
1242 :group 'org-link-follow
1243 :type 'boolean)
1245 (defcustom org-open-directory-means-index-dot-org nil
1246 "Non-nil means, a link to a directory really means to index.org.
1247 When nil, following a directory link will run dired or open a finder/explorer
1248 window on that directory."
1249 :group 'org-link-follow
1250 :type 'boolean)
1252 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1253 "Function and arguments to call for following mailto links.
1254 This is a list with the first element being a lisp function, and the
1255 remaining elements being arguments to the function. In string arguments,
1256 %a will be replaced by the address, and %s will be replaced by the subject
1257 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1258 :group 'org-link-follow
1259 :type '(choice
1260 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1261 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1262 (const :tag "message-mail" (message-mail "%a" "%s"))
1263 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1265 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1266 "Non-nil means, ask for confirmation before executing shell links.
1267 Shell links can be dangerous: just think about a link
1269 [[shell:rm -rf ~/*][Google Search]]
1271 This link would show up in your Org-mode document as \"Google Search\",
1272 but really it would remove your entire home directory.
1273 Therefore we advise against setting this variable to nil.
1274 Just change it to `y-or-n-p' if you want to confirm with a
1275 single keystroke rather than having to type \"yes\"."
1276 :group 'org-link-follow
1277 :type '(choice
1278 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1279 (const :tag "with y-or-n (faster)" y-or-n-p)
1280 (const :tag "no confirmation (dangerous)" nil)))
1282 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1283 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1284 Elisp links can be dangerous: just think about a link
1286 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1288 This link would show up in your Org-mode document as \"Google Search\",
1289 but really it would remove your entire home directory.
1290 Therefore we advise against setting this variable to nil.
1291 Just change it to `y-or-n-p' if you want to confirm with a
1292 single keystroke rather than having to type \"yes\"."
1293 :group 'org-link-follow
1294 :type '(choice
1295 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1296 (const :tag "with y-or-n (faster)" y-or-n-p)
1297 (const :tag "no confirmation (dangerous)" nil)))
1299 (defconst org-file-apps-defaults-gnu
1300 '((remote . emacs)
1301 (system . mailcap)
1302 (t . mailcap))
1303 "Default file applications on a UNIX or GNU/Linux system.
1304 See `org-file-apps'.")
1306 (defconst org-file-apps-defaults-macosx
1307 '((remote . emacs)
1308 (t . "open %s")
1309 (system . "open %s")
1310 ("ps.gz" . "gv %s")
1311 ("eps.gz" . "gv %s")
1312 ("dvi" . "xdvi %s")
1313 ("fig" . "xfig %s"))
1314 "Default file applications on a MacOS X system.
1315 The system \"open\" is known as a default, but we use X11 applications
1316 for some files for which the OS does not have a good default.
1317 See `org-file-apps'.")
1319 (defconst org-file-apps-defaults-windowsnt
1320 (list
1321 '(remote . emacs)
1322 (cons t
1323 (list (if (featurep 'xemacs)
1324 'mswindows-shell-execute
1325 'w32-shell-execute)
1326 "open" 'file))
1327 (cons 'system
1328 (list (if (featurep 'xemacs)
1329 'mswindows-shell-execute
1330 'w32-shell-execute)
1331 "open" 'file)))
1332 "Default file applications on a Windows NT system.
1333 The system \"open\" is used for most files.
1334 See `org-file-apps'.")
1336 (defcustom org-file-apps
1338 (auto-mode . emacs)
1339 ("\\.x?html?\\'" . default)
1340 ("\\.pdf\\'" . default)
1342 "External applications for opening `file:path' items in a document.
1343 Org-mode uses system defaults for different file types, but
1344 you can use this variable to set the application for a given file
1345 extension. The entries in this list are cons cells where the car identifies
1346 files and the cdr the corresponding command. Possible values for the
1347 file identifier are
1348 \"regex\" Regular expression matched against the file name. For backward
1349 compatibility, this can also be a string with only alphanumeric
1350 characters, which is then interpreted as an extension.
1351 `directory' Matches a directory
1352 `remote' Matches a remote file, accessible through tramp or efs.
1353 Remote files most likely should be visited through Emacs
1354 because external applications cannot handle such paths.
1355 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1356 so all files Emacs knows how to handle. Using this with
1357 command `emacs' will open most files in Emacs. Beware that this
1358 will also open html files inside Emacs, unless you add
1359 (\"html\" . default) to the list as well.
1360 t Default for files not matched by any of the other options.
1361 `system' The system command to open files, like `open' on Windows
1362 and Mac OS X, and mailcap under GNU/Linux. This is the command
1363 that will be selected if you call `C-c C-o' with a double
1364 `C-u C-u' prefix.
1366 Possible values for the command are:
1367 `emacs' The file will be visited by the current Emacs process.
1368 `default' Use the default application for this file type, which is the
1369 association for t in the list, most likely in the system-specific
1370 part.
1371 This can be used to overrule an unwanted setting in the
1372 system-specific variable.
1373 `system' Use the system command for opening files, like \"open\".
1374 This command is specified by the entry whose car is `system'.
1375 Most likely, the system-specific version of this variable
1376 does define this command, but you can overrule/replace it
1377 here.
1378 string A command to be executed by a shell; %s will be replaced
1379 by the path to the file.
1380 sexp A Lisp form which will be evaluated. The file path will
1381 be available in the Lisp variable `file'.
1382 For more examples, see the system specific constants
1383 `org-file-apps-defaults-macosx'
1384 `org-file-apps-defaults-windowsnt'
1385 `org-file-apps-defaults-gnu'."
1386 :group 'org-link-follow
1387 :type '(repeat
1388 (cons (choice :value ""
1389 (string :tag "Extension")
1390 (const :tag "System command to open files" system)
1391 (const :tag "Default for unrecognized files" t)
1392 (const :tag "Remote file" remote)
1393 (const :tag "Links to a directory" directory)
1394 (const :tag "Any files that have Emacs modes"
1395 auto-mode))
1396 (choice :value ""
1397 (const :tag "Visit with Emacs" emacs)
1398 (const :tag "Use default" default)
1399 (const :tag "Use the system command" system)
1400 (string :tag "Command")
1401 (sexp :tag "Lisp form")))))
1403 (defgroup org-refile nil
1404 "Options concerning refiling entries in Org-mode."
1405 :tag "Org Refile"
1406 :group 'org)
1408 (defcustom org-directory "~/org"
1409 "Directory with org files.
1410 This is just a default location to look for Org files. There is no need
1411 at all to put your files into this directory. It is only used in the
1412 following situations:
1414 1. When a remember template specifies a target file that is not an
1415 absolute path. The path will then be interpreted relative to
1416 `org-directory'
1417 2. When a remember note is filed away in an interactive way (when exiting the
1418 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1419 with `org-directory' as the default path."
1420 :group 'org-refile
1421 :group 'org-remember
1422 :type 'directory)
1424 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1425 "Default target for storing notes.
1426 Used by the hooks for remember.el. This can be a string, or nil to mean
1427 the value of `remember-data-file'.
1428 You can set this on a per-template basis with the variable
1429 `org-remember-templates'."
1430 :group 'org-refile
1431 :group 'org-remember
1432 :type '(choice
1433 (const :tag "Default from remember-data-file" nil)
1434 file))
1436 (defcustom org-goto-interface 'outline
1437 "The default interface to be used for `org-goto'.
1438 Allowed values are:
1439 outline The interface shows an outline of the relevant file
1440 and the correct heading is found by moving through
1441 the outline or by searching with incremental search.
1442 outline-path-completion Headlines in the current buffer are offered via
1443 completion. This is the interface also used by
1444 the refile command."
1445 :group 'org-refile
1446 :type '(choice
1447 (const :tag "Outline" outline)
1448 (const :tag "Outline-path-completion" outline-path-completion)))
1450 (defcustom org-goto-max-level 5
1451 "Maximum level to be considered when running org-goto with refile interface."
1452 :group 'org-refile
1453 :type 'integer)
1455 (defcustom org-reverse-note-order nil
1456 "Non-nil means, store new notes at the beginning of a file or entry.
1457 When nil, new notes will be filed to the end of a file or entry.
1458 This can also be a list with cons cells of regular expressions that
1459 are matched against file names, and values."
1460 :group 'org-remember
1461 :group 'org-refile
1462 :type '(choice
1463 (const :tag "Reverse always" t)
1464 (const :tag "Reverse never" nil)
1465 (repeat :tag "By file name regexp"
1466 (cons regexp boolean))))
1468 (defcustom org-refile-targets nil
1469 "Targets for refiling entries with \\[org-refile].
1470 This is list of cons cells. Each cell contains:
1471 - a specification of the files to be considered, either a list of files,
1472 or a symbol whose function or variable value will be used to retrieve
1473 a file name or a list of file names. If you use `org-agenda-files' for
1474 that, all agenda files will be scanned for targets. Nil means, consider
1475 headings in the current buffer.
1476 - A specification of how to find candidate refile targets. This may be
1477 any of:
1478 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1479 This tag has to be present in all target headlines, inheritance will
1480 not be considered.
1481 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1482 todo keyword.
1483 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1484 headlines that are refiling targets.
1485 - a cons cell (:level . N). Any headline of level N is considered a target.
1486 Note that, when `org-odd-levels-only' is set, level corresponds to
1487 order in hierarchy, not to the number of stars.
1488 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1489 Note that, when `org-odd-levels-only' is set, level corresponds to
1490 order in hierarchy, not to the number of stars.
1492 When this variable is nil, all top-level headlines in the current buffer
1493 are used, equivalent to the value `((nil . (:level . 1))'."
1494 :group 'org-refile
1495 :type '(repeat
1496 (cons
1497 (choice :value org-agenda-files
1498 (const :tag "All agenda files" org-agenda-files)
1499 (const :tag "Current buffer" nil)
1500 (function) (variable) (file))
1501 (choice :tag "Identify target headline by"
1502 (cons :tag "Specific tag" (const :value :tag) (string))
1503 (cons :tag "TODO keyword" (const :value :todo) (string))
1504 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1505 (cons :tag "Level number" (const :value :level) (integer))
1506 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1508 (defcustom org-refile-use-outline-path nil
1509 "Non-nil means, provide refile targets as paths.
1510 So a level 3 headline will be available as level1/level2/level3.
1511 When the value is `file', also include the file name (without directory)
1512 into the path. When `full-file-path', include the full file path."
1513 :group 'org-refile
1514 :type '(choice
1515 (const :tag "Not" nil)
1516 (const :tag "Yes" t)
1517 (const :tag "Start with file name" file)
1518 (const :tag "Start with full file path" full-file-path)))
1520 (defcustom org-outline-path-complete-in-steps t
1521 "Non-nil means, complete the outline path in hierarchical steps.
1522 When Org-mode uses the refile interface to select an outline path
1523 \(see variable `org-refile-use-outline-path'), the completion of
1524 the path can be done is a single go, or if can be done in steps down
1525 the headline hierarchy. Going in steps is probably the best if you
1526 do not use a special completion package like `ido' or `icicles'.
1527 However, when using these packages, going in one step can be very
1528 fast, while still showing the whole path to the entry."
1529 :group 'org-refile
1530 :type 'boolean)
1532 (defgroup org-todo nil
1533 "Options concerning TODO items in Org-mode."
1534 :tag "Org TODO"
1535 :group 'org)
1537 (defgroup org-progress nil
1538 "Options concerning Progress logging in Org-mode."
1539 :tag "Org Progress"
1540 :group 'org-time)
1542 (defvar org-todo-interpretation-widgets
1544 (:tag "Sequence (cycling hits every state)" sequence)
1545 (:tag "Type (cycling directly to DONE)" type))
1546 "The available interpretation symbols for customizing
1547 `org-todo-keywords'.
1548 Interested libraries should add to this list.")
1550 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1551 "List of TODO entry keyword sequences and their interpretation.
1552 \\<org-mode-map>This is a list of sequences.
1554 Each sequence starts with a symbol, either `sequence' or `type',
1555 indicating if the keywords should be interpreted as a sequence of
1556 action steps, or as different types of TODO items. The first
1557 keywords are states requiring action - these states will select a headline
1558 for inclusion into the global TODO list Org-mode produces. If one of
1559 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1560 signify that no further action is necessary. If \"|\" is not found,
1561 the last keyword is treated as the only DONE state of the sequence.
1563 The command \\[org-todo] cycles an entry through these states, and one
1564 additional state where no keyword is present. For details about this
1565 cycling, see the manual.
1567 TODO keywords and interpretation can also be set on a per-file basis with
1568 the special #+SEQ_TODO and #+TYP_TODO lines.
1570 Each keyword can optionally specify a character for fast state selection
1571 \(in combination with the variable `org-use-fast-todo-selection')
1572 and specifiers for state change logging, using the same syntax
1573 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1574 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1575 indicates to record a time stamp each time this state is selected.
1577 Each keyword may also specify if a timestamp or a note should be
1578 recorded when entering or leaving the state, by adding additional
1579 characters in the parenthesis after the keyword. This looks like this:
1580 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1581 record only the time of the state change. With X and Y being either
1582 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1583 Y when leaving the state if and only if the *target* state does not
1584 define X. You may omit any of the fast-selection key or X or /Y,
1585 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1587 For backward compatibility, this variable may also be just a list
1588 of keywords - in this case the interpretation (sequence or type) will be
1589 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1590 :group 'org-todo
1591 :group 'org-keywords
1592 :type '(choice
1593 (repeat :tag "Old syntax, just keywords"
1594 (string :tag "Keyword"))
1595 (repeat :tag "New syntax"
1596 (cons
1597 (choice
1598 :tag "Interpretation"
1599 ;;Quick and dirty way to see
1600 ;;`org-todo-interpretations'. This takes the
1601 ;;place of item arguments
1602 :convert-widget
1603 (lambda (widget)
1604 (widget-put widget
1605 :args (mapcar
1606 #'(lambda (x)
1607 (widget-convert
1608 (cons 'const x)))
1609 org-todo-interpretation-widgets))
1610 widget))
1611 (repeat
1612 (string :tag "Keyword"))))))
1614 (defvar org-todo-keywords-1 nil
1615 "All TODO and DONE keywords active in a buffer.")
1616 (make-variable-buffer-local 'org-todo-keywords-1)
1617 (defvar org-todo-keywords-for-agenda nil)
1618 (defvar org-done-keywords-for-agenda nil)
1619 (defvar org-todo-keyword-alist-for-agenda nil)
1620 (defvar org-tag-alist-for-agenda nil)
1621 (defvar org-agenda-contributing-files nil)
1622 (defvar org-not-done-keywords nil)
1623 (make-variable-buffer-local 'org-not-done-keywords)
1624 (defvar org-done-keywords nil)
1625 (make-variable-buffer-local 'org-done-keywords)
1626 (defvar org-todo-heads nil)
1627 (make-variable-buffer-local 'org-todo-heads)
1628 (defvar org-todo-sets nil)
1629 (make-variable-buffer-local 'org-todo-sets)
1630 (defvar org-todo-log-states nil)
1631 (make-variable-buffer-local 'org-todo-log-states)
1632 (defvar org-todo-kwd-alist nil)
1633 (make-variable-buffer-local 'org-todo-kwd-alist)
1634 (defvar org-todo-key-alist nil)
1635 (make-variable-buffer-local 'org-todo-key-alist)
1636 (defvar org-todo-key-trigger nil)
1637 (make-variable-buffer-local 'org-todo-key-trigger)
1639 (defcustom org-todo-interpretation 'sequence
1640 "Controls how TODO keywords are interpreted.
1641 This variable is in principle obsolete and is only used for
1642 backward compatibility, if the interpretation of todo keywords is
1643 not given already in `org-todo-keywords'. See that variable for
1644 more information."
1645 :group 'org-todo
1646 :group 'org-keywords
1647 :type '(choice (const sequence)
1648 (const type)))
1650 (defcustom org-use-fast-todo-selection t
1651 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1652 This variable describes if and under what circumstances the cycling
1653 mechanism for TODO keywords will be replaced by a single-key, direct
1654 selection scheme.
1656 When nil, fast selection is never used.
1658 When the symbol `prefix', it will be used when `org-todo' is called with
1659 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1660 in an agenda buffer.
1662 When t, fast selection is used by default. In this case, the prefix
1663 argument forces cycling instead.
1665 In all cases, the special interface is only used if access keys have actually
1666 been assigned by the user, i.e. if keywords in the configuration are followed
1667 by a letter in parenthesis, like TODO(t)."
1668 :group 'org-todo
1669 :type '(choice
1670 (const :tag "Never" nil)
1671 (const :tag "By default" t)
1672 (const :tag "Only with C-u C-c C-t" prefix)))
1674 (defcustom org-provide-todo-statistics t
1675 "Non-nil means, update todo statistics after insert and toggle.
1676 When this is set, todo statistics is updated in the parent of the current
1677 entry each time a todo state is changed."
1678 :group 'org-todo
1679 :type 'boolean)
1681 (defcustom org-after-todo-state-change-hook nil
1682 "Hook which is run after the state of a TODO item was changed.
1683 The new state (a string with a TODO keyword, or nil) is available in the
1684 Lisp variable `state'."
1685 :group 'org-todo
1686 :type 'hook)
1688 (defvar org-blocker-hook nil
1689 "Hook for functions that are allowed to block a state change.
1691 Each function gets as its single argument a property list, see
1692 `org-trigger-hook' for more information about this list.
1694 If any of the functions in this hook returns nil, the state change
1695 is blocked.")
1697 (defvar org-trigger-hook nil
1698 "Hook for functions that are triggered by a state change.
1700 Each function gets as its single argument a property list with at least
1701 the following elements:
1703 (:type type-of-change :position pos-at-entry-start
1704 :from old-state :to new-state)
1706 Depending on the type, more properties may be present.
1708 This mechanism is currently implemented for:
1710 TODO state changes
1711 ------------------
1712 :type todo-state-change
1713 :from previous state (keyword as a string), or nil, or a symbol
1714 'todo' or 'done', to indicate the general type of state.
1715 :to new state, like in :from")
1717 (defcustom org-enforce-todo-dependencies nil
1718 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1719 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1720 be blocked if any prior sibling is not yet done.
1721 This variable needs to be set before org.el is loaded, and you need to
1722 restart Emacs after a change to make the change effective. The only way
1723 to change is while Emacs is running is through the customize interface."
1724 :set (lambda (var val)
1725 (set var val)
1726 (if val
1727 (add-hook 'org-blocker-hook
1728 'org-block-todo-from-children-or-siblings)
1729 (remove-hook 'org-blocker-hook
1730 'org-block-todo-from-children-or-siblings)))
1731 :group 'org-todo
1732 :type 'boolean)
1734 (defcustom org-enforce-todo-checkbox-dependencies nil
1735 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1736 When this is nil, checkboxes have no influence on switching TODO states.
1737 When non-nil, you first need to check off all check boxes before the TODO
1738 entry can be switched to DONE.
1739 This variable needs to be set before org.el is loaded, and you need to
1740 restart Emacs after a change to make the change effective. The only way
1741 to change is while Emacs is running is through the customize interface."
1742 :set (lambda (var val)
1743 (set var val)
1744 (if val
1745 (add-hook 'org-blocker-hook
1746 'org-block-todo-from-checkboxes)
1747 (remove-hook 'org-blocker-hook
1748 'org-block-todo-from-checkboxes)))
1749 :group 'org-todo
1750 :type 'boolean)
1752 (defcustom org-todo-state-tags-triggers nil
1753 "Tag changes that should be triggered by TODO state changes.
1754 This is a list. Each entry is
1756 (state-change (tag . flag) .......)
1758 State-change can be a string with a state, and empty string to indicate the
1759 state that has no TODO keyword, or it can be one of the symbols `todo'
1760 or `done', meaning any not-done or done state, respectively."
1761 :group 'org-todo
1762 :group 'org-tags
1763 :type '(repeat
1764 (cons (choice :tag "When changing to"
1765 (const :tag "Not-done state" todo)
1766 (const :tag "Done state" done)
1767 (string :tag "State"))
1768 (repeat
1769 (cons :tag "Tag action"
1770 (string :tag "Tag")
1771 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1773 (defcustom org-log-done nil
1774 "Information to record when a task moves to the DONE state.
1776 Possible values are:
1778 nil Don't add anything, just change the keyword
1779 time Add a time stamp to the task
1780 note Prompt a closing note and add it with template `org-log-note-headings'
1782 This option can also be set with on a per-file-basis with
1784 #+STARTUP: nologdone
1785 #+STARTUP: logdone
1786 #+STARTUP: lognotedone
1788 You can have local logging settings for a subtree by setting the LOGGING
1789 property to one or more of these keywords."
1790 :group 'org-todo
1791 :group 'org-progress
1792 :type '(choice
1793 (const :tag "No logging" nil)
1794 (const :tag "Record CLOSED timestamp" time)
1795 (const :tag "Record CLOSED timestamp with closing note." note)))
1797 ;; Normalize old uses of org-log-done.
1798 (cond
1799 ((eq org-log-done t) (setq org-log-done 'time))
1800 ((and (listp org-log-done) (memq 'done org-log-done))
1801 (setq org-log-done 'note)))
1803 (defcustom org-log-note-clock-out nil
1804 "Non-nil means, record a note when clocking out of an item.
1805 This can also be configured on a per-file basis by adding one of
1806 the following lines anywhere in the buffer:
1808 #+STARTUP: lognoteclock-out
1809 #+STARTUP: nolognoteclock-out"
1810 :group 'org-todo
1811 :group 'org-progress
1812 :type 'boolean)
1814 (defcustom org-log-done-with-time t
1815 "Non-nil means, the CLOSED time stamp will contain date and time.
1816 When nil, only the date will be recorded."
1817 :group 'org-progress
1818 :type 'boolean)
1820 (defcustom org-log-note-headings
1821 '((done . "CLOSING NOTE %t")
1822 (state . "State %-12s from %-12S %t")
1823 (note . "Note taken on %t")
1824 (clock-out . ""))
1825 "Headings for notes added to entries.
1826 The value is an alist, with the car being a symbol indicating the note
1827 context, and the cdr is the heading to be used. The heading may also be the
1828 empty string.
1829 %t in the heading will be replaced by a time stamp.
1830 %s will be replaced by the new TODO state, in double quotes.
1831 %S will be replaced by the old TODO state, in double quotes.
1832 %u will be replaced by the user name.
1833 %U will be replaced by the full user name."
1834 :group 'org-todo
1835 :group 'org-progress
1836 :type '(list :greedy t
1837 (cons (const :tag "Heading when closing an item" done) string)
1838 (cons (const :tag
1839 "Heading when changing todo state (todo sequence only)"
1840 state) string)
1841 (cons (const :tag "Heading when just taking a note" note) string)
1842 (cons (const :tag "Heading when clocking out" clock-out) string)))
1844 (unless (assq 'note org-log-note-headings)
1845 (push '(note . "%t") org-log-note-headings))
1847 (defcustom org-log-into-drawer nil
1848 "Non-nil means, insert state change notes and time stamps into a drawer.
1849 When nil, state changes notes will be inserted after the headline and
1850 any scheduling and clock lines, but not inside a drawer.
1852 The value of this variable should be the name of the drawer to use.
1853 LOGBOOK is proposed at the default drawer for this purpose, you can
1854 also set this to a string to define the drawer of your choice.
1856 A value of t is also allowed, representing \"LOGBOOK\".
1858 If this variable is set, `org-log-state-notes-insert-after-drawers'
1859 will be ignored."
1860 :group 'org-todo
1861 :group 'org-progress
1862 :type '(choice
1863 (const :tag "Not into a drawer" nil)
1864 (const :tag "LOGBOOK" t)
1865 (string :tag "Other")))
1867 (if (fboundp 'defvaralias)
1868 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1870 (defcustom org-log-state-notes-insert-after-drawers nil
1871 "Non-nil means, insert state change notes after any drawers in entry.
1872 Only the drawers that *immediately* follow the headline and the
1873 deadline/scheduled line are skipped.
1874 When nil, insert notes right after the heading and perhaps the line
1875 with deadline/scheduling if present.
1877 This variable will have no effect if `org-log-into-drawer' is
1878 set."
1879 :group 'org-todo
1880 :group 'org-progress
1881 :type 'boolean)
1883 (defcustom org-log-states-order-reversed t
1884 "Non-nil means, the latest state change note will be directly after heading.
1885 When nil, the notes will be orderer according to time."
1886 :group 'org-todo
1887 :group 'org-progress
1888 :type 'boolean)
1890 (defcustom org-log-repeat 'time
1891 "Non-nil means, record moving through the DONE state when triggering repeat.
1892 An auto-repeating tasks is immediately switched back to TODO when marked
1893 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1894 the TODO keyword definition, or recording a closing note by setting
1895 `org-log-done', there will be no record of the task moving through DONE.
1896 This variable forces taking a note anyway. Possible values are:
1898 nil Don't force a record
1899 time Record a time stamp
1900 note Record a note
1902 This option can also be set with on a per-file-basis with
1904 #+STARTUP: logrepeat
1905 #+STARTUP: lognoterepeat
1906 #+STARTUP: nologrepeat
1908 You can have local logging settings for a subtree by setting the LOGGING
1909 property to one or more of these keywords."
1910 :group 'org-todo
1911 :group 'org-progress
1912 :type '(choice
1913 (const :tag "Don't force a record" nil)
1914 (const :tag "Force recording the DONE state" time)
1915 (const :tag "Force recording a note with the DONE state" note)))
1918 (defgroup org-priorities nil
1919 "Priorities in Org-mode."
1920 :tag "Org Priorities"
1921 :group 'org-todo)
1923 (defcustom org-highest-priority ?A
1924 "The highest priority of TODO items. A character like ?A, ?B etc.
1925 Must have a smaller ASCII number than `org-lowest-priority'."
1926 :group 'org-priorities
1927 :type 'character)
1929 (defcustom org-lowest-priority ?C
1930 "The lowest priority of TODO items. A character like ?A, ?B etc.
1931 Must have a larger ASCII number than `org-highest-priority'."
1932 :group 'org-priorities
1933 :type 'character)
1935 (defcustom org-default-priority ?B
1936 "The default priority of TODO items.
1937 This is the priority an item get if no explicit priority is given."
1938 :group 'org-priorities
1939 :type 'character)
1941 (defcustom org-priority-start-cycle-with-default t
1942 "Non-nil means, start with default priority when starting to cycle.
1943 When this is nil, the first step in the cycle will be (depending on the
1944 command used) one higher or lower that the default priority."
1945 :group 'org-priorities
1946 :type 'boolean)
1948 (defgroup org-time nil
1949 "Options concerning time stamps and deadlines in Org-mode."
1950 :tag "Org Time"
1951 :group 'org)
1953 (defcustom org-insert-labeled-timestamps-at-point nil
1954 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1955 When nil, these labeled time stamps are forces into the second line of an
1956 entry, just after the headline. When scheduling from the global TODO list,
1957 the time stamp will always be forced into the second line."
1958 :group 'org-time
1959 :type 'boolean)
1961 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1962 "Formats for `format-time-string' which are used for time stamps.
1963 It is not recommended to change this constant.")
1965 (defcustom org-time-stamp-rounding-minutes '(0 5)
1966 "Number of minutes to round time stamps to.
1967 These are two values, the first applies when first creating a time stamp.
1968 The second applies when changing it with the commands `S-up' and `S-down'.
1969 When changing the time stamp, this means that it will change in steps
1970 of N minutes, as given by the second value.
1972 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1973 numbers should be factors of 60, so for example 5, 10, 15.
1975 When this is larger than 1, you can still force an exact time-stamp by using
1976 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1977 and by using a prefix arg to `S-up/down' to specify the exact number
1978 of minutes to shift."
1979 :group 'org-time
1980 :get '(lambda (var) ; Make sure all entries have 5 elements
1981 (if (integerp (default-value var))
1982 (list (default-value var) 5)
1983 (default-value var)))
1984 :type '(list
1985 (integer :tag "when inserting times")
1986 (integer :tag "when modifying times")))
1988 ;; Normalize old customizations of this variable.
1989 (when (integerp org-time-stamp-rounding-minutes)
1990 (setq org-time-stamp-rounding-minutes
1991 (list org-time-stamp-rounding-minutes
1992 org-time-stamp-rounding-minutes)))
1994 (defcustom org-display-custom-times nil
1995 "Non-nil means, overlay custom formats over all time stamps.
1996 The formats are defined through the variable `org-time-stamp-custom-formats'.
1997 To turn this on on a per-file basis, insert anywhere in the file:
1998 #+STARTUP: customtime"
1999 :group 'org-time
2000 :set 'set-default
2001 :type 'sexp)
2002 (make-variable-buffer-local 'org-display-custom-times)
2004 (defcustom org-time-stamp-custom-formats
2005 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2006 "Custom formats for time stamps. See `format-time-string' for the syntax.
2007 These are overlayed over the default ISO format if the variable
2008 `org-display-custom-times' is set. Time like %H:%M should be at the
2009 end of the second format."
2010 :group 'org-time
2011 :type 'sexp)
2013 (defun org-time-stamp-format (&optional long inactive)
2014 "Get the right format for a time string."
2015 (let ((f (if long (cdr org-time-stamp-formats)
2016 (car org-time-stamp-formats))))
2017 (if inactive
2018 (concat "[" (substring f 1 -1) "]")
2019 f)))
2021 (defcustom org-time-clocksum-format "%d:%02d"
2022 "The format string used when creating CLOCKSUM lines, or when
2023 org-mode generates a time duration."
2024 :group 'org-time
2025 :type 'string)
2027 (defcustom org-deadline-warning-days 14
2028 "No. of days before expiration during which a deadline becomes active.
2029 This variable governs the display in sparse trees and in the agenda.
2030 When 0 or negative, it means use this number (the absolute value of it)
2031 even if a deadline has a different individual lead time specified.
2033 Custom commands can set this variable in the options section."
2034 :group 'org-time
2035 :group 'org-agenda-daily/weekly
2036 :type 'integer)
2038 (defcustom org-read-date-prefer-future t
2039 "Non-nil means, assume future for incomplete date input from user.
2040 This affects the following situations:
2041 1. The user gives a day, but no month.
2042 For example, if today is the 15th, and you enter \"3\", Org-mode will
2043 read this as the third of *next* month. However, if you enter \"17\",
2044 it will be considered as *this* month.
2045 2. The user gives a month but not a year.
2046 For example, if it is april and you enter \"feb 2\", this will be read
2047 as feb 2, *next* year. \"May 5\", however, will be this year.
2049 Currently this does not work for ISO week specifications.
2051 When this option is nil, the current month and year will always be used
2052 as defaults."
2053 :group 'org-time
2054 :type 'boolean)
2056 (defcustom org-read-date-display-live t
2057 "Non-nil means, display current interpretation of date prompt live.
2058 This display will be in an overlay, in the minibuffer."
2059 :group 'org-time
2060 :type 'boolean)
2062 (defcustom org-read-date-popup-calendar t
2063 "Non-nil means, pop up a calendar when prompting for a date.
2064 In the calendar, the date can be selected with mouse-1. However, the
2065 minibuffer will also be active, and you can simply enter the date as well.
2066 When nil, only the minibuffer will be available."
2067 :group 'org-time
2068 :type 'boolean)
2069 (if (fboundp 'defvaralias)
2070 (defvaralias 'org-popup-calendar-for-date-prompt
2071 'org-read-date-popup-calendar))
2073 (defcustom org-read-date-minibuffer-setup-hook nil
2074 "Hook to be used to set up keys for the date/time interface.
2075 Add key definitions to `minibuffer-local-map', which will be a temporary
2076 copy."
2077 :group 'org-time
2078 :type 'hook)
2080 (defcustom org-extend-today-until 0
2081 "The hour when your day really ends. Must be an integer.
2082 This has influence for the following applications:
2083 - When switching the agenda to \"today\". It it is still earlier than
2084 the time given here, the day recognized as TODAY is actually yesterday.
2085 - When a date is read from the user and it is still before the time given
2086 here, the current date and time will be assumed to be yesterday, 23:59.
2087 Also, timestamps inserted in remember templates follow this rule.
2089 IMPORTANT: This is a feature whose implementation is and likely will
2090 remain incomplete. Really, it is only here because past midnight seems to
2091 be the favorite working time of John Wiegley :-)"
2092 :group 'org-time
2093 :type 'integer)
2095 (defcustom org-edit-timestamp-down-means-later nil
2096 "Non-nil means, S-down will increase the time in a time stamp.
2097 When nil, S-up will increase."
2098 :group 'org-time
2099 :type 'boolean)
2101 (defcustom org-calendar-follow-timestamp-change t
2102 "Non-nil means, make the calendar window follow timestamp changes.
2103 When a timestamp is modified and the calendar window is visible, it will be
2104 moved to the new date."
2105 :group 'org-time
2106 :type 'boolean)
2108 (defgroup org-tags nil
2109 "Options concerning tags in Org-mode."
2110 :tag "Org Tags"
2111 :group 'org)
2113 (defcustom org-tag-alist nil
2114 "List of tags allowed in Org-mode files.
2115 When this list is nil, Org-mode will base TAG input on what is already in the
2116 buffer.
2117 The value of this variable is an alist, the car of each entry must be a
2118 keyword as a string, the cdr may be a character that is used to select
2119 that tag through the fast-tag-selection interface.
2120 See the manual for details."
2121 :group 'org-tags
2122 :type '(repeat
2123 (choice
2124 (cons (string :tag "Tag name")
2125 (character :tag "Access char"))
2126 (const :tag "Start radio group" (:startgroup))
2127 (const :tag "End radio group" (:endgroup))
2128 (const :tag "New line" (:newline)))))
2130 (defcustom org-tag-persistent-alist nil
2131 "List of tags that will always appear in all Org-mode files.
2132 This is in addition to any in buffer settings or customizations
2133 of `org-tag-alist'.
2134 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2135 The value of this variable is an alist, the car of each entry must be a
2136 keyword as a string, the cdr may be a character that is used to select
2137 that tag through the fast-tag-selection interface.
2138 See the manual for details.
2139 To disable these tags on a per-file basis, insert anywhere in the file:
2140 #+STARTUP: noptag"
2141 :group 'org-tags
2142 :type '(repeat
2143 (choice
2144 (cons (string :tag "Tag name")
2145 (character :tag "Access char"))
2146 (const :tag "Start radio group" (:startgroup))
2147 (const :tag "End radio group" (:endgroup))
2148 (const :tag "New line" (:newline)))))
2150 (defvar org-file-tags nil
2151 "List of tags that can be inherited by all entries in the file.
2152 The tags will be inherited if the variable `org-use-tag-inheritance'
2153 says they should be.
2154 This variable is populated from #+TAG lines.")
2156 (defcustom org-use-fast-tag-selection 'auto
2157 "Non-nil means, use fast tag selection scheme.
2158 This is a special interface to select and deselect tags with single keys.
2159 When nil, fast selection is never used.
2160 When the symbol `auto', fast selection is used if and only if selection
2161 characters for tags have been configured, either through the variable
2162 `org-tag-alist' or through a #+TAGS line in the buffer.
2163 When t, fast selection is always used and selection keys are assigned
2164 automatically if necessary."
2165 :group 'org-tags
2166 :type '(choice
2167 (const :tag "Always" t)
2168 (const :tag "Never" nil)
2169 (const :tag "When selection characters are configured" 'auto)))
2171 (defcustom org-fast-tag-selection-single-key nil
2172 "Non-nil means, fast tag selection exits after first change.
2173 When nil, you have to press RET to exit it.
2174 During fast tag selection, you can toggle this flag with `C-c'.
2175 This variable can also have the value `expert'. In this case, the window
2176 displaying the tags menu is not even shown, until you press C-c again."
2177 :group 'org-tags
2178 :type '(choice
2179 (const :tag "No" nil)
2180 (const :tag "Yes" t)
2181 (const :tag "Expert" expert)))
2183 (defvar org-fast-tag-selection-include-todo nil
2184 "Non-nil means, fast tags selection interface will also offer TODO states.
2185 This is an undocumented feature, you should not rely on it.")
2187 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2188 "The column to which tags should be indented in a headline.
2189 If this number is positive, it specifies the column. If it is negative,
2190 it means that the tags should be flushright to that column. For example,
2191 -80 works well for a normal 80 character screen."
2192 :group 'org-tags
2193 :type 'integer)
2195 (defcustom org-auto-align-tags t
2196 "Non-nil means, realign tags after pro/demotion of TODO state change.
2197 These operations change the length of a headline and therefore shift
2198 the tags around. With this options turned on, after each such operation
2199 the tags are again aligned to `org-tags-column'."
2200 :group 'org-tags
2201 :type 'boolean)
2203 (defcustom org-use-tag-inheritance t
2204 "Non-nil means, tags in levels apply also for sublevels.
2205 When nil, only the tags directly given in a specific line apply there.
2206 This may also be a list of tags that should be inherited, or a regexp that
2207 matches tags that should be inherited. Additional control is possible
2208 with the variable `org-tags-exclude-from-inheritance' which gives an
2209 explicit list of tags to be excluded from inheritance., even if the value of
2210 `org-use-tag-inheritance' would select it for inheritance.
2212 If this option is t, a match early-on in a tree can lead to a large
2213 number of matches in the subtree when constructing the agenda or creating
2214 a sparse tree. If you only want to see the first match in a tree during
2215 a search, check out the variable `org-tags-match-list-sublevels'."
2216 :group 'org-tags
2217 :type '(choice
2218 (const :tag "Not" nil)
2219 (const :tag "Always" t)
2220 (repeat :tag "Specific tags" (string :tag "Tag"))
2221 (regexp :tag "Tags matched by regexp")))
2223 (defcustom org-tags-exclude-from-inheritance nil
2224 "List of tags that should never be inherited.
2225 This is a way to exclude a few tags from inheritance. For way to do
2226 the opposite, to actively allow inheritance for selected tags,
2227 see the variable `org-use-tag-inheritance'."
2228 :group 'org-tags
2229 :type '(repeat (string :tag "Tag")))
2231 (defun org-tag-inherit-p (tag)
2232 "Check if TAG is one that should be inherited."
2233 (cond
2234 ((member tag org-tags-exclude-from-inheritance) nil)
2235 ((eq org-use-tag-inheritance t) t)
2236 ((not org-use-tag-inheritance) nil)
2237 ((stringp org-use-tag-inheritance)
2238 (string-match org-use-tag-inheritance tag))
2239 ((listp org-use-tag-inheritance)
2240 (member tag org-use-tag-inheritance))
2241 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2243 (defcustom org-tags-match-list-sublevels t
2244 "Non-nil means list also sublevels of headlines matching a search.
2245 This variable applies to tags/property searches, and also to stuck
2246 projects because this search is based on a tags match as well.
2248 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2249 the sublevels of a headline matching a tag search often also match
2250 the same search. Listing all of them can create very long lists.
2251 Setting this variable to nil causes subtrees of a match to be skipped.
2253 As a special case, if the tag search is restricted to TODO items, the
2254 value of this variable is ignored and sublevels are always checked, to
2255 make sure all corresponding TODO items find their way into the list.
2257 This variable is semi-obsolete and probably should always be true. It
2258 is better to limit inheritance to certain tags using the variables
2259 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2260 :group 'org-tags
2261 :type '(choice
2262 (const :tag "No, don't list them" nil)
2263 (const :tag "Yes, do list them" t)
2264 (const :tag "List them, indented with leading dots" indented)))
2266 (defvar org-tags-history nil
2267 "History of minibuffer reads for tags.")
2268 (defvar org-last-tags-completion-table nil
2269 "The last used completion table for tags.")
2270 (defvar org-after-tags-change-hook nil
2271 "Hook that is run after the tags in a line have changed.")
2273 (defgroup org-properties nil
2274 "Options concerning properties in Org-mode."
2275 :tag "Org Properties"
2276 :group 'org)
2278 (defcustom org-property-format "%-10s %s"
2279 "How property key/value pairs should be formatted by `indent-line'.
2280 When `indent-line' hits a property definition, it will format the line
2281 according to this format, mainly to make sure that the values are
2282 lined-up with respect to each other."
2283 :group 'org-properties
2284 :type 'string)
2286 (defcustom org-use-property-inheritance nil
2287 "Non-nil means, properties apply also for sublevels.
2289 This setting is chiefly used during property searches. Turning it on can
2290 cause significant overhead when doing a search, which is why it is not
2291 on by default.
2293 When nil, only the properties directly given in the current entry count.
2294 When t, every property is inherited. The value may also be a list of
2295 properties that should have inheritance, or a regular expression matching
2296 properties that should be inherited.
2298 However, note that some special properties use inheritance under special
2299 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2300 and the properties ending in \"_ALL\" when they are used as descriptor
2301 for valid values of a property.
2303 Note for programmers:
2304 When querying an entry with `org-entry-get', you can control if inheritance
2305 should be used. By default, `org-entry-get' looks only at the local
2306 properties. You can request inheritance by setting the inherit argument
2307 to t (to force inheritance) or to `selective' (to respect the setting
2308 in this variable)."
2309 :group 'org-properties
2310 :type '(choice
2311 (const :tag "Not" nil)
2312 (const :tag "Always" t)
2313 (repeat :tag "Specific properties" (string :tag "Property"))
2314 (regexp :tag "Properties matched by regexp")))
2316 (defun org-property-inherit-p (property)
2317 "Check if PROPERTY is one that should be inherited."
2318 (cond
2319 ((eq org-use-property-inheritance t) t)
2320 ((not org-use-property-inheritance) nil)
2321 ((stringp org-use-property-inheritance)
2322 (string-match org-use-property-inheritance property))
2323 ((listp org-use-property-inheritance)
2324 (member property org-use-property-inheritance))
2325 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2327 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2328 "The default column format, if no other format has been defined.
2329 This variable can be set on the per-file basis by inserting a line
2331 #+COLUMNS: %25ITEM ....."
2332 :group 'org-properties
2333 :type 'string)
2335 (defcustom org-columns-ellipses ".."
2336 "The ellipses to be used when a field in column view is truncated.
2337 When this is the empty string, as many characters as possible are shown,
2338 but then there will be no visual indication that the field has been truncated.
2339 When this is a string of length N, the last N characters of a truncated
2340 field are replaced by this string. If the column is narrower than the
2341 ellipses string, only part of the ellipses string will be shown."
2342 :group 'org-properties
2343 :type 'string)
2345 (defcustom org-columns-modify-value-for-display-function nil
2346 "Function that modifies values for display in column view.
2347 For example, it can be used to cut out a certain part from a time stamp.
2348 The function must take 2 arguments:
2350 column-title The title of the column (*not* the property name)
2351 value The value that should be modified.
2353 The function should return the value that should be displayed,
2354 or nil if the normal value should be used."
2355 :group 'org-properties
2356 :type 'function)
2358 (defcustom org-effort-property "Effort"
2359 "The property that is being used to keep track of effort estimates.
2360 Effort estimates given in this property need to have the format H:MM."
2361 :group 'org-properties
2362 :group 'org-progress
2363 :type '(string :tag "Property"))
2365 (defconst org-global-properties-fixed
2366 '(("VISIBILITY_ALL" . "folded children content all"))
2367 "List of property/value pairs that can be inherited by any entry.
2369 These are fixed values, for the preset properties. The user variable
2370 that can be used to add to this list is `org-global-properties'.
2372 The entries in this list are cons cells where the car is a property
2373 name and cdr is a string with the value. If the value represents
2374 multiple items like an \"_ALL\" property, separate the items by
2375 spaces.")
2377 (defcustom org-global-properties nil
2378 "List of property/value pairs that can be inherited by any entry.
2380 This list will be combined with the constant `org-global-properties-fixed'.
2382 The entries in this list are cons cells where the car is a property
2383 name and cdr is a string with the value.
2385 You can set buffer-local values for the same purpose in the variable
2386 `org-file-properties' this by adding lines like
2388 #+PROPERTY: NAME VALUE"
2389 :group 'org-properties
2390 :type '(repeat
2391 (cons (string :tag "Property")
2392 (string :tag "Value"))))
2394 (defvar org-file-properties nil
2395 "List of property/value pairs that can be inherited by any entry.
2396 Valid for the current buffer.
2397 This variable is populated from #+PROPERTY lines.")
2398 (make-variable-buffer-local 'org-file-properties)
2400 (defgroup org-agenda nil
2401 "Options concerning agenda views in Org-mode."
2402 :tag "Org Agenda"
2403 :group 'org)
2405 (defvar org-category nil
2406 "Variable used by org files to set a category for agenda display.
2407 Such files should use a file variable to set it, for example
2409 # -*- mode: org; org-category: \"ELisp\"
2411 or contain a special line
2413 #+CATEGORY: ELisp
2415 If the file does not specify a category, then file's base name
2416 is used instead.")
2417 (make-variable-buffer-local 'org-category)
2418 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2420 (defcustom org-agenda-files nil
2421 "The files to be used for agenda display.
2422 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2423 \\[org-remove-file]. You can also use customize to edit the list.
2425 If an entry is a directory, all files in that directory that are matched by
2426 `org-agenda-file-regexp' will be part of the file list.
2428 If the value of the variable is not a list but a single file name, then
2429 the list of agenda files is actually stored and maintained in that file, one
2430 agenda file per line."
2431 :group 'org-agenda
2432 :type '(choice
2433 (repeat :tag "List of files and directories" file)
2434 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2436 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2437 "Regular expression to match files for `org-agenda-files'.
2438 If any element in the list in that variable contains a directory instead
2439 of a normal file, all files in that directory that are matched by this
2440 regular expression will be included."
2441 :group 'org-agenda
2442 :type 'regexp)
2444 (defcustom org-agenda-text-search-extra-files nil
2445 "List of extra files to be searched by text search commands.
2446 These files will be search in addition to the agenda files by the
2447 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2448 Note that these files will only be searched for text search commands,
2449 not for the other agenda views like todo lists, tag searches or the weekly
2450 agenda. This variable is intended to list notes and possibly archive files
2451 that should also be searched by these two commands.
2452 In fact, if the first element in the list is the symbol `agenda-archives',
2453 than all archive files of all agenda files will be added to the search
2454 scope."
2455 :group 'org-agenda
2456 :type '(set :greedy t
2457 (const :tag "Agenda Archives" agenda-archives)
2458 (repeat :inline t (file))))
2460 (if (fboundp 'defvaralias)
2461 (defvaralias 'org-agenda-multi-occur-extra-files
2462 'org-agenda-text-search-extra-files))
2464 (defcustom org-agenda-skip-unavailable-files nil
2465 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2466 A nil value means to remove them, after a query, from the list."
2467 :group 'org-agenda
2468 :type 'boolean)
2470 (defcustom org-calendar-to-agenda-key [?c]
2471 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2472 The command `org-calendar-goto-agenda' will be bound to this key. The
2473 default is the character `c' because then `c' can be used to switch back and
2474 forth between agenda and calendar."
2475 :group 'org-agenda
2476 :type 'sexp)
2478 (defcustom org-calendar-agenda-action-key [?k]
2479 "The key to be installed in `calendar-mode-map' for agenda-action.
2480 The command `org-agenda-action' will be bound to this key. The
2481 default is the character `k' because we use the same key in the agenda."
2482 :group 'org-agenda
2483 :type 'sexp)
2485 (eval-after-load "calendar"
2486 '(progn
2487 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2488 'org-calendar-goto-agenda)
2489 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2490 'org-agenda-action)))
2492 (defgroup org-latex nil
2493 "Options for embedding LaTeX code into Org-mode."
2494 :tag "Org LaTeX"
2495 :group 'org)
2497 (defcustom org-format-latex-options
2498 '(:foreground default :background default :scale 1.0
2499 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2500 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2501 "Options for creating images from LaTeX fragments.
2502 This is a property list with the following properties:
2503 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2504 `default' means use the foreground of the default face.
2505 :background the background color, or \"Transparent\".
2506 `default' means use the background of the default face.
2507 :scale a scaling factor for the size of the images.
2508 :html-foreground, :html-background, :html-scale
2509 the same numbers for HTML export.
2510 :matchers a list indicating which matchers should be used to
2511 find LaTeX fragments. Valid members of this list are:
2512 \"begin\" find environments
2513 \"$1\" find single characters surrounded by $.$
2514 \"$\" find math expressions surrounded by $...$
2515 \"$$\" find math expressions surrounded by $$....$$
2516 \"\\(\" find math expressions surrounded by \\(...\\)
2517 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2518 :group 'org-latex
2519 :type 'plist)
2521 (defcustom org-format-latex-header "\\documentclass{article}
2522 \\usepackage{fullpage} % do not remove
2523 \\usepackage{amssymb}
2524 \\usepackage[usenames]{color}
2525 \\usepackage{amsmath}
2526 \\usepackage{latexsym}
2527 \\usepackage[mathscr]{eucal}
2528 \\pagestyle{empty} % do not remove"
2529 "The document header used for processing LaTeX fragments."
2530 :group 'org-latex
2531 :type 'string)
2534 (defgroup org-font-lock nil
2535 "Font-lock settings for highlighting in Org-mode."
2536 :tag "Org Font Lock"
2537 :group 'org)
2539 (defcustom org-level-color-stars-only nil
2540 "Non-nil means fontify only the stars in each headline.
2541 When nil, the entire headline is fontified.
2542 Changing it requires restart of `font-lock-mode' to become effective
2543 also in regions already fontified."
2544 :group 'org-font-lock
2545 :type 'boolean)
2547 (defcustom org-hide-leading-stars nil
2548 "Non-nil means, hide the first N-1 stars in a headline.
2549 This works by using the face `org-hide' for these stars. This
2550 face is white for a light background, and black for a dark
2551 background. You may have to customize the face `org-hide' to
2552 make this work.
2553 Changing it requires restart of `font-lock-mode' to become effective
2554 also in regions already fontified.
2555 You may also set this on a per-file basis by adding one of the following
2556 lines to the buffer:
2558 #+STARTUP: hidestars
2559 #+STARTUP: showstars"
2560 :group 'org-font-lock
2561 :type 'boolean)
2563 (defcustom org-fontify-done-headline nil
2564 "Non-nil means, change the face of a headline if it is marked DONE.
2565 Normally, only the TODO/DONE keyword indicates the state of a headline.
2566 When this is non-nil, the headline after the keyword is set to the
2567 `org-headline-done' as an additional indication."
2568 :group 'org-font-lock
2569 :type 'boolean)
2571 (defcustom org-fontify-emphasized-text t
2572 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2573 Changing this variable requires a restart of Emacs to take effect."
2574 :group 'org-font-lock
2575 :type 'boolean)
2577 (defcustom org-highlight-latex-fragments-and-specials nil
2578 "Non-nil means, fontify what is treated specially by the exporters."
2579 :group 'org-font-lock
2580 :type 'boolean)
2582 (defcustom org-hide-emphasis-markers nil
2583 "Non-nil mean font-lock should hide the emphasis marker characters."
2584 :group 'org-font-lock
2585 :type 'boolean)
2587 (defvar org-emph-re nil
2588 "Regular expression for matching emphasis.")
2589 (defvar org-verbatim-re nil
2590 "Regular expression for matching verbatim text.")
2591 (defvar org-emphasis-regexp-components) ; defined just below
2592 (defvar org-emphasis-alist) ; defined just below
2593 (defun org-set-emph-re (var val)
2594 "Set variable and compute the emphasis regular expression."
2595 (set var val)
2596 (when (and (boundp 'org-emphasis-alist)
2597 (boundp 'org-emphasis-regexp-components)
2598 org-emphasis-alist org-emphasis-regexp-components)
2599 (let* ((e org-emphasis-regexp-components)
2600 (pre (car e))
2601 (post (nth 1 e))
2602 (border (nth 2 e))
2603 (body (nth 3 e))
2604 (nl (nth 4 e))
2605 (body1 (concat body "*?"))
2606 (markers (mapconcat 'car org-emphasis-alist ""))
2607 (vmarkers (mapconcat
2608 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2609 org-emphasis-alist "")))
2610 ;; make sure special characters appear at the right position in the class
2611 (if (string-match "\\^" markers)
2612 (setq markers (concat (replace-match "" t t markers) "^")))
2613 (if (string-match "-" markers)
2614 (setq markers (concat (replace-match "" t t markers) "-")))
2615 (if (string-match "\\^" vmarkers)
2616 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2617 (if (string-match "-" vmarkers)
2618 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2619 (if (> nl 0)
2620 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2621 (int-to-string nl) "\\}")))
2622 ;; Make the regexp
2623 (setq org-emph-re
2624 (concat "\\([" pre "]\\|^\\)"
2625 "\\("
2626 "\\([" markers "]\\)"
2627 "\\("
2628 "[^" border "]\\|"
2629 "[^" border "]"
2630 body1
2631 "[^" border "]"
2632 "\\)"
2633 "\\3\\)"
2634 "\\([" post "]\\|$\\)"))
2635 (setq org-verbatim-re
2636 (concat "\\([" pre "]\\|^\\)"
2637 "\\("
2638 "\\([" vmarkers "]\\)"
2639 "\\("
2640 "[^" border "]\\|"
2641 "[^" border "]"
2642 body1
2643 "[^" border "]"
2644 "\\)"
2645 "\\3\\)"
2646 "\\([" post "]\\|$\\)")))))
2648 (defcustom org-emphasis-regexp-components
2649 '(" \t('\"{" "- \t.,:!?;'\")}" " \t\r\n,\"'" "." 1)
2650 "Components used to build the regular expression for emphasis.
2651 This is a list with 6 entries. Terminology: In an emphasis string
2652 like \" *strong word* \", we call the initial space PREMATCH, the final
2653 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2654 and \"trong wor\" is the body. The different components in this variable
2655 specify what is allowed/forbidden in each part:
2657 pre Chars allowed as prematch. Beginning of line will be allowed too.
2658 post Chars allowed as postmatch. End of line will be allowed too.
2659 border The chars *forbidden* as border characters.
2660 body-regexp A regexp like \".\" to match a body character. Don't use
2661 non-shy groups here, and don't allow newline here.
2662 newline The maximum number of newlines allowed in an emphasis exp.
2664 Use customize to modify this, or restart Emacs after changing it."
2665 :group 'org-font-lock
2666 :set 'org-set-emph-re
2667 :type '(list
2668 (sexp :tag "Allowed chars in pre ")
2669 (sexp :tag "Allowed chars in post ")
2670 (sexp :tag "Forbidden chars in border ")
2671 (sexp :tag "Regexp for body ")
2672 (integer :tag "number of newlines allowed")
2673 (option (boolean :tag "Please ignore this button"))))
2675 (defcustom org-emphasis-alist
2676 `(("*" bold "<b>" "</b>")
2677 ("/" italic "<i>" "</i>")
2678 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2679 ("=" org-code "<code>" "</code>" verbatim)
2680 ("~" org-verbatim "<code>" "</code>" verbatim)
2681 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2682 "<del>" "</del>")
2684 "Special syntax for emphasized text.
2685 Text starting and ending with a special character will be emphasized, for
2686 example *bold*, _underlined_ and /italic/. This variable sets the marker
2687 characters, the face to be used by font-lock for highlighting in Org-mode
2688 Emacs buffers, and the HTML tags to be used for this.
2689 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2690 Use customize to modify this, or restart Emacs after changing it."
2691 :group 'org-font-lock
2692 :set 'org-set-emph-re
2693 :type '(repeat
2694 (list
2695 (string :tag "Marker character")
2696 (choice
2697 (face :tag "Font-lock-face")
2698 (plist :tag "Face property list"))
2699 (string :tag "HTML start tag")
2700 (string :tag "HTML end tag")
2701 (option (const verbatim)))))
2703 ;;; Miscellaneous options
2705 (defgroup org-completion nil
2706 "Completion in Org-mode."
2707 :tag "Org Completion"
2708 :group 'org)
2710 (defcustom org-completion-use-ido nil
2711 "Non-nil means, use ido completion wherever possible.
2712 Note that `ido-mode' must be active for this variable to be relevant.
2713 If you decide to turn this variable on, you might well want to turn off
2714 `org-outline-path-complete-in-steps'."
2715 :group 'org-completion
2716 :type 'boolean)
2718 (defcustom org-completion-fallback-command 'hippie-expand
2719 "The expansion command called by \\[org-complete] in normal context.
2720 Normal means, no org-mode-specific context."
2721 :group 'org-completion
2722 :type 'function)
2724 ;;; Functions and variables from ther packages
2725 ;; Declared here to avoid compiler warnings
2727 ;; XEmacs only
2728 (defvar outline-mode-menu-heading)
2729 (defvar outline-mode-menu-show)
2730 (defvar outline-mode-menu-hide)
2731 (defvar zmacs-regions) ; XEmacs regions
2733 ;; Emacs only
2734 (defvar mark-active)
2736 ;; Various packages
2737 (declare-function find-library-name "find-func" (library))
2738 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2739 (declare-function calendar-forward-day "cal-move" (arg))
2740 (declare-function calendar-goto-date "cal-move" (date))
2741 (declare-function calendar-goto-today "cal-move" ())
2742 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2743 (defvar calc-embedded-close-formula)
2744 (defvar calc-embedded-open-formula)
2745 (declare-function cdlatex-tab "ext:cdlatex" ())
2746 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2747 (defvar font-lock-unfontify-region-function)
2748 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2749 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2750 (defvar iswitchb-temp-buflist)
2751 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2752 (defvar org-agenda-tags-todo-honor-ignore-options)
2753 (declare-function org-agenda-skip "org-agenda" ())
2754 (declare-function org-format-agenda-item "org-agenda"
2755 (extra txt &optional category tags dotime noprefix remove-re))
2756 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2757 (declare-function org-agenda-change-all-lines "org-agenda"
2758 (newhead hdmarker &optional fixface just-this))
2759 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2760 (declare-function org-agenda-maybe-redo "org-agenda" ())
2761 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2762 (beg end))
2763 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2764 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2765 "org-agenda" (&optional end))
2767 (declare-function parse-time-string "parse-time" (string))
2768 (declare-function remember "remember" (&optional initial))
2769 (declare-function remember-buffer-desc "remember" ())
2770 (declare-function remember-finalize "remember" ())
2771 (defvar remember-save-after-remembering)
2772 (defvar remember-data-file)
2773 (defvar remember-register)
2774 (defvar remember-buffer)
2775 (defvar remember-handler-functions)
2776 (defvar remember-annotation-functions)
2777 (defvar texmathp-why)
2778 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2779 (declare-function table--at-cell-p "table" (position &optional object at-column))
2781 (defvar w3m-current-url)
2782 (defvar w3m-current-title)
2784 (defvar org-latex-regexps)
2786 ;;; Autoload and prepare some org modules
2788 ;; Some table stuff that needs to be defined here, because it is used
2789 ;; by the functions setting up org-mode or checking for table context.
2791 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2792 "Detects an org-type or table-type table.")
2793 (defconst org-table-line-regexp "^[ \t]*|"
2794 "Detects an org-type table line.")
2795 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2796 "Detects an org-type table line.")
2797 (defconst org-table-hline-regexp "^[ \t]*|-"
2798 "Detects an org-type table hline.")
2799 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2800 "Detects a table-type table hline.")
2801 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2802 "Searching from within a table (any type) this finds the first line
2803 outside the table.")
2805 ;; Autoload the functions in org-table.el that are needed by functions here.
2807 (eval-and-compile
2808 (org-autoload "org-table"
2809 '(org-table-align org-table-begin org-table-blank-field
2810 org-table-convert org-table-convert-region org-table-copy-down
2811 org-table-copy-region org-table-create
2812 org-table-create-or-convert-from-region
2813 org-table-create-with-table.el org-table-current-dline
2814 org-table-cut-region org-table-delete-column org-table-edit-field
2815 org-table-edit-formulas org-table-end org-table-eval-formula
2816 org-table-export org-table-field-info
2817 org-table-get-stored-formulas org-table-goto-column
2818 org-table-hline-and-move org-table-import org-table-insert-column
2819 org-table-insert-hline org-table-insert-row org-table-iterate
2820 org-table-justify-field-maybe org-table-kill-row
2821 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2822 org-table-move-column org-table-move-column-left
2823 org-table-move-column-right org-table-move-row
2824 org-table-move-row-down org-table-move-row-up
2825 org-table-next-field org-table-next-row org-table-paste-rectangle
2826 org-table-previous-field org-table-recalculate
2827 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2828 org-table-toggle-coordinate-overlays
2829 org-table-toggle-formula-debugger org-table-wrap-region
2830 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2832 (defun org-at-table-p (&optional table-type)
2833 "Return t if the cursor is inside an org-type table.
2834 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2835 (if org-enable-table-editor
2836 (save-excursion
2837 (beginning-of-line 1)
2838 (looking-at (if table-type org-table-any-line-regexp
2839 org-table-line-regexp)))
2840 nil))
2841 (defsubst org-table-p () (org-at-table-p))
2843 (defun org-at-table.el-p ()
2844 "Return t if and only if we are at a table.el table."
2845 (and (org-at-table-p 'any)
2846 (save-excursion
2847 (goto-char (org-table-begin 'any))
2848 (looking-at org-table1-hline-regexp))))
2849 (defun org-table-recognize-table.el ()
2850 "If there is a table.el table nearby, recognize it and move into it."
2851 (if org-table-tab-recognizes-table.el
2852 (if (org-at-table.el-p)
2853 (progn
2854 (beginning-of-line 1)
2855 (if (looking-at org-table-dataline-regexp)
2857 (if (looking-at org-table1-hline-regexp)
2858 (progn
2859 (beginning-of-line 2)
2860 (if (looking-at org-table-any-border-regexp)
2861 (beginning-of-line -1)))))
2862 (if (re-search-forward "|" (org-table-end t) t)
2863 (progn
2864 (require 'table)
2865 (if (table--at-cell-p (point))
2867 (message "recognizing table.el table...")
2868 (table-recognize-table)
2869 (message "recognizing table.el table...done")))
2870 (error "This should not happen..."))
2872 nil)
2873 nil))
2875 (defun org-at-table-hline-p ()
2876 "Return t if the cursor is inside a hline in a table."
2877 (if org-enable-table-editor
2878 (save-excursion
2879 (beginning-of-line 1)
2880 (looking-at org-table-hline-regexp))
2881 nil))
2883 (defvar org-table-clean-did-remove-column nil)
2885 (defun org-table-map-tables (function)
2886 "Apply FUNCTION to the start of all tables in the buffer."
2887 (save-excursion
2888 (save-restriction
2889 (widen)
2890 (goto-char (point-min))
2891 (while (re-search-forward org-table-any-line-regexp nil t)
2892 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2893 (beginning-of-line 1)
2894 (if (looking-at org-table-line-regexp)
2895 (save-excursion (funcall function)))
2896 (re-search-forward org-table-any-border-regexp nil 1))))
2897 (message "Mapping tables: done"))
2899 ;; Declare and autoload functions from org-exp.el
2901 (declare-function org-default-export-plist "org-exp")
2902 (declare-function org-infile-export-plist "org-exp")
2903 (declare-function org-get-current-options "org-exp")
2904 (eval-and-compile
2905 (org-autoload "org-exp"
2906 '(org-export org-export-as-ascii org-export-visible
2907 org-insert-export-options-template org-export-as-html-and-open
2908 org-export-as-html-batch org-export-as-html-to-buffer
2909 org-replace-region-by-html org-export-region-as-html
2910 org-export-as-html org-export-icalendar-this-file
2911 org-export-icalendar-all-agenda-files
2912 org-table-clean-before-export
2913 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2915 ;; Declare and autoload functions from org-agenda.el
2917 (eval-and-compile
2918 (org-autoload "org-agenda"
2919 '(org-agenda org-agenda-list org-search-view
2920 org-todo-list org-tags-view org-agenda-list-stuck-projects
2921 org-diary org-agenda-to-appt
2922 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2924 ;; Autoload org-remember
2926 (eval-and-compile
2927 (org-autoload "org-remember"
2928 '(org-remember-insinuate org-remember-annotation
2929 org-remember-apply-template org-remember org-remember-handler)))
2931 ;; Autoload org-clock.el
2934 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2935 (beg end))
2936 (declare-function org-clock-update-mode-line "org-clock" ())
2937 (defvar org-clock-start-time)
2938 (defvar org-clock-marker (make-marker)
2939 "Marker recording the last clock-in.")
2941 (eval-and-compile
2942 (org-autoload
2943 "org-clock"
2944 '(org-clock-in org-clock-out org-clock-cancel
2945 org-clock-goto org-clock-sum org-clock-display
2946 org-clock-remove-overlays org-clock-report
2947 org-clocktable-shift org-dblock-write:clocktable
2948 org-get-clocktable)))
2950 (defun org-clock-update-time-maybe ()
2951 "If this is a CLOCK line, update it and return t.
2952 Otherwise, return nil."
2953 (interactive)
2954 (save-excursion
2955 (beginning-of-line 1)
2956 (skip-chars-forward " \t")
2957 (when (looking-at org-clock-string)
2958 (let ((re (concat "[ \t]*" org-clock-string
2959 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2960 "\\([ \t]*=>.*\\)?\\)?"))
2961 ts te h m s neg)
2962 (cond
2963 ((not (looking-at re))
2964 nil)
2965 ((not (match-end 2))
2966 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2967 (> org-clock-marker (point))
2968 (<= org-clock-marker (point-at-eol)))
2969 ;; The clock is running here
2970 (setq org-clock-start-time
2971 (apply 'encode-time
2972 (org-parse-time-string (match-string 1))))
2973 (org-clock-update-mode-line)))
2975 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2976 (end-of-line 1)
2977 (setq ts (match-string 1)
2978 te (match-string 3))
2979 (setq s (- (time-to-seconds
2980 (apply 'encode-time (org-parse-time-string te)))
2981 (time-to-seconds
2982 (apply 'encode-time (org-parse-time-string ts))))
2983 neg (< s 0)
2984 s (abs s)
2985 h (floor (/ s 3600))
2986 s (- s (* 3600 h))
2987 m (floor (/ s 60))
2988 s (- s (* 60 s)))
2989 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2990 t))))))
2992 (defun org-check-running-clock ()
2993 "Check if the current buffer contains the running clock.
2994 If yes, offer to stop it and to save the buffer with the changes."
2995 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2996 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2997 (buffer-name))))
2998 (org-clock-out)
2999 (when (y-or-n-p "Save changed buffer?")
3000 (save-buffer))))
3002 (defun org-clocktable-try-shift (dir n)
3003 "Check if this line starts a clock table, if yes, shift the time block."
3004 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3005 (org-clocktable-shift dir n)))
3007 ;; Autoload org-timer.el
3009 (eval-and-compile
3010 (org-autoload
3011 "org-timer"
3012 '(org-timer-start org-timer org-timer-item
3013 org-timer-change-times-in-region)))
3015 ;; Autoload org-feed.el
3017 (eval-and-compile
3018 (org-autoload
3019 "org-feed"
3020 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3023 ;; Autoload archiving code
3024 ;; The stuff that is needed for cycling and tags has to be defined here.
3026 (defgroup org-archive nil
3027 "Options concerning archiving in Org-mode."
3028 :tag "Org Archive"
3029 :group 'org-structure)
3031 (defcustom org-archive-location "%s_archive::"
3032 "The location where subtrees should be archived.
3034 The value of this variable is a string, consisting of two parts,
3035 separated by a double-colon. The first part is a filename and
3036 the second part is a headline.
3038 When the filename is omitted, archiving happens in the same file.
3039 %s in the filename will be replaced by the current file
3040 name (without the directory part). Archiving to a different file
3041 is useful to keep archived entries from contributing to the
3042 Org-mode Agenda.
3044 The archived entries will be filed as subtrees of the specified
3045 headline. When the headline is omitted, the subtrees are simply
3046 filed away at the end of the file, as top-level entries. Also in
3047 the heading you can use %s to represent the file name, this can be
3048 useful when using the same archive for a number of different files.
3050 Here are a few examples:
3051 \"%s_archive::\"
3052 If the current file is Projects.org, archive in file
3053 Projects.org_archive, as top-level trees. This is the default.
3055 \"::* Archived Tasks\"
3056 Archive in the current file, under the top-level headline
3057 \"* Archived Tasks\".
3059 \"~/org/archive.org::\"
3060 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3062 \"~/org/archive.org::From %s\"
3063 Archive in file ~/org/archive.org (absolute path), und headlines
3064 \"From FILENAME\" where file name is the current file name.
3066 \"basement::** Finished Tasks\"
3067 Archive in file ./basement (relative path), as level 3 trees
3068 below the level 2 heading \"** Finished Tasks\".
3070 You may set this option on a per-file basis by adding to the buffer a
3071 line like
3073 #+ARCHIVE: basement::** Finished Tasks
3075 You may also define it locally for a subtree by setting an ARCHIVE property
3076 in the entry. If such a property is found in an entry, or anywhere up
3077 the hierarchy, it will be used."
3078 :group 'org-archive
3079 :type 'string)
3081 (defcustom org-archive-tag "ARCHIVE"
3082 "The tag that marks a subtree as archived.
3083 An archived subtree does not open during visibility cycling, and does
3084 not contribute to the agenda listings.
3085 After changing this, font-lock must be restarted in the relevant buffers to
3086 get the proper fontification."
3087 :group 'org-archive
3088 :group 'org-keywords
3089 :type 'string)
3091 (defcustom org-agenda-skip-archived-trees t
3092 "Non-nil means, the agenda will skip any items located in archived trees.
3093 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3094 variable is no longer recommended, you should leave it at the value t.
3095 Instead, use the key `v' to cycle the archives-mode in the agenda."
3096 :group 'org-archive
3097 :group 'org-agenda-skip
3098 :type 'boolean)
3100 (defcustom org-columns-skip-arrchived-trees t
3101 "Non-nil means, irgnore archived trees when creating column view."
3102 :group 'org-archive
3103 :group 'org-properties
3104 :type 'boolean)
3106 (defcustom org-cycle-open-archived-trees nil
3107 "Non-nil means, `org-cycle' will open archived trees.
3108 An archived tree is a tree marked with the tag ARCHIVE.
3109 When nil, archived trees will stay folded. You can still open them with
3110 normal outline commands like `show-all', but not with the cycling commands."
3111 :group 'org-archive
3112 :group 'org-cycle
3113 :type 'boolean)
3115 (defcustom org-sparse-tree-open-archived-trees nil
3116 "Non-nil means sparse tree construction shows matches in archived trees.
3117 When nil, matches in these trees are highlighted, but the trees are kept in
3118 collapsed state."
3119 :group 'org-archive
3120 :group 'org-sparse-trees
3121 :type 'boolean)
3123 (defun org-cycle-hide-archived-subtrees (state)
3124 "Re-hide all archived subtrees after a visibility state change."
3125 (when (and (not org-cycle-open-archived-trees)
3126 (not (memq state '(overview folded))))
3127 (save-excursion
3128 (let* ((globalp (memq state '(contents all)))
3129 (beg (if globalp (point-min) (point)))
3130 (end (if globalp (point-max) (org-end-of-subtree t))))
3131 (org-hide-archived-subtrees beg end)
3132 (goto-char beg)
3133 (if (looking-at (concat ".*:" org-archive-tag ":"))
3134 (message "%s" (substitute-command-keys
3135 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3137 (defun org-force-cycle-archived ()
3138 "Cycle subtree even if it is archived."
3139 (interactive)
3140 (setq this-command 'org-cycle)
3141 (let ((org-cycle-open-archived-trees t))
3142 (call-interactively 'org-cycle)))
3144 (defun org-hide-archived-subtrees (beg end)
3145 "Re-hide all archived subtrees after a visibility state change."
3146 (save-excursion
3147 (let* ((re (concat ":" org-archive-tag ":")))
3148 (goto-char beg)
3149 (while (re-search-forward re end t)
3150 (and (org-on-heading-p) (hide-subtree))
3151 (org-end-of-subtree t)))))
3153 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3155 (eval-and-compile
3156 (org-autoload "org-archive"
3157 '(org-add-archive-files org-archive-subtree
3158 org-archive-to-archive-sibling org-toggle-archive-tag)))
3160 ;; Autoload Column View Code
3162 (declare-function org-columns-number-to-string "org-colview")
3163 (declare-function org-columns-get-format-and-top-level "org-colview")
3164 (declare-function org-columns-compute "org-colview")
3166 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3167 '(org-columns-number-to-string org-columns-get-format-and-top-level
3168 org-columns-compute org-agenda-columns org-columns-remove-overlays
3169 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3171 ;; Autoload ID code
3173 (declare-function org-id-store-link "org-id")
3174 (declare-function org-id-locations-load "org-id")
3175 (declare-function org-id-locations-save "org-id")
3176 (defvar org-id-track-globally)
3177 (org-autoload "org-id"
3178 '(org-id-get-create org-id-new org-id-copy org-id-get
3179 org-id-get-with-outline-path-completion
3180 org-id-get-with-outline-drilling
3181 org-id-goto org-id-find org-id-store-link))
3183 ;; Autoload Plotting Code
3185 (org-autoload "org-plot"
3186 '(org-plot/gnuplot))
3188 ;;; Variables for pre-computed regular expressions, all buffer local
3190 (defvar org-drawer-regexp nil
3191 "Matches first line of a hidden block.")
3192 (make-variable-buffer-local 'org-drawer-regexp)
3193 (defvar org-todo-regexp nil
3194 "Matches any of the TODO state keywords.")
3195 (make-variable-buffer-local 'org-todo-regexp)
3196 (defvar org-not-done-regexp nil
3197 "Matches any of the TODO state keywords except the last one.")
3198 (make-variable-buffer-local 'org-not-done-regexp)
3199 (defvar org-todo-line-regexp nil
3200 "Matches a headline and puts TODO state into group 2 if present.")
3201 (make-variable-buffer-local 'org-todo-line-regexp)
3202 (defvar org-complex-heading-regexp nil
3203 "Matches a headline and puts everything into groups:
3204 group 1: the stars
3205 group 2: The todo keyword, maybe
3206 group 3: Priority cookie
3207 group 4: True headline
3208 group 5: Tags")
3209 (make-variable-buffer-local 'org-complex-heading-regexp)
3210 (defvar org-todo-line-tags-regexp nil
3211 "Matches a headline and puts TODO state into group 2 if present.
3212 Also put tags into group 4 if tags are present.")
3213 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3214 (defvar org-nl-done-regexp nil
3215 "Matches newline followed by a headline with the DONE keyword.")
3216 (make-variable-buffer-local 'org-nl-done-regexp)
3217 (defvar org-looking-at-done-regexp nil
3218 "Matches the DONE keyword a point.")
3219 (make-variable-buffer-local 'org-looking-at-done-regexp)
3220 (defvar org-ds-keyword-length 12
3221 "Maximum length of the Deadline and SCHEDULED keywords.")
3222 (make-variable-buffer-local 'org-ds-keyword-length)
3223 (defvar org-deadline-regexp nil
3224 "Matches the DEADLINE keyword.")
3225 (make-variable-buffer-local 'org-deadline-regexp)
3226 (defvar org-deadline-time-regexp nil
3227 "Matches the DEADLINE keyword together with a time stamp.")
3228 (make-variable-buffer-local 'org-deadline-time-regexp)
3229 (defvar org-deadline-line-regexp nil
3230 "Matches the DEADLINE keyword and the rest of the line.")
3231 (make-variable-buffer-local 'org-deadline-line-regexp)
3232 (defvar org-scheduled-regexp nil
3233 "Matches the SCHEDULED keyword.")
3234 (make-variable-buffer-local 'org-scheduled-regexp)
3235 (defvar org-scheduled-time-regexp nil
3236 "Matches the SCHEDULED keyword together with a time stamp.")
3237 (make-variable-buffer-local 'org-scheduled-time-regexp)
3238 (defvar org-closed-time-regexp nil
3239 "Matches the CLOSED keyword together with a time stamp.")
3240 (make-variable-buffer-local 'org-closed-time-regexp)
3242 (defvar org-keyword-time-regexp nil
3243 "Matches any of the 4 keywords, together with the time stamp.")
3244 (make-variable-buffer-local 'org-keyword-time-regexp)
3245 (defvar org-keyword-time-not-clock-regexp nil
3246 "Matches any of the 3 keywords, together with the time stamp.")
3247 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3248 (defvar org-maybe-keyword-time-regexp nil
3249 "Matches a timestamp, possibly preceeded by a keyword.")
3250 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3251 (defvar org-planning-or-clock-line-re nil
3252 "Matches a line with planning or clock info.")
3253 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3255 (defconst org-plain-time-of-day-regexp
3256 (concat
3257 "\\(\\<[012]?[0-9]"
3258 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3259 "\\(--?"
3260 "\\(\\<[012]?[0-9]"
3261 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3262 "\\)?")
3263 "Regular expression to match a plain time or time range.
3264 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3265 groups carry important information:
3266 0 the full match
3267 1 the first time, range or not
3268 8 the second time, if it is a range.")
3270 (defconst org-plain-time-extension-regexp
3271 (concat
3272 "\\(\\<[012]?[0-9]"
3273 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3274 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3275 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3276 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3277 groups carry important information:
3278 0 the full match
3279 7 hours of duration
3280 9 minutes of duration")
3282 (defconst org-stamp-time-of-day-regexp
3283 (concat
3284 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3285 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3286 "\\(--?"
3287 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3288 "Regular expression to match a timestamp time or time range.
3289 After a match, the following groups carry important information:
3290 0 the full match
3291 1 date plus weekday, for backreferencing to make sure both times on same day
3292 2 the first time, range or not
3293 4 the second time, if it is a range.")
3295 (defconst org-startup-options
3296 '(("fold" org-startup-folded t)
3297 ("overview" org-startup-folded t)
3298 ("nofold" org-startup-folded nil)
3299 ("showall" org-startup-folded nil)
3300 ("content" org-startup-folded content)
3301 ("hidestars" org-hide-leading-stars t)
3302 ("showstars" org-hide-leading-stars nil)
3303 ("odd" org-odd-levels-only t)
3304 ("oddeven" org-odd-levels-only nil)
3305 ("align" org-startup-align-all-tables t)
3306 ("noalign" org-startup-align-all-tables nil)
3307 ("customtime" org-display-custom-times t)
3308 ("logdone" org-log-done time)
3309 ("lognotedone" org-log-done note)
3310 ("nologdone" org-log-done nil)
3311 ("lognoteclock-out" org-log-note-clock-out t)
3312 ("nolognoteclock-out" org-log-note-clock-out nil)
3313 ("logrepeat" org-log-repeat state)
3314 ("lognoterepeat" org-log-repeat note)
3315 ("nologrepeat" org-log-repeat nil)
3316 ("fninline" org-footnote-define-inline t)
3317 ("nofninline" org-footnote-define-inline nil)
3318 ("fnlocal" org-footnote-section nil)
3319 ("fnauto" org-footnote-auto-label t)
3320 ("fnprompt" org-footnote-auto-label nil)
3321 ("fnconfirm" org-footnote-auto-label confirm)
3322 ("fnplain" org-footnote-auto-label plain)
3323 ("constcgs" constants-unit-system cgs)
3324 ("constSI" constants-unit-system SI)
3325 ("noptag" org-tag-persistent-alist nil))
3326 "Variable associated with STARTUP options for org-mode.
3327 Each element is a list of three items: The startup options as written
3328 in the #+STARTUP line, the corresponding variable, and the value to
3329 set this variable to if the option is found. An optional forth element PUSH
3330 means to push this value onto the list in the variable.")
3332 (defun org-set-regexps-and-options ()
3333 "Precompute regular expressions for current buffer."
3334 (when (org-mode-p)
3335 (org-set-local 'org-todo-kwd-alist nil)
3336 (org-set-local 'org-todo-key-alist nil)
3337 (org-set-local 'org-todo-key-trigger nil)
3338 (org-set-local 'org-todo-keywords-1 nil)
3339 (org-set-local 'org-done-keywords nil)
3340 (org-set-local 'org-todo-heads nil)
3341 (org-set-local 'org-todo-sets nil)
3342 (org-set-local 'org-todo-log-states nil)
3343 (org-set-local 'org-file-properties nil)
3344 (org-set-local 'org-file-tags nil)
3345 (let ((re (org-make-options-regexp
3346 '("CATEGORY" "TODO" "COLUMNS"
3347 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3348 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3349 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3350 (splitre "[ \t]+")
3351 kwds kws0 kwsa key log value cat arch tags const links hw dws
3352 tail sep kws1 prio props ftags drawers
3353 ext-setup-or-nil setup-contents (start 0))
3354 (save-excursion
3355 (save-restriction
3356 (widen)
3357 (goto-char (point-min))
3358 (while (or (and ext-setup-or-nil
3359 (string-match re ext-setup-or-nil start)
3360 (setq start (match-end 0)))
3361 (and (setq ext-setup-or-nil nil start 0)
3362 (re-search-forward re nil t)))
3363 (setq key (upcase (match-string 1 ext-setup-or-nil))
3364 value (org-match-string-no-properties 2 ext-setup-or-nil))
3365 (cond
3366 ((equal key "CATEGORY")
3367 (if (string-match "[ \t]+$" value)
3368 (setq value (replace-match "" t t value)))
3369 (setq cat value))
3370 ((member key '("SEQ_TODO" "TODO"))
3371 (push (cons 'sequence (org-split-string value splitre)) kwds))
3372 ((equal key "TYP_TODO")
3373 (push (cons 'type (org-split-string value splitre)) kwds))
3374 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3375 ;; general TODO-like setup
3376 (push (cons (intern (downcase (match-string 1 key)))
3377 (org-split-string value splitre)) kwds))
3378 ((equal key "TAGS")
3379 (setq tags (append tags (if tags '("\\n") nil)
3380 (org-split-string value splitre))))
3381 ((equal key "COLUMNS")
3382 (org-set-local 'org-columns-default-format value))
3383 ((equal key "LINK")
3384 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3385 (push (cons (match-string 1 value)
3386 (org-trim (match-string 2 value)))
3387 links)))
3388 ((equal key "PRIORITIES")
3389 (setq prio (org-split-string value " +")))
3390 ((equal key "PROPERTY")
3391 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3392 (push (cons (match-string 1 value) (match-string 2 value))
3393 props)))
3394 ((equal key "FILETAGS")
3395 (when (string-match "\\S-" value)
3396 (setq ftags
3397 (append
3398 ftags
3399 (apply 'append
3400 (mapcar (lambda (x) (org-split-string x ":"))
3401 (org-split-string value)))))))
3402 ((equal key "DRAWERS")
3403 (setq drawers (org-split-string value splitre)))
3404 ((equal key "CONSTANTS")
3405 (setq const (append const (org-split-string value splitre))))
3406 ((equal key "STARTUP")
3407 (let ((opts (org-split-string value splitre))
3408 l var val)
3409 (while (setq l (pop opts))
3410 (when (setq l (assoc l org-startup-options))
3411 (setq var (nth 1 l) val (nth 2 l))
3412 (if (not (nth 3 l))
3413 (set (make-local-variable var) val)
3414 (if (not (listp (symbol-value var)))
3415 (set (make-local-variable var) nil))
3416 (set (make-local-variable var) (symbol-value var))
3417 (add-to-list var val))))))
3418 ((equal key "ARCHIVE")
3419 (string-match " *$" value)
3420 (setq arch (replace-match "" t t value))
3421 (remove-text-properties 0 (length arch)
3422 '(face t fontified t) arch))
3423 ((equal key "SETUPFILE")
3424 (setq setup-contents (org-file-contents
3425 (expand-file-name
3426 (org-remove-double-quotes value))
3427 'noerror))
3428 (if (not ext-setup-or-nil)
3429 (setq ext-setup-or-nil setup-contents start 0)
3430 (setq ext-setup-or-nil
3431 (concat (substring ext-setup-or-nil 0 start)
3432 "\n" setup-contents "\n"
3433 (substring ext-setup-or-nil start)))))
3434 ))))
3435 (when cat
3436 (org-set-local 'org-category (intern cat))
3437 (push (cons "CATEGORY" cat) props))
3438 (when prio
3439 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3440 (setq prio (mapcar 'string-to-char prio))
3441 (org-set-local 'org-highest-priority (nth 0 prio))
3442 (org-set-local 'org-lowest-priority (nth 1 prio))
3443 (org-set-local 'org-default-priority (nth 2 prio)))
3444 (and props (org-set-local 'org-file-properties (nreverse props)))
3445 (and ftags (org-set-local 'org-file-tags
3446 (mapcar 'org-add-prop-inherited ftags)))
3447 (and drawers (org-set-local 'org-drawers drawers))
3448 (and arch (org-set-local 'org-archive-location arch))
3449 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3450 ;; Process the TODO keywords
3451 (unless kwds
3452 ;; Use the global values as if they had been given locally.
3453 (setq kwds (default-value 'org-todo-keywords))
3454 (if (stringp (car kwds))
3455 (setq kwds (list (cons org-todo-interpretation
3456 (default-value 'org-todo-keywords)))))
3457 (setq kwds (reverse kwds)))
3458 (setq kwds (nreverse kwds))
3459 (let (inter kws kw)
3460 (while (setq kws (pop kwds))
3461 (let ((kws (or
3462 (run-hook-with-args-until-success
3463 'org-todo-setup-filter-hook kws)
3464 kws)))
3465 (setq inter (pop kws) sep (member "|" kws)
3466 kws0 (delete "|" (copy-sequence kws))
3467 kwsa nil
3468 kws1 (mapcar
3469 (lambda (x)
3470 ;; 1 2
3471 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3472 (progn
3473 (setq kw (match-string 1 x)
3474 key (and (match-end 2) (match-string 2 x))
3475 log (org-extract-log-state-settings x))
3476 (push (cons kw (and key (string-to-char key))) kwsa)
3477 (and log (push log org-todo-log-states))
3479 (error "Invalid TODO keyword %s" x)))
3480 kws0)
3481 kwsa (if kwsa (append '((:startgroup))
3482 (nreverse kwsa)
3483 '((:endgroup))))
3484 hw (car kws1)
3485 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3486 tail (list inter hw (car dws) (org-last dws))))
3487 (add-to-list 'org-todo-heads hw 'append)
3488 (push kws1 org-todo-sets)
3489 (setq org-done-keywords (append org-done-keywords dws nil))
3490 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3491 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3492 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3493 (setq org-todo-sets (nreverse org-todo-sets)
3494 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3495 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3496 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3497 ;; Process the constants
3498 (when const
3499 (let (e cst)
3500 (while (setq e (pop const))
3501 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3502 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3503 (setq org-table-formula-constants-local cst)))
3505 ;; Process the tags.
3506 (when tags
3507 (let (e tgs)
3508 (while (setq e (pop tags))
3509 (cond
3510 ((equal e "{") (push '(:startgroup) tgs))
3511 ((equal e "}") (push '(:endgroup) tgs))
3512 ((equal e "\\n") (push '(:newline) tgs))
3513 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3514 (push (cons (match-string 1 e)
3515 (string-to-char (match-string 2 e)))
3516 tgs))
3517 (t (push (list e) tgs))))
3518 (org-set-local 'org-tag-alist nil)
3519 (while (setq e (pop tgs))
3520 (or (and (stringp (car e))
3521 (assoc (car e) org-tag-alist))
3522 (push e org-tag-alist)))))
3524 ;; Compute the regular expressions and other local variables
3525 (if (not org-done-keywords)
3526 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3527 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3528 (length org-scheduled-string)
3529 (length org-clock-string)
3530 (length org-closed-string)))
3531 org-drawer-regexp
3532 (concat "^[ \t]*:\\("
3533 (mapconcat 'regexp-quote org-drawers "\\|")
3534 "\\):[ \t]*$")
3535 org-not-done-keywords
3536 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3537 org-todo-regexp
3538 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3539 "\\|") "\\)\\>")
3540 org-not-done-regexp
3541 (concat "\\<\\("
3542 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3543 "\\)\\>")
3544 org-todo-line-regexp
3545 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3546 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3547 "\\)\\>\\)?[ \t]*\\(.*\\)")
3548 org-complex-heading-regexp
3549 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3550 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3551 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3552 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3553 org-nl-done-regexp
3554 (concat "\n\\*+[ \t]+"
3555 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3556 "\\)" "\\>")
3557 org-todo-line-tags-regexp
3558 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3559 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3560 (org-re
3561 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3562 org-looking-at-done-regexp
3563 (concat "^" "\\(?:"
3564 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3565 "\\>")
3566 org-deadline-regexp (concat "\\<" org-deadline-string)
3567 org-deadline-time-regexp
3568 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3569 org-deadline-line-regexp
3570 (concat "\\<\\(" org-deadline-string "\\).*")
3571 org-scheduled-regexp
3572 (concat "\\<" org-scheduled-string)
3573 org-scheduled-time-regexp
3574 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3575 org-closed-time-regexp
3576 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3577 org-keyword-time-regexp
3578 (concat "\\<\\(" org-scheduled-string
3579 "\\|" org-deadline-string
3580 "\\|" org-closed-string
3581 "\\|" org-clock-string "\\)"
3582 " *[[<]\\([^]>]+\\)[]>]")
3583 org-keyword-time-not-clock-regexp
3584 (concat "\\<\\(" org-scheduled-string
3585 "\\|" org-deadline-string
3586 "\\|" org-closed-string
3587 "\\)"
3588 " *[[<]\\([^]>]+\\)[]>]")
3589 org-maybe-keyword-time-regexp
3590 (concat "\\(\\<\\(" org-scheduled-string
3591 "\\|" org-deadline-string
3592 "\\|" org-closed-string
3593 "\\|" org-clock-string "\\)\\)?"
3594 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3595 org-planning-or-clock-line-re
3596 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3597 "\\|" org-deadline-string
3598 "\\|" org-closed-string "\\|" org-clock-string
3599 "\\)\\>\\)")
3601 (org-compute-latex-and-specials-regexp)
3602 (org-set-font-lock-defaults))))
3604 (defun org-file-contents (file &optional noerror)
3605 "Return the contents of FILE, as a string."
3606 (if (or (not file)
3607 (not (file-readable-p file)))
3608 (if noerror
3609 (progn
3610 (message "Cannot read file %s" file)
3611 (ding) (sit-for 2)
3613 (error "Cannot read file %s" file))
3614 (with-temp-buffer
3615 (insert-file-contents file)
3616 (buffer-string))))
3618 (defun org-extract-log-state-settings (x)
3619 "Extract the log state setting from a TODO keyword string.
3620 This will extract info from a string like \"WAIT(w@/!)\"."
3621 (let (kw key log1 log2)
3622 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3623 (setq kw (match-string 1 x)
3624 key (and (match-end 2) (match-string 2 x))
3625 log1 (and (match-end 3) (match-string 3 x))
3626 log2 (and (match-end 4) (match-string 4 x)))
3627 (and (or log1 log2)
3628 (list kw
3629 (and log1 (if (equal log1 "!") 'time 'note))
3630 (and log2 (if (equal log2 "!") 'time 'note)))))))
3632 (defun org-remove-keyword-keys (list)
3633 "Remove a pair of parenthesis at the end of each string in LIST."
3634 (mapcar (lambda (x)
3635 (if (string-match "(.*)$" x)
3636 (substring x 0 (match-beginning 0))
3638 list))
3640 ;; FIXME: this could be done much better, using second characters etc.
3641 (defun org-assign-fast-keys (alist)
3642 "Assign fast keys to a keyword-key alist.
3643 Respect keys that are already there."
3644 (let (new e k c c1 c2 (char ?a))
3645 (while (setq e (pop alist))
3646 (cond
3647 ((equal e '(:startgroup)) (push e new))
3648 ((equal e '(:endgroup)) (push e new))
3649 ((equal e '(:newline)) (push e new))
3651 (setq k (car e) c2 nil)
3652 (if (cdr e)
3653 (setq c (cdr e))
3654 ;; automatically assign a character.
3655 (setq c1 (string-to-char
3656 (downcase (substring
3657 k (if (= (string-to-char k) ?@) 1 0)))))
3658 (if (or (rassoc c1 new) (rassoc c1 alist))
3659 (while (or (rassoc char new) (rassoc char alist))
3660 (setq char (1+ char)))
3661 (setq c2 c1))
3662 (setq c (or c2 char)))
3663 (push (cons k c) new))))
3664 (nreverse new)))
3666 ;;; Some variables used in various places
3668 (defvar org-window-configuration nil
3669 "Used in various places to store a window configuration.")
3670 (defvar org-finish-function nil
3671 "Function to be called when `C-c C-c' is used.
3672 This is for getting out of special buffers like remember.")
3675 ;; FIXME: Occasionally check by commenting these, to make sure
3676 ;; no other functions uses these, forgetting to let-bind them.
3677 (defvar entry)
3678 (defvar state)
3679 (defvar last-state)
3680 (defvar date)
3681 (defvar description)
3683 ;; Defined somewhere in this file, but used before definition.
3684 (defvar org-html-entities)
3685 (defvar org-struct-menu)
3686 (defvar org-org-menu)
3687 (defvar org-tbl-menu)
3688 (defvar org-agenda-keymap)
3690 ;;;; Define the Org-mode
3692 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3693 (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."))
3696 ;; We use a before-change function to check if a table might need
3697 ;; an update.
3698 (defvar org-table-may-need-update t
3699 "Indicates that a table might need an update.
3700 This variable is set by `org-before-change-function'.
3701 `org-table-align' sets it back to nil.")
3702 (defun org-before-change-function (beg end)
3703 "Every change indicates that a table might need an update."
3704 (setq org-table-may-need-update t))
3705 (defvar org-mode-map)
3706 (defvar org-mode-hook nil
3707 "Mode hook for Org-mode, run after the mode was turned on.")
3708 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3709 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3710 (defvar org-table-buffer-is-an nil)
3711 (defconst org-outline-regexp "\\*+ ")
3713 ;;;###autoload
3714 (define-derived-mode org-mode outline-mode "Org"
3715 "Outline-based notes management and organizer, alias
3716 \"Carsten's outline-mode for keeping track of everything.\"
3718 Org-mode develops organizational tasks around a NOTES file which
3719 contains information about projects as plain text. Org-mode is
3720 implemented on top of outline-mode, which is ideal to keep the content
3721 of large files well structured. It supports ToDo items, deadlines and
3722 time stamps, which magically appear in the diary listing of the Emacs
3723 calendar. Tables are easily created with a built-in table editor.
3724 Plain text URL-like links connect to websites, emails (VM), Usenet
3725 messages (Gnus), BBDB entries, and any files related to the project.
3726 For printing and sharing of notes, an Org-mode file (or a part of it)
3727 can be exported as a structured ASCII or HTML file.
3729 The following commands are available:
3731 \\{org-mode-map}"
3733 ;; Get rid of Outline menus, they are not needed
3734 ;; Need to do this here because define-derived-mode sets up
3735 ;; the keymap so late. Still, it is a waste to call this each time
3736 ;; we switch another buffer into org-mode.
3737 (if (featurep 'xemacs)
3738 (when (boundp 'outline-mode-menu-heading)
3739 ;; Assume this is Greg's port, it used easymenu
3740 (easy-menu-remove outline-mode-menu-heading)
3741 (easy-menu-remove outline-mode-menu-show)
3742 (easy-menu-remove outline-mode-menu-hide))
3743 (define-key org-mode-map [menu-bar headings] 'undefined)
3744 (define-key org-mode-map [menu-bar hide] 'undefined)
3745 (define-key org-mode-map [menu-bar show] 'undefined))
3747 (org-load-modules-maybe)
3748 (easy-menu-add org-org-menu)
3749 (easy-menu-add org-tbl-menu)
3750 (org-install-agenda-files-menu)
3751 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3752 (org-add-to-invisibility-spec '(org-cwidth))
3753 (when (featurep 'xemacs)
3754 (org-set-local 'line-move-ignore-invisible t))
3755 (org-set-local 'outline-regexp org-outline-regexp)
3756 (org-set-local 'outline-level 'org-outline-level)
3757 (when (and org-ellipsis
3758 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3759 (fboundp 'make-glyph-code))
3760 (unless org-display-table
3761 (setq org-display-table (make-display-table)))
3762 (set-display-table-slot
3763 org-display-table 4
3764 (vconcat (mapcar
3765 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3766 org-ellipsis)))
3767 (if (stringp org-ellipsis) org-ellipsis "..."))))
3768 (setq buffer-display-table org-display-table))
3769 (org-set-regexps-and-options)
3770 (when (and org-tag-faces (not org-tags-special-faces-re))
3771 ;; tag faces set outside customize.... force initialization.
3772 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3773 ;; Calc embedded
3774 (org-set-local 'calc-embedded-open-mode "# ")
3775 (modify-syntax-entry ?# "<")
3776 (modify-syntax-entry ?@ "w")
3777 (if org-startup-truncated (setq truncate-lines t))
3778 (org-set-local 'font-lock-unfontify-region-function
3779 'org-unfontify-region)
3780 ;; Activate before-change-function
3781 (org-set-local 'org-table-may-need-update t)
3782 (org-add-hook 'before-change-functions 'org-before-change-function nil
3783 'local)
3784 ;; Check for running clock before killing a buffer
3785 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3786 ;; Paragraphs and auto-filling
3787 (org-set-autofill-regexps)
3788 (setq indent-line-function 'org-indent-line-function)
3789 (org-update-radio-target-regexp)
3790 ;; Make sure dependence stuff works reliably, even for users who set it
3791 ;; too late :-(
3792 (if org-enforce-todo-dependencies
3793 (add-hook 'org-blocker-hook
3794 'org-block-todo-from-children-or-siblings)
3795 (remove-hook 'org-blocker-hook
3796 'org-block-todo-from-children-or-siblings))
3797 (if org-enforce-todo-checkbox-dependencies
3798 (add-hook 'org-blocker-hook
3799 'org-block-todo-from-checkboxes)
3800 (remove-hook 'org-blocker-hook
3801 'org-block-todo-from-checkboxes))
3803 ;; Comment characters
3804 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3805 (org-set-local 'comment-padding " ")
3807 ;; Align options lines
3808 (org-set-local
3809 'align-mode-rules-list
3810 '((org-in-buffer-settings
3811 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3812 (modes . '(org-mode)))))
3814 ;; Imenu
3815 (org-set-local 'imenu-create-index-function
3816 'org-imenu-get-tree)
3818 ;; Make isearch reveal context
3819 (if (or (featurep 'xemacs)
3820 (not (boundp 'outline-isearch-open-invisible-function)))
3821 ;; Emacs 21 and XEmacs make use of the hook
3822 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3823 ;; Emacs 22 deals with this through a special variable
3824 (org-set-local 'outline-isearch-open-invisible-function
3825 (lambda (&rest ignore) (org-show-context 'isearch))))
3827 ;; If empty file that did not turn on org-mode automatically, make it to.
3828 (if (and org-insert-mode-line-in-empty-file
3829 (interactive-p)
3830 (= (point-min) (point-max)))
3831 (insert "# -*- mode: org -*-\n\n"))
3833 (unless org-inhibit-startup
3834 (when org-startup-align-all-tables
3835 (let ((bmp (buffer-modified-p)))
3836 (org-table-map-tables 'org-table-align)
3837 (set-buffer-modified-p bmp)))
3838 (org-set-startup-visibility)))
3840 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3842 (defun org-current-time ()
3843 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3844 (if (> (car org-time-stamp-rounding-minutes) 1)
3845 (let ((r (car org-time-stamp-rounding-minutes))
3846 (time (decode-time)))
3847 (apply 'encode-time
3848 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3849 (nthcdr 2 time))))
3850 (current-time)))
3852 ;;;; Font-Lock stuff, including the activators
3854 (defvar org-mouse-map (make-sparse-keymap))
3855 (org-defkey org-mouse-map
3856 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3857 (org-defkey org-mouse-map
3858 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3859 (when org-mouse-1-follows-link
3860 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3861 (when org-tab-follows-link
3862 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3863 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3865 (require 'font-lock)
3867 (defconst org-non-link-chars "]\t\n\r<>")
3868 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3869 "shell" "elisp"))
3870 (defvar org-link-types-re nil
3871 "Matches a link that has a url-like prefix like \"http:\"")
3872 (defvar org-link-re-with-space nil
3873 "Matches a link with spaces, optional angular brackets around it.")
3874 (defvar org-link-re-with-space2 nil
3875 "Matches a link with spaces, optional angular brackets around it.")
3876 (defvar org-link-re-with-space3 nil
3877 "Matches a link with spaces, only for internal part in bracket links.")
3878 (defvar org-angle-link-re nil
3879 "Matches link with angular brackets, spaces are allowed.")
3880 (defvar org-plain-link-re nil
3881 "Matches plain link, without spaces.")
3882 (defvar org-bracket-link-regexp nil
3883 "Matches a link in double brackets.")
3884 (defvar org-bracket-link-analytic-regexp nil
3885 "Regular expression used to analyze links.
3886 Here is what the match groups contain after a match:
3887 1: http:
3888 2: http
3889 3: path
3890 4: [desc]
3891 5: desc")
3892 (defvar org-bracket-link-analytic-regexp++ nil
3893 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3894 (defvar org-any-link-re nil
3895 "Regular expression matching any link.")
3897 (defun org-make-link-regexps ()
3898 "Update the link regular expressions.
3899 This should be called after the variable `org-link-types' has changed."
3900 (setq org-link-types-re
3901 (concat
3902 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3903 org-link-re-with-space
3904 (concat
3905 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3906 "\\([^" org-non-link-chars " ]"
3907 "[^" org-non-link-chars "]*"
3908 "[^" org-non-link-chars " ]\\)>?")
3909 org-link-re-with-space2
3910 (concat
3911 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3912 "\\([^" org-non-link-chars " ]"
3913 "[^\t\n\r]*"
3914 "[^" org-non-link-chars " ]\\)>?")
3915 org-link-re-with-space3
3916 (concat
3917 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3918 "\\([^" org-non-link-chars " ]"
3919 "[^\t\n\r]*\\)")
3920 org-angle-link-re
3921 (concat
3922 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3923 "\\([^" org-non-link-chars " ]"
3924 "[^" org-non-link-chars "]*"
3925 "\\)>")
3926 org-plain-link-re
3927 (concat
3928 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3929 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3930 org-bracket-link-regexp
3931 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3932 org-bracket-link-analytic-regexp
3933 (concat
3934 "\\[\\["
3935 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3936 "\\([^]]+\\)"
3937 "\\]"
3938 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3939 "\\]")
3940 org-bracket-link-analytic-regexp++
3941 (concat
3942 "\\[\\["
3943 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3944 "\\([^]]+\\)"
3945 "\\]"
3946 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3947 "\\]")
3948 org-any-link-re
3949 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3950 org-angle-link-re "\\)\\|\\("
3951 org-plain-link-re "\\)")))
3953 (org-make-link-regexps)
3955 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3956 "Regular expression for fast time stamp matching.")
3957 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3958 "Regular expression for fast time stamp matching.")
3959 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3960 "Regular expression matching time strings for analysis.
3961 This one does not require the space after the date, so it can be used
3962 on a string that terminates immediately after the date.")
3963 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3964 "Regular expression matching time strings for analysis.")
3965 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3966 "Regular expression matching time stamps, with groups.")
3967 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3968 "Regular expression matching time stamps (also [..]), with groups.")
3969 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3970 "Regular expression matching a time stamp range.")
3971 (defconst org-tr-regexp-both
3972 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3973 "Regular expression matching a time stamp range.")
3974 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3975 org-ts-regexp "\\)?")
3976 "Regular expression matching a time stamp or time stamp range.")
3977 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3978 org-ts-regexp-both "\\)?")
3979 "Regular expression matching a time stamp or time stamp range.
3980 The time stamps may be either active or inactive.")
3982 (defvar org-emph-face nil)
3984 (defun org-do-emphasis-faces (limit)
3985 "Run through the buffer and add overlays to links."
3986 (let (rtn)
3987 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3988 (if (not (= (char-after (match-beginning 3))
3989 (char-after (match-beginning 4))))
3990 (progn
3991 (setq rtn t)
3992 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3993 'face
3994 (nth 1 (assoc (match-string 3)
3995 org-emphasis-alist)))
3996 (add-text-properties (match-beginning 2) (match-end 2)
3997 '(font-lock-multiline t))
3998 (when org-hide-emphasis-markers
3999 (add-text-properties (match-end 4) (match-beginning 5)
4000 '(invisible org-link))
4001 (add-text-properties (match-beginning 3) (match-end 3)
4002 '(invisible org-link)))))
4003 (backward-char 1))
4004 rtn))
4006 (defun org-emphasize (&optional char)
4007 "Insert or change an emphasis, i.e. a font like bold or italic.
4008 If there is an active region, change that region to a new emphasis.
4009 If there is no region, just insert the marker characters and position
4010 the cursor between them.
4011 CHAR should be either the marker character, or the first character of the
4012 HTML tag associated with that emphasis. If CHAR is a space, the means
4013 to remove the emphasis of the selected region.
4014 If char is not given (for example in an interactive call) it
4015 will be prompted for."
4016 (interactive)
4017 (let ((eal org-emphasis-alist) e det
4018 (erc org-emphasis-regexp-components)
4019 (prompt "")
4020 (string "") beg end move tag c s)
4021 (if (org-region-active-p)
4022 (setq beg (region-beginning) end (region-end)
4023 string (buffer-substring beg end))
4024 (setq move t))
4026 (while (setq e (pop eal))
4027 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4028 c (aref tag 0))
4029 (push (cons c (string-to-char (car e))) det)
4030 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4031 (substring tag 1)))))
4032 (setq det (nreverse det))
4033 (unless char
4034 (message "%s" (concat "Emphasis marker or tag:" prompt))
4035 (setq char (read-char-exclusive)))
4036 (setq char (or (cdr (assoc char det)) char))
4037 (if (equal char ?\ )
4038 (setq s "" move nil)
4039 (unless (assoc (char-to-string char) org-emphasis-alist)
4040 (error "No such emphasis marker: \"%c\"" char))
4041 (setq s (char-to-string char)))
4042 (while (and (> (length string) 1)
4043 (equal (substring string 0 1) (substring string -1))
4044 (assoc (substring string 0 1) org-emphasis-alist))
4045 (setq string (substring string 1 -1)))
4046 (setq string (concat s string s))
4047 (if beg (delete-region beg end))
4048 (unless (or (bolp)
4049 (string-match (concat "[" (nth 0 erc) "\n]")
4050 (char-to-string (char-before (point)))))
4051 (insert " "))
4052 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4053 (char-to-string (char-after (point))))
4054 (insert " ") (backward-char 1))
4055 (insert string)
4056 (and move (backward-char 1))))
4058 (defconst org-nonsticky-props
4059 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4062 (defun org-activate-plain-links (limit)
4063 "Run through the buffer and add overlays to links."
4064 (catch 'exit
4065 (let (f)
4066 (while (re-search-forward org-plain-link-re limit t)
4067 (setq f (get-text-property (match-beginning 0) 'face))
4068 (if (or (eq f 'org-tag)
4069 (and (listp f) (memq 'org-tag f)))
4071 (add-text-properties (match-beginning 0) (match-end 0)
4072 (list 'mouse-face 'highlight
4073 'rear-nonsticky org-nonsticky-props
4074 'keymap org-mouse-map
4076 (throw 'exit t))))))
4078 (defun org-activate-code (limit)
4079 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4080 (progn
4081 (remove-text-properties (match-beginning 0) (match-end 0)
4082 '(display t invisible t intangible t))
4083 t)))
4085 (defun org-activate-angle-links (limit)
4086 "Run through the buffer and add overlays to links."
4087 (if (re-search-forward org-angle-link-re limit t)
4088 (progn
4089 (add-text-properties (match-beginning 0) (match-end 0)
4090 (list 'mouse-face 'highlight
4091 'rear-nonsticky org-nonsticky-props
4092 'keymap org-mouse-map
4094 t)))
4096 (defun org-activate-footnote-links (limit)
4097 "Run through the buffer and add overlays to links."
4098 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4099 limit t)
4100 (progn
4101 (add-text-properties (match-beginning 2) (match-end 2)
4102 (list 'mouse-face 'highlight
4103 'rear-nonsticky org-nonsticky-props
4104 'keymap org-mouse-map
4105 'help-echo
4106 (if (= (point-at-bol) (match-beginning 2))
4107 "Footnote definition"
4108 "Footnote reference")
4110 t)))
4112 (defun org-activate-bracket-links (limit)
4113 "Run through the buffer and add overlays to bracketed links."
4114 (if (re-search-forward org-bracket-link-regexp limit t)
4115 (let* ((help (concat "LINK: "
4116 (org-match-string-no-properties 1)))
4117 ;; FIXME: above we should remove the escapes.
4118 ;; but that requires another match, protecting match data,
4119 ;; a lot of overhead for font-lock.
4120 (ip (org-maybe-intangible
4121 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4122 'keymap org-mouse-map 'mouse-face 'highlight
4123 'font-lock-multiline t 'help-echo help)))
4124 (vp (list 'rear-nonsticky org-nonsticky-props
4125 'keymap org-mouse-map 'mouse-face 'highlight
4126 'font-lock-multiline t 'help-echo help)))
4127 ;; We need to remove the invisible property here. Table narrowing
4128 ;; may have made some of this invisible.
4129 (remove-text-properties (match-beginning 0) (match-end 0)
4130 '(invisible nil))
4131 (if (match-end 3)
4132 (progn
4133 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4134 (add-text-properties (match-beginning 3) (match-end 3) vp)
4135 (add-text-properties (match-end 3) (match-end 0) ip))
4136 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4137 (add-text-properties (match-beginning 1) (match-end 1) vp)
4138 (add-text-properties (match-end 1) (match-end 0) ip))
4139 t)))
4141 (defun org-activate-dates (limit)
4142 "Run through the buffer and add overlays to dates."
4143 (if (re-search-forward org-tsr-regexp-both limit t)
4144 (progn
4145 (add-text-properties (match-beginning 0) (match-end 0)
4146 (list 'mouse-face 'highlight
4147 'rear-nonsticky org-nonsticky-props
4148 'keymap org-mouse-map))
4149 (when org-display-custom-times
4150 (if (match-end 3)
4151 (org-display-custom-time (match-beginning 3) (match-end 3)))
4152 (org-display-custom-time (match-beginning 1) (match-end 1)))
4153 t)))
4155 (defvar org-target-link-regexp nil
4156 "Regular expression matching radio targets in plain text.")
4157 (make-variable-buffer-local 'org-target-link-regexp)
4158 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4159 "Regular expression matching a link target.")
4160 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4161 "Regular expression matching a radio target.")
4162 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4163 "Regular expression matching any target.")
4165 (defun org-activate-target-links (limit)
4166 "Run through the buffer and add overlays to target matches."
4167 (when org-target-link-regexp
4168 (let ((case-fold-search t))
4169 (if (re-search-forward org-target-link-regexp limit t)
4170 (progn
4171 (add-text-properties (match-beginning 0) (match-end 0)
4172 (list 'mouse-face 'highlight
4173 'rear-nonsticky org-nonsticky-props
4174 'keymap org-mouse-map
4175 'help-echo "Radio target link"
4176 'org-linked-text t))
4177 t)))))
4179 (defun org-update-radio-target-regexp ()
4180 "Find all radio targets in this file and update the regular expression."
4181 (interactive)
4182 (when (memq 'radio org-activate-links)
4183 (setq org-target-link-regexp
4184 (org-make-target-link-regexp (org-all-targets 'radio)))
4185 (org-restart-font-lock)))
4187 (defun org-hide-wide-columns (limit)
4188 (let (s e)
4189 (setq s (text-property-any (point) (or limit (point-max))
4190 'org-cwidth t))
4191 (when s
4192 (setq e (next-single-property-change s 'org-cwidth))
4193 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4194 (goto-char e)
4195 t)))
4197 (defvar org-latex-and-specials-regexp nil
4198 "Regular expression for highlighting export special stuff.")
4199 (defvar org-match-substring-regexp)
4200 (defvar org-match-substring-with-braces-regexp)
4201 (defvar org-export-html-special-string-regexps)
4203 (defun org-compute-latex-and-specials-regexp ()
4204 "Compute regular expression for stuff treated specially by exporters."
4205 (if (not org-highlight-latex-fragments-and-specials)
4206 (org-set-local 'org-latex-and-specials-regexp nil)
4207 (require 'org-exp)
4208 (let*
4209 ((matchers (plist-get org-format-latex-options :matchers))
4210 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4211 org-latex-regexps)))
4212 (options (org-combine-plists (org-default-export-plist)
4213 (org-infile-export-plist)))
4214 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4215 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4216 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4217 (org-export-html-expand (plist-get options :expand-quoted-html))
4218 (org-export-with-special-strings (plist-get options :special-strings))
4219 (re-sub
4220 (cond
4221 ((equal org-export-with-sub-superscripts '{})
4222 (list org-match-substring-with-braces-regexp))
4223 (org-export-with-sub-superscripts
4224 (list org-match-substring-regexp))
4225 (t nil)))
4226 (re-latex
4227 (if org-export-with-LaTeX-fragments
4228 (mapcar (lambda (x) (nth 1 x)) latexs)))
4229 (re-macros
4230 (if org-export-with-TeX-macros
4231 (list (concat "\\\\"
4232 (regexp-opt
4233 (append (mapcar 'car org-html-entities)
4234 (if (boundp 'org-latex-entities)
4235 org-latex-entities nil))
4236 'words))) ; FIXME
4238 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4239 (re-special (if org-export-with-special-strings
4240 (mapcar (lambda (x) (car x))
4241 org-export-html-special-string-regexps)))
4242 (re-rest
4243 (delq nil
4244 (list
4245 (if org-export-html-expand "@<[^>\n]+>")
4246 ))))
4247 (org-set-local
4248 'org-latex-and-specials-regexp
4249 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4250 re-rest) "\\|")))))
4252 (defun org-do-latex-and-special-faces (limit)
4253 "Run through the buffer and add overlays to links."
4254 (when org-latex-and-specials-regexp
4255 (let (rtn d)
4256 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4257 limit t))
4258 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4259 'face))
4260 '(org-code org-verbatim underline)))
4261 (progn
4262 (setq rtn t
4263 d (cond ((member (char-after (1+ (match-beginning 0)))
4264 '(?_ ?^)) 1)
4265 (t 0)))
4266 (font-lock-prepend-text-property
4267 (+ d (match-beginning 0)) (match-end 0)
4268 'face 'org-latex-and-export-specials)
4269 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4270 '(font-lock-multiline t)))))
4271 rtn)))
4273 (defun org-restart-font-lock ()
4274 "Restart font-lock-mode, to force refontification."
4275 (when (and (boundp 'font-lock-mode) font-lock-mode)
4276 (font-lock-mode -1)
4277 (font-lock-mode 1)))
4279 (defun org-all-targets (&optional radio)
4280 "Return a list of all targets in this file.
4281 With optional argument RADIO, only find radio targets."
4282 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4283 rtn)
4284 (save-excursion
4285 (goto-char (point-min))
4286 (while (re-search-forward re nil t)
4287 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4288 rtn)))
4290 (defun org-make-target-link-regexp (targets)
4291 "Make regular expression matching all strings in TARGETS.
4292 The regular expression finds the targets also if there is a line break
4293 between words."
4294 (and targets
4295 (concat
4296 "\\<\\("
4297 (mapconcat
4298 (lambda (x)
4299 (while (string-match " +" x)
4300 (setq x (replace-match "\\s-+" t t x)))
4302 targets
4303 "\\|")
4304 "\\)\\>")))
4306 (defun org-activate-tags (limit)
4307 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4308 (progn
4309 (add-text-properties (match-beginning 1) (match-end 1)
4310 (list 'mouse-face 'highlight
4311 'rear-nonsticky org-nonsticky-props
4312 'keymap org-mouse-map))
4313 t)))
4315 (defun org-outline-level ()
4316 (save-excursion
4317 (looking-at outline-regexp)
4318 (if (match-beginning 1)
4319 (+ (org-get-string-indentation (match-string 1)) 1000)
4320 (1- (- (match-end 0) (match-beginning 0))))))
4322 (defvar org-font-lock-keywords nil)
4324 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4325 "Regular expression matching a property line.")
4327 (defvar org-font-lock-hook nil
4328 "Functions to be called for special font lock stuff.")
4330 (defun org-font-lock-hook (limit)
4331 (run-hook-with-args 'org-font-lock-hook limit))
4333 (defun org-set-font-lock-defaults ()
4334 (let* ((em org-fontify-emphasized-text)
4335 (lk org-activate-links)
4336 (org-font-lock-extra-keywords
4337 (list
4338 ;; Call the hook
4339 '(org-font-lock-hook)
4340 ;; Headlines
4341 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4342 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4343 ;; Table lines
4344 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4345 (1 'org-table t))
4346 ;; Table internals
4347 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4348 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4349 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4350 ;; Drawers
4351 (list org-drawer-regexp '(0 'org-special-keyword t))
4352 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4353 ;; Properties
4354 (list org-property-re
4355 '(1 'org-special-keyword t)
4356 '(3 'org-property-value t))
4357 (if org-format-transports-properties-p
4358 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4359 ;; Links
4360 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4361 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4362 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4363 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4364 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4365 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4366 (if (memq 'footnote lk) '(org-activate-footnote-links
4367 (2 'org-footnote t)))
4368 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4369 '(org-hide-wide-columns (0 nil append))
4370 ;; TODO lines
4371 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4372 '(1 (org-get-todo-face 1) t))
4373 ;; DONE
4374 (if org-fontify-done-headline
4375 (list (concat "^[*]+ +\\<\\("
4376 (mapconcat 'regexp-quote org-done-keywords "\\|")
4377 "\\)\\(.*\\)")
4378 '(2 'org-headline-done t))
4379 nil)
4380 ;; Priorities
4381 '(org-font-lock-add-priority-faces)
4382 ;; Tags
4383 '(org-font-lock-add-tag-faces)
4384 ;; Special keywords
4385 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4386 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4387 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4388 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4389 ;; Emphasis
4390 (if em
4391 (if (featurep 'xemacs)
4392 '(org-do-emphasis-faces (0 nil append))
4393 '(org-do-emphasis-faces)))
4394 ;; Checkboxes
4395 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4396 2 'org-checkbox prepend)
4397 (if org-provide-checkbox-statistics
4398 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4399 (0 (org-get-checkbox-statistics-face) t)))
4400 ;; Description list items
4401 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4402 2 'bold prepend)
4403 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4404 '(1 'org-archived prepend))
4405 ;; Specials
4406 '(org-do-latex-and-special-faces)
4407 ;; Code
4408 '(org-activate-code (1 'org-code t))
4409 ;; COMMENT
4410 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4411 "\\|" org-quote-string "\\)\\>")
4412 '(1 'org-special-keyword t))
4413 '("^#.*" (0 'font-lock-comment-face t))
4415 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4416 ;; Now set the full font-lock-keywords
4417 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4418 (org-set-local 'font-lock-defaults
4419 '(org-font-lock-keywords t nil nil backward-paragraph))
4420 (kill-local-variable 'font-lock-keywords) nil))
4422 (defvar org-m nil)
4423 (defvar org-l nil)
4424 (defvar org-f nil)
4425 (defun org-get-level-face (n)
4426 "Get the right face for match N in font-lock matching of headlines."
4427 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4428 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4429 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4430 (cond
4431 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4432 ((eq n 2) org-f)
4433 (t (if org-level-color-stars-only nil org-f))))
4435 (defun org-get-todo-face (kwd)
4436 "Get the right face for a TODO keyword KWD.
4437 If KWD is a number, get the corresponding match group."
4438 (if (numberp kwd) (setq kwd (match-string kwd)))
4439 (or (cdr (assoc kwd org-todo-keyword-faces))
4440 (and (member kwd org-done-keywords) 'org-done)
4441 'org-todo))
4443 (defun org-font-lock-add-tag-faces (limit)
4444 "Add the special tag faces."
4445 (when (and org-tag-faces org-tags-special-faces-re)
4446 (while (re-search-forward org-tags-special-faces-re limit t)
4447 (add-text-properties (match-beginning 1) (match-end 1)
4448 (list 'face (org-get-tag-face 1)
4449 'font-lock-fontified t))
4450 (backward-char 1))))
4452 (defun org-font-lock-add-priority-faces (limit)
4453 "Add the special priority faces."
4454 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4455 (add-text-properties
4456 (match-beginning 0) (match-end 0)
4457 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4458 org-priority-faces))
4459 'org-special-keyword)
4460 'font-lock-fontified t))))
4462 (defun org-get-tag-face (kwd)
4463 "Get the right face for a TODO keyword KWD.
4464 If KWD is a number, get the corresponding match group."
4465 (if (numberp kwd) (setq kwd (match-string kwd)))
4466 (or (cdr (assoc kwd org-tag-faces))
4467 'org-tag))
4469 (defun org-unfontify-region (beg end &optional maybe_loudly)
4470 "Remove fontification and activation overlays from links."
4471 (font-lock-default-unfontify-region beg end)
4472 (let* ((buffer-undo-list t)
4473 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4474 (inhibit-modification-hooks t)
4475 deactivate-mark buffer-file-name buffer-file-truename)
4476 (remove-text-properties beg end
4477 '(mouse-face t keymap t org-linked-text t
4478 invisible t intangible t))))
4480 ;;;; Visibility cycling, including org-goto and indirect buffer
4482 ;;; Cycling
4484 (defvar org-cycle-global-status nil)
4485 (make-variable-buffer-local 'org-cycle-global-status)
4486 (defvar org-cycle-subtree-status nil)
4487 (make-variable-buffer-local 'org-cycle-subtree-status)
4489 ;;;###autoload
4491 (defvar org-inlinetask-min-level)
4492 (defun org-cycle (&optional arg)
4493 "Visibility cycling for Org-mode.
4495 - When this function is called with a prefix argument, rotate the entire
4496 buffer through 3 states (global cycling)
4497 1. OVERVIEW: Show only top-level headlines.
4498 2. CONTENTS: Show all headlines of all levels, but no body text.
4499 3. SHOW ALL: Show everything.
4500 When called with two C-u C-u prefixes, switch to the startup visibility,
4501 determined by the variable `org-startup-folded', and by any VISIBILITY
4502 properties in the buffer.
4503 When called with three C-u C-u C-u prefixed, show the entire buffer,
4504 including drawers.
4506 - When point is at the beginning of a headline, rotate the subtree started
4507 by this line through 3 different states (local cycling)
4508 1. FOLDED: Only the main headline is shown.
4509 2. CHILDREN: The main headline and the direct children are shown.
4510 From this state, you can move to one of the children
4511 and zoom in further.
4512 3. SUBTREE: Show the entire subtree, including body text.
4514 - When there is a numeric prefix, go up to a heading with level ARG, do
4515 a `show-subtree' and return to the previous cursor position. If ARG
4516 is negative, go up that many levels.
4518 - When point is not at the beginning of a headline, execute the global
4519 binding for TAB, which is re-indenting the line. See the option
4520 `org-cycle-emulate-tab' for details.
4522 - Special case: if point is at the beginning of the buffer and there is
4523 no headline in line 1, this function will act as if called with prefix arg.
4524 But only if also the variable `org-cycle-global-at-bob' is t."
4525 (interactive "P")
4526 (org-load-modules-maybe)
4527 (let* ((limit-level
4528 (or org-cycle-max-level
4529 (and (boundp 'org-inlinetask-min-level)
4530 org-inlinetask-min-level
4531 (1- org-inlinetask-min-level))))
4532 (nstars (and limit-level
4533 (if org-odd-levels-only
4534 (and limit-level (1- (* limit-level 2)))
4535 limit-level)))
4536 (outline-regexp
4537 (cond
4538 ((not (org-mode-p)) outline-regexp)
4539 (org-cycle-include-plain-lists
4540 (concat "\\(?:\\*"
4541 (if nstars (format "\\{1,%d\\} " nstars) "+")
4542 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4543 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4544 (bob-special (and org-cycle-global-at-bob (bobp)
4545 (not (looking-at outline-regexp))))
4546 (org-cycle-hook
4547 (if bob-special
4548 (delq 'org-optimize-window-after-visibility-change
4549 (copy-sequence org-cycle-hook))
4550 org-cycle-hook))
4551 (pos (point)))
4553 (if (or bob-special (equal arg '(4)))
4554 ;; special case: use global cycling
4555 (setq arg t))
4557 (cond
4559 ((equal arg '(16))
4560 (org-set-startup-visibility)
4561 (message "Startup visibility, plus VISIBILITY properties"))
4563 ((equal arg '(64))
4564 (show-all)
4565 (message "Entire buffer visible, including drawers"))
4567 ((org-at-table-p 'any)
4568 ;; Enter the table or move to the next field in the table
4569 (or (org-table-recognize-table.el)
4570 (progn
4571 (if arg (org-table-edit-field t)
4572 (org-table-justify-field-maybe)
4573 (call-interactively 'org-table-next-field)))))
4575 ((eq arg t) ;; Global cycling
4577 (cond
4578 ((and (eq last-command this-command)
4579 (eq org-cycle-global-status 'overview))
4580 ;; We just created the overview - now do table of contents
4581 ;; This can be slow in very large buffers, so indicate action
4582 (message "CONTENTS...")
4583 (org-content)
4584 (message "CONTENTS...done")
4585 (setq org-cycle-global-status 'contents)
4586 (run-hook-with-args 'org-cycle-hook 'contents))
4588 ((and (eq last-command this-command)
4589 (eq org-cycle-global-status 'contents))
4590 ;; We just showed the table of contents - now show everything
4591 (show-all)
4592 (message "SHOW ALL")
4593 (setq org-cycle-global-status 'all)
4594 (run-hook-with-args 'org-cycle-hook 'all))
4597 ;; Default action: go to overview
4598 (org-overview)
4599 (message "OVERVIEW")
4600 (setq org-cycle-global-status 'overview)
4601 (run-hook-with-args 'org-cycle-hook 'overview))))
4603 ((and org-drawers org-drawer-regexp
4604 (save-excursion
4605 (beginning-of-line 1)
4606 (looking-at org-drawer-regexp)))
4607 ;; Toggle block visibility
4608 (org-flag-drawer
4609 (not (get-char-property (match-end 0) 'invisible))))
4611 ((integerp arg)
4612 ;; Show-subtree, ARG levels up from here.
4613 (save-excursion
4614 (org-back-to-heading)
4615 (outline-up-heading (if (< arg 0) (- arg)
4616 (- (funcall outline-level) arg)))
4617 (org-show-subtree)))
4619 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4620 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4621 ;; At a heading: rotate between three different views
4622 (org-back-to-heading)
4623 (let ((goal-column 0) eoh eol eos)
4624 ;; First, some boundaries
4625 (save-excursion
4626 (org-back-to-heading)
4627 (save-excursion
4628 (beginning-of-line 2)
4629 (while (and (not (eobp)) ;; this is like `next-line'
4630 (get-char-property (1- (point)) 'invisible))
4631 (beginning-of-line 2)) (setq eol (point)))
4632 (outline-end-of-heading) (setq eoh (point))
4633 (org-end-of-subtree t)
4634 (unless (eobp)
4635 (skip-chars-forward " \t\n")
4636 (beginning-of-line 1) ; in case this is an item
4638 (setq eos (1- (point))))
4639 ;; Find out what to do next and set `this-command'
4640 (cond
4641 ((= eos eoh)
4642 ;; Nothing is hidden behind this heading
4643 (message "EMPTY ENTRY")
4644 (setq org-cycle-subtree-status nil)
4645 (save-excursion
4646 (goto-char eos)
4647 (outline-next-heading)
4648 (if (org-invisible-p) (org-flag-heading nil))))
4649 ((or (>= eol eos)
4650 (not (string-match "\\S-" (buffer-substring eol eos))))
4651 ;; Entire subtree is hidden in one line: open it
4652 (org-show-entry)
4653 (show-children)
4654 (message "CHILDREN")
4655 (save-excursion
4656 (goto-char eos)
4657 (outline-next-heading)
4658 (if (org-invisible-p) (org-flag-heading nil)))
4659 (setq org-cycle-subtree-status 'children)
4660 (run-hook-with-args 'org-cycle-hook 'children))
4661 ((and (eq last-command this-command)
4662 (eq org-cycle-subtree-status 'children))
4663 ;; We just showed the children, now show everything.
4664 (org-show-subtree)
4665 (message "SUBTREE")
4666 (setq org-cycle-subtree-status 'subtree)
4667 (run-hook-with-args 'org-cycle-hook 'subtree))
4669 ;; Default action: hide the subtree.
4670 (hide-subtree)
4671 (message "FOLDED")
4672 (setq org-cycle-subtree-status 'folded)
4673 (run-hook-with-args 'org-cycle-hook 'folded)))))
4675 ;; TAB emulation and template completion
4676 (buffer-read-only (org-back-to-heading))
4678 ((org-try-structure-completion))
4680 ((org-try-cdlatex-tab))
4682 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4683 (or (not (bolp))
4684 (not (looking-at outline-regexp))))
4685 (call-interactively (global-key-binding "\t")))
4687 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4688 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4689 (or (and (eq org-cycle-emulate-tab 'white)
4690 (= (match-end 0) (point-at-eol)))
4691 (and (eq org-cycle-emulate-tab 'whitestart)
4692 (>= (match-end 0) pos))))
4694 (eq org-cycle-emulate-tab t))
4695 (call-interactively (global-key-binding "\t")))
4697 (t (save-excursion
4698 (org-back-to-heading)
4699 (org-cycle))))))
4701 ;;;###autoload
4702 (defun org-global-cycle (&optional arg)
4703 "Cycle the global visibility. For details see `org-cycle'.
4704 With C-u prefix arg, switch to startup visibility.
4705 With a numeric prefix, show all headlines up to that level."
4706 (interactive "P")
4707 (let ((org-cycle-include-plain-lists
4708 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4709 (cond
4710 ((integerp arg)
4711 (show-all)
4712 (hide-sublevels arg)
4713 (setq org-cycle-global-status 'contents))
4714 ((equal arg '(4))
4715 (org-set-startup-visibility)
4716 (message "Startup visibility, plus VISIBILITY properties."))
4718 (org-cycle '(4))))))
4720 (defun org-set-startup-visibility ()
4721 "Set the visibility required by startup options and properties."
4722 (cond
4723 ((eq org-startup-folded t)
4724 (org-cycle '(4)))
4725 ((eq org-startup-folded 'content)
4726 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4727 (org-cycle '(4)) (org-cycle '(4)))))
4728 (org-set-visibility-according-to-property 'no-cleanup)
4729 (org-cycle-hide-archived-subtrees 'all)
4730 (org-cycle-hide-drawers 'all)
4731 (org-cycle-show-empty-lines 'all))
4733 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4734 "Switch subtree visibilities according to :VISIBILITY: property."
4735 (interactive)
4736 (let (org-show-entry-below state)
4737 (save-excursion
4738 (goto-char (point-min))
4739 (while (re-search-forward
4740 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4741 nil t)
4742 (setq state (match-string 1))
4743 (save-excursion
4744 (org-back-to-heading t)
4745 (hide-subtree)
4746 (org-reveal)
4747 (cond
4748 ((equal state '("fold" "folded"))
4749 (hide-subtree))
4750 ((equal state "children")
4751 (org-show-hidden-entry)
4752 (show-children))
4753 ((equal state "content")
4754 (save-excursion
4755 (save-restriction
4756 (org-narrow-to-subtree)
4757 (org-content))))
4758 ((member state '("all" "showall"))
4759 (show-subtree)))))
4760 (unless no-cleanup
4761 (org-cycle-hide-archived-subtrees 'all)
4762 (org-cycle-hide-drawers 'all)
4763 (org-cycle-show-empty-lines 'all)))))
4765 (defun org-overview ()
4766 "Switch to overview mode, showing only top-level headlines.
4767 Really, this shows all headlines with level equal or greater than the level
4768 of the first headline in the buffer. This is important, because if the
4769 first headline is not level one, then (hide-sublevels 1) gives confusing
4770 results."
4771 (interactive)
4772 (let ((level (save-excursion
4773 (goto-char (point-min))
4774 (if (re-search-forward (concat "^" outline-regexp) nil t)
4775 (progn
4776 (goto-char (match-beginning 0))
4777 (funcall outline-level))))))
4778 (and level (hide-sublevels level))))
4780 (defun org-content (&optional arg)
4781 "Show all headlines in the buffer, like a table of contents.
4782 With numerical argument N, show content up to level N."
4783 (interactive "P")
4784 (save-excursion
4785 ;; Visit all headings and show their offspring
4786 (and (integerp arg) (org-overview))
4787 (goto-char (point-max))
4788 (catch 'exit
4789 (while (and (progn (condition-case nil
4790 (outline-previous-visible-heading 1)
4791 (error (goto-char (point-min))))
4793 (looking-at outline-regexp))
4794 (if (integerp arg)
4795 (show-children (1- arg))
4796 (show-branches))
4797 (if (bobp) (throw 'exit nil))))))
4800 (defun org-optimize-window-after-visibility-change (state)
4801 "Adjust the window after a change in outline visibility.
4802 This function is the default value of the hook `org-cycle-hook'."
4803 (when (get-buffer-window (current-buffer))
4804 (cond
4805 ((eq state 'content) nil)
4806 ((eq state 'all) nil)
4807 ((eq state 'folded) nil)
4808 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4809 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4811 (defun org-compact-display-after-subtree-move ()
4812 "Show a compacter version of the tree of the entry's parent."
4813 (save-excursion
4814 (if (org-up-heading-safe)
4815 (progn
4816 (hide-subtree)
4817 (show-entry)
4818 (show-children)
4819 (org-cycle-show-empty-lines 'children)
4820 (org-cycle-hide-drawers 'children))
4821 (org-overview))))
4823 (defun org-cycle-show-empty-lines (state)
4824 "Show empty lines above all visible headlines.
4825 The region to be covered depends on STATE when called through
4826 `org-cycle-hook'. Lisp program can use t for STATE to get the
4827 entire buffer covered. Note that an empty line is only shown if there
4828 are at least `org-cycle-separator-lines' empty lines before the headline."
4829 (when (> org-cycle-separator-lines 0)
4830 (save-excursion
4831 (let* ((n org-cycle-separator-lines)
4832 (re (cond
4833 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4834 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4835 (t (let ((ns (number-to-string (- n 2))))
4836 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4837 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4838 beg end)
4839 (cond
4840 ((memq state '(overview contents t))
4841 (setq beg (point-min) end (point-max)))
4842 ((memq state '(children folded))
4843 (setq beg (point) end (progn (org-end-of-subtree t t)
4844 (beginning-of-line 2)
4845 (point)))))
4846 (when beg
4847 (goto-char beg)
4848 (while (re-search-forward re end t)
4849 (if (not (get-char-property (match-end 1) 'invisible))
4850 (outline-flag-region
4851 (match-beginning 1) (match-end 1) nil)))))))
4852 ;; Never hide empty lines at the end of the file.
4853 (save-excursion
4854 (goto-char (point-max))
4855 (outline-previous-heading)
4856 (outline-end-of-heading)
4857 (if (and (looking-at "[ \t\n]+")
4858 (= (match-end 0) (point-max)))
4859 (outline-flag-region (point) (match-end 0) nil))))
4861 (defun org-show-empty-lines-in-parent ()
4862 "Move to the parent and re-show empty lines before visible headlines."
4863 (save-excursion
4864 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4865 (org-cycle-show-empty-lines context))))
4867 (defun org-cycle-hide-drawers (state)
4868 "Re-hide all drawers after a visibility state change."
4869 (when (and (org-mode-p)
4870 (not (memq state '(overview folded))))
4871 (save-excursion
4872 (let* ((globalp (memq state '(contents all)))
4873 (beg (if globalp (point-min) (point)))
4874 (end (if globalp (point-max) (org-end-of-subtree t))))
4875 (goto-char beg)
4876 (while (re-search-forward org-drawer-regexp end t)
4877 (org-flag-drawer t))))))
4879 (defun org-flag-drawer (flag)
4880 (save-excursion
4881 (beginning-of-line 1)
4882 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4883 (let ((b (match-end 0))
4884 (outline-regexp org-outline-regexp))
4885 (if (re-search-forward
4886 "^[ \t]*:END:"
4887 (save-excursion (outline-next-heading) (point)) t)
4888 (outline-flag-region b (point-at-eol) flag)
4889 (error ":END: line missing"))))))
4891 (defun org-subtree-end-visible-p ()
4892 "Is the end of the current subtree visible?"
4893 (pos-visible-in-window-p
4894 (save-excursion (org-end-of-subtree t) (point))))
4896 (defun org-first-headline-recenter (&optional N)
4897 "Move cursor to the first headline and recenter the headline.
4898 Optional argument N means, put the headline into the Nth line of the window."
4899 (goto-char (point-min))
4900 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4901 (beginning-of-line)
4902 (recenter (prefix-numeric-value N))))
4904 ;;; Org-goto
4906 (defvar org-goto-window-configuration nil)
4907 (defvar org-goto-marker nil)
4908 (defvar org-goto-map
4909 (let ((map (make-sparse-keymap)))
4910 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4911 (while (setq cmd (pop cmds))
4912 (substitute-key-definition cmd cmd map global-map)))
4913 (suppress-keymap map)
4914 (org-defkey map "\C-m" 'org-goto-ret)
4915 (org-defkey map [(return)] 'org-goto-ret)
4916 (org-defkey map [(left)] 'org-goto-left)
4917 (org-defkey map [(right)] 'org-goto-right)
4918 (org-defkey map [(control ?g)] 'org-goto-quit)
4919 (org-defkey map "\C-i" 'org-cycle)
4920 (org-defkey map [(tab)] 'org-cycle)
4921 (org-defkey map [(down)] 'outline-next-visible-heading)
4922 (org-defkey map [(up)] 'outline-previous-visible-heading)
4923 (if org-goto-auto-isearch
4924 (if (fboundp 'define-key-after)
4925 (define-key-after map [t] 'org-goto-local-auto-isearch)
4926 nil)
4927 (org-defkey map "q" 'org-goto-quit)
4928 (org-defkey map "n" 'outline-next-visible-heading)
4929 (org-defkey map "p" 'outline-previous-visible-heading)
4930 (org-defkey map "f" 'outline-forward-same-level)
4931 (org-defkey map "b" 'outline-backward-same-level)
4932 (org-defkey map "u" 'outline-up-heading))
4933 (org-defkey map "/" 'org-occur)
4934 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4935 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4936 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4937 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4938 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4939 map))
4941 (defconst org-goto-help
4942 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4943 RET=jump to location [Q]uit and return to previous location
4944 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4946 (defvar org-goto-start-pos) ; dynamically scoped parameter
4948 ;; FIXME: Docstring doe not mention both interfaces
4949 (defun org-goto (&optional alternative-interface)
4950 "Look up a different location in the current file, keeping current visibility.
4952 When you want look-up or go to a different location in a document, the
4953 fastest way is often to fold the entire buffer and then dive into the tree.
4954 This method has the disadvantage, that the previous location will be folded,
4955 which may not be what you want.
4957 This command works around this by showing a copy of the current buffer
4958 in an indirect buffer, in overview mode. You can dive into the tree in
4959 that copy, use org-occur and incremental search to find a location.
4960 When pressing RET or `Q', the command returns to the original buffer in
4961 which the visibility is still unchanged. After RET is will also jump to
4962 the location selected in the indirect buffer and expose the
4963 the headline hierarchy above."
4964 (interactive "P")
4965 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4966 (org-refile-use-outline-path t)
4967 (interface
4968 (if (not alternative-interface)
4969 org-goto-interface
4970 (if (eq org-goto-interface 'outline)
4971 'outline-path-completion
4972 'outline)))
4973 (org-goto-start-pos (point))
4974 (selected-point
4975 (if (eq interface 'outline)
4976 (car (org-get-location (current-buffer) org-goto-help))
4977 (nth 3 (org-refile-get-location "Goto: ")))))
4978 (if selected-point
4979 (progn
4980 (org-mark-ring-push org-goto-start-pos)
4981 (goto-char selected-point)
4982 (if (or (org-invisible-p) (org-invisible-p2))
4983 (org-show-context 'org-goto)))
4984 (message "Quit"))))
4986 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4987 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4988 (defvar org-goto-local-auto-isearch-map) ; defined below
4990 (defun org-get-location (buf help)
4991 "Let the user select a location in the Org-mode buffer BUF.
4992 This function uses a recursive edit. It returns the selected position
4993 or nil."
4994 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4995 (isearch-hide-immediately nil)
4996 (isearch-search-fun-function
4997 (lambda () 'org-goto-local-search-headings))
4998 (org-goto-selected-point org-goto-exit-command))
4999 (save-excursion
5000 (save-window-excursion
5001 (delete-other-windows)
5002 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5003 (switch-to-buffer
5004 (condition-case nil
5005 (make-indirect-buffer (current-buffer) "*org-goto*")
5006 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5007 (with-output-to-temp-buffer "*Help*"
5008 (princ help))
5009 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5010 (setq buffer-read-only nil)
5011 (let ((org-startup-truncated t)
5012 (org-startup-folded nil)
5013 (org-startup-align-all-tables nil))
5014 (org-mode)
5015 (org-overview))
5016 (setq buffer-read-only t)
5017 (if (and (boundp 'org-goto-start-pos)
5018 (integer-or-marker-p org-goto-start-pos))
5019 (let ((org-show-hierarchy-above t)
5020 (org-show-siblings t)
5021 (org-show-following-heading t))
5022 (goto-char org-goto-start-pos)
5023 (and (org-invisible-p) (org-show-context)))
5024 (goto-char (point-min)))
5025 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5026 (message "Select location and press RET")
5027 (use-local-map org-goto-map)
5028 (recursive-edit)
5030 (kill-buffer "*org-goto*")
5031 (cons org-goto-selected-point org-goto-exit-command)))
5033 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5034 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5035 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5036 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5038 (defun org-goto-local-search-headings (string bound noerror)
5039 "Search and make sure that any matches are in headlines."
5040 (catch 'return
5041 (while (if isearch-forward
5042 (search-forward string bound noerror)
5043 (search-backward string bound noerror))
5044 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5045 (and (member :headline context)
5046 (not (member :tags context))))
5047 (throw 'return (point))))))
5049 (defun org-goto-local-auto-isearch ()
5050 "Start isearch."
5051 (interactive)
5052 (goto-char (point-min))
5053 (let ((keys (this-command-keys)))
5054 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5055 (isearch-mode t)
5056 (isearch-process-search-char (string-to-char keys)))))
5058 (defun org-goto-ret (&optional arg)
5059 "Finish `org-goto' by going to the new location."
5060 (interactive "P")
5061 (setq org-goto-selected-point (point)
5062 org-goto-exit-command 'return)
5063 (throw 'exit nil))
5065 (defun org-goto-left ()
5066 "Finish `org-goto' by going to the new location."
5067 (interactive)
5068 (if (org-on-heading-p)
5069 (progn
5070 (beginning-of-line 1)
5071 (setq org-goto-selected-point (point)
5072 org-goto-exit-command 'left)
5073 (throw 'exit nil))
5074 (error "Not on a heading")))
5076 (defun org-goto-right ()
5077 "Finish `org-goto' by going to the new location."
5078 (interactive)
5079 (if (org-on-heading-p)
5080 (progn
5081 (setq org-goto-selected-point (point)
5082 org-goto-exit-command 'right)
5083 (throw 'exit nil))
5084 (error "Not on a heading")))
5086 (defun org-goto-quit ()
5087 "Finish `org-goto' without cursor motion."
5088 (interactive)
5089 (setq org-goto-selected-point nil)
5090 (setq org-goto-exit-command 'quit)
5091 (throw 'exit nil))
5093 ;;; Indirect buffer display of subtrees
5095 (defvar org-indirect-dedicated-frame nil
5096 "This is the frame being used for indirect tree display.")
5097 (defvar org-last-indirect-buffer nil)
5099 (defun org-tree-to-indirect-buffer (&optional arg)
5100 "Create indirect buffer and narrow it to current subtree.
5101 With numerical prefix ARG, go up to this level and then take that tree.
5102 If ARG is negative, go up that many levels.
5103 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5104 indirect buffer previously made with this command, to avoid proliferation of
5105 indirect buffers. However, when you call the command with a `C-u' prefix, or
5106 when `org-indirect-buffer-display' is `new-frame', the last buffer
5107 is kept so that you can work with several indirect buffers at the same time.
5108 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5109 requests that a new frame be made for the new buffer, so that the dedicated
5110 frame is not changed."
5111 (interactive "P")
5112 (let ((cbuf (current-buffer))
5113 (cwin (selected-window))
5114 (pos (point))
5115 beg end level heading ibuf)
5116 (save-excursion
5117 (org-back-to-heading t)
5118 (when (numberp arg)
5119 (setq level (org-outline-level))
5120 (if (< arg 0) (setq arg (+ level arg)))
5121 (while (> (setq level (org-outline-level)) arg)
5122 (outline-up-heading 1 t)))
5123 (setq beg (point)
5124 heading (org-get-heading))
5125 (org-end-of-subtree t) (setq end (point)))
5126 (if (and (buffer-live-p org-last-indirect-buffer)
5127 (not (eq org-indirect-buffer-display 'new-frame))
5128 (not arg))
5129 (kill-buffer org-last-indirect-buffer))
5130 (setq ibuf (org-get-indirect-buffer cbuf)
5131 org-last-indirect-buffer ibuf)
5132 (cond
5133 ((or (eq org-indirect-buffer-display 'new-frame)
5134 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5135 (select-frame (make-frame))
5136 (delete-other-windows)
5137 (switch-to-buffer ibuf)
5138 (org-set-frame-title heading))
5139 ((eq org-indirect-buffer-display 'dedicated-frame)
5140 (raise-frame
5141 (select-frame (or (and org-indirect-dedicated-frame
5142 (frame-live-p org-indirect-dedicated-frame)
5143 org-indirect-dedicated-frame)
5144 (setq org-indirect-dedicated-frame (make-frame)))))
5145 (delete-other-windows)
5146 (switch-to-buffer ibuf)
5147 (org-set-frame-title (concat "Indirect: " heading)))
5148 ((eq org-indirect-buffer-display 'current-window)
5149 (switch-to-buffer ibuf))
5150 ((eq org-indirect-buffer-display 'other-window)
5151 (pop-to-buffer ibuf))
5152 (t (error "Invalid value.")))
5153 (if (featurep 'xemacs)
5154 (save-excursion (org-mode) (turn-on-font-lock)))
5155 (narrow-to-region beg end)
5156 (show-all)
5157 (goto-char pos)
5158 (and (window-live-p cwin) (select-window cwin))))
5160 (defun org-get-indirect-buffer (&optional buffer)
5161 (setq buffer (or buffer (current-buffer)))
5162 (let ((n 1) (base (buffer-name buffer)) bname)
5163 (while (buffer-live-p
5164 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5165 (setq n (1+ n)))
5166 (condition-case nil
5167 (make-indirect-buffer buffer bname 'clone)
5168 (error (make-indirect-buffer buffer bname)))))
5170 (defun org-set-frame-title (title)
5171 "Set the title of the current frame to the string TITLE."
5172 ;; FIXME: how to name a single frame in XEmacs???
5173 (unless (featurep 'xemacs)
5174 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5176 ;;;; Structure editing
5178 ;;; Inserting headlines
5180 (defun org-previous-line-empty-p ()
5181 (save-excursion
5182 (and (not (bobp))
5183 (or (beginning-of-line 0) t)
5184 (save-match-data
5185 (looking-at "[ \t]*$")))))
5187 (defun org-insert-heading (&optional force-heading)
5188 "Insert a new heading or item with same depth at point.
5189 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5190 If point is at the beginning of a headline, insert a sibling before the
5191 current headline. If point is not at the beginning, do not split the line,
5192 but create the new headline after the current line."
5193 (interactive "P")
5194 (if (= (buffer-size) 0)
5195 (insert "\n* ")
5196 (when (or force-heading (not (org-insert-item)))
5197 (let* ((empty-line-p nil)
5198 (head (save-excursion
5199 (condition-case nil
5200 (progn
5201 (org-back-to-heading)
5202 (setq empty-line-p (org-previous-line-empty-p))
5203 (match-string 0))
5204 (error "*"))))
5205 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5206 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5207 pos hide-previous previous-pos)
5208 (cond
5209 ((and (org-on-heading-p) (bolp)
5210 (or (bobp)
5211 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5212 ;; insert before the current line
5213 (open-line (if blank 2 1)))
5214 ((and (bolp)
5215 (or (bobp)
5216 (save-excursion
5217 (backward-char 1) (not (org-invisible-p)))))
5218 ;; insert right here
5219 nil)
5221 ;; somewhere in the line
5222 (save-excursion
5223 (setq previous-pos (point-at-bol))
5224 (end-of-line)
5225 (setq hide-previous (org-invisible-p)))
5226 (and org-insert-heading-respect-content (org-show-subtree))
5227 (let ((split
5228 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5229 (save-excursion
5230 (let ((p (point)))
5231 (goto-char (point-at-bol))
5232 (and (looking-at org-complex-heading-regexp)
5233 (> p (match-beginning 4)))))))
5234 tags pos)
5235 (cond
5236 (org-insert-heading-respect-content
5237 (org-end-of-subtree nil t)
5238 (or (bolp) (newline))
5239 (or (org-previous-line-empty-p)
5240 (and blank (newline)))
5241 (open-line 1))
5242 ((org-on-heading-p)
5243 (when hide-previous
5244 (show-children)
5245 (org-show-entry))
5246 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5247 (setq tags (and (match-end 2) (match-string 2)))
5248 (and (match-end 1)
5249 (delete-region (match-beginning 1) (match-end 1)))
5250 (setq pos (point-at-bol))
5251 (or split (end-of-line 1))
5252 (delete-horizontal-space)
5253 (newline (if blank 2 1))
5254 (when tags
5255 (save-excursion
5256 (goto-char pos)
5257 (end-of-line 1)
5258 (insert " " tags)
5259 (org-set-tags nil 'align))))
5261 (or split (end-of-line 1))
5262 (newline (if blank 2 1)))))))
5263 (insert head) (just-one-space)
5264 (setq pos (point))
5265 (end-of-line 1)
5266 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5267 (when (and org-insert-heading-respect-content hide-previous)
5268 (save-excursion
5269 (goto-char previous-pos)
5270 (hide-subtree)))
5271 (run-hooks 'org-insert-heading-hook)))))
5273 (defun org-get-heading (&optional no-tags)
5274 "Return the heading of the current entry, without the stars."
5275 (save-excursion
5276 (org-back-to-heading t)
5277 (if (looking-at
5278 (if no-tags
5279 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5280 "\\*+[ \t]+\\([^\r\n]*\\)"))
5281 (match-string 1) "")))
5283 (defun org-heading-components ()
5284 "Return the components of the current heading.
5285 This is a list with the following elements:
5286 - the level as an integer
5287 - the reduced level, different if `org-odd-levels-only' is set.
5288 - the TODO keyword, or nil
5289 - the priority character, like ?A, or nil if no priority is given
5290 - the headline text itself, or the tags string if no headline text
5291 - the tags string, or nil."
5292 (save-excursion
5293 (org-back-to-heading t)
5294 (if (looking-at org-complex-heading-regexp)
5295 (list (length (match-string 1))
5296 (org-reduced-level (length (match-string 1)))
5297 (org-match-string-no-properties 2)
5298 (and (match-end 3) (aref (match-string 3) 2))
5299 (org-match-string-no-properties 4)
5300 (org-match-string-no-properties 5)))))
5302 (defun org-insert-heading-after-current ()
5303 "Insert a new heading with same level as current, after current subtree."
5304 (interactive)
5305 (org-back-to-heading)
5306 (org-insert-heading)
5307 (org-move-subtree-down)
5308 (end-of-line 1))
5310 (defun org-insert-heading-respect-content ()
5311 (interactive)
5312 (let ((org-insert-heading-respect-content t))
5313 (org-insert-heading t)))
5315 (defun org-insert-todo-heading-respect-content (&optional force-state)
5316 (interactive "P")
5317 (let ((org-insert-heading-respect-content t))
5318 (org-insert-todo-heading force-state t)))
5320 (defun org-insert-todo-heading (arg &optional force-heading)
5321 "Insert a new heading with the same level and TODO state as current heading.
5322 If the heading has no TODO state, or if the state is DONE, use the first
5323 state (TODO by default). Also with prefix arg, force first state."
5324 (interactive "P")
5325 (when (or force-heading (not (org-insert-item 'checkbox)))
5326 (org-insert-heading force-heading)
5327 (save-excursion
5328 (org-back-to-heading)
5329 (outline-previous-heading)
5330 (looking-at org-todo-line-regexp))
5331 (let*
5332 ((new-mark-x
5333 (if (or arg
5334 (not (match-beginning 2))
5335 (member (match-string 2) org-done-keywords))
5336 (car org-todo-keywords-1)
5337 (match-string 2)))
5338 (new-mark
5340 (run-hook-with-args-until-success
5341 'org-todo-get-default-hook new-mark-x nil)
5342 new-mark-x)))
5343 (beginning-of-line 1)
5344 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5345 (insert new-mark " ")))
5346 (when org-provide-todo-statistics
5347 (org-update-parent-todo-statistics))))
5349 (defun org-insert-subheading (arg)
5350 "Insert a new subheading and demote it.
5351 Works for outline headings and for plain lists alike."
5352 (interactive "P")
5353 (org-insert-heading arg)
5354 (cond
5355 ((org-on-heading-p) (org-do-demote))
5356 ((org-at-item-p) (org-indent-item 1))))
5358 (defun org-insert-todo-subheading (arg)
5359 "Insert a new subheading with TODO keyword or checkbox and demote it.
5360 Works for outline headings and for plain lists alike."
5361 (interactive "P")
5362 (org-insert-todo-heading arg)
5363 (cond
5364 ((org-on-heading-p) (org-do-demote))
5365 ((org-at-item-p) (org-indent-item 1))))
5367 ;;; Promotion and Demotion
5369 (defun org-promote-subtree ()
5370 "Promote the entire subtree.
5371 See also `org-promote'."
5372 (interactive)
5373 (save-excursion
5374 (org-map-tree 'org-promote))
5375 (org-fix-position-after-promote))
5377 (defun org-demote-subtree ()
5378 "Demote the entire subtree. See `org-demote'.
5379 See also `org-promote'."
5380 (interactive)
5381 (save-excursion
5382 (org-map-tree 'org-demote))
5383 (org-fix-position-after-promote))
5386 (defun org-do-promote ()
5387 "Promote the current heading higher up the tree.
5388 If the region is active in `transient-mark-mode', promote all headings
5389 in the region."
5390 (interactive)
5391 (save-excursion
5392 (if (org-region-active-p)
5393 (org-map-region 'org-promote (region-beginning) (region-end))
5394 (org-promote)))
5395 (org-fix-position-after-promote))
5397 (defun org-do-demote ()
5398 "Demote the current heading lower down the tree.
5399 If the region is active in `transient-mark-mode', demote all headings
5400 in the region."
5401 (interactive)
5402 (save-excursion
5403 (if (org-region-active-p)
5404 (org-map-region 'org-demote (region-beginning) (region-end))
5405 (org-demote)))
5406 (org-fix-position-after-promote))
5408 (defun org-fix-position-after-promote ()
5409 "Make sure that after pro/demotion cursor position is right."
5410 (let ((pos (point)))
5411 (when (save-excursion
5412 (beginning-of-line 1)
5413 (looking-at org-todo-line-regexp)
5414 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5415 (cond ((eobp) (insert " "))
5416 ((eolp) (insert " "))
5417 ((equal (char-after) ?\ ) (forward-char 1))))))
5419 (defun org-reduced-level (l)
5420 "Compute the effective level of a heading.
5421 This takes into account the setting of `org-odd-levels-only'."
5422 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5424 (defun org-get-valid-level (level &optional change)
5425 "Rectify a level change under the influence of `org-odd-levels-only'
5426 LEVEL is a current level, CHANGE is by how much the level should be
5427 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5428 even level numbers will become the next higher odd number."
5429 (if org-odd-levels-only
5430 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5431 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5432 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5433 (max 1 (+ level (or change 0)))))
5435 (if (boundp 'define-obsolete-function-alias)
5436 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5437 (define-obsolete-function-alias 'org-get-legal-level
5438 'org-get-valid-level)
5439 (define-obsolete-function-alias 'org-get-legal-level
5440 'org-get-valid-level "23.1")))
5442 (defun org-promote ()
5443 "Promote the current heading higher up the tree.
5444 If the region is active in `transient-mark-mode', promote all headings
5445 in the region."
5446 (org-back-to-heading t)
5447 (let* ((level (save-match-data (funcall outline-level)))
5448 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5449 (diff (abs (- level (length up-head) -1))))
5450 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5451 (replace-match up-head nil t)
5452 ;; Fixup tag positioning
5453 (and org-auto-align-tags (org-set-tags nil t))
5454 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5456 (defun org-demote ()
5457 "Demote the current heading lower down the tree.
5458 If the region is active in `transient-mark-mode', demote all headings
5459 in the region."
5460 (org-back-to-heading t)
5461 (let* ((level (save-match-data (funcall outline-level)))
5462 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5463 (diff (abs (- level (length down-head) -1))))
5464 (replace-match down-head nil t)
5465 ;; Fixup tag positioning
5466 (and org-auto-align-tags (org-set-tags nil t))
5467 (if org-adapt-indentation (org-fixup-indentation diff))))
5469 (defun org-map-tree (fun)
5470 "Call FUN for every heading underneath the current one."
5471 (org-back-to-heading)
5472 (let ((level (funcall outline-level)))
5473 (save-excursion
5474 (funcall fun)
5475 (while (and (progn
5476 (outline-next-heading)
5477 (> (funcall outline-level) level))
5478 (not (eobp)))
5479 (funcall fun)))))
5481 (defun org-map-region (fun beg end)
5482 "Call FUN for every heading between BEG and END."
5483 (let ((org-ignore-region t))
5484 (save-excursion
5485 (setq end (copy-marker end))
5486 (goto-char beg)
5487 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5488 (< (point) end))
5489 (funcall fun))
5490 (while (and (progn
5491 (outline-next-heading)
5492 (< (point) end))
5493 (not (eobp)))
5494 (funcall fun)))))
5496 (defun org-fixup-indentation (diff)
5497 "Change the indentation in the current entry by DIFF
5498 However, if any line in the current entry has no indentation, or if it
5499 would end up with no indentation after the change, nothing at all is done."
5500 (save-excursion
5501 (let ((end (save-excursion (outline-next-heading)
5502 (point-marker)))
5503 (prohibit (if (> diff 0)
5504 "^\\S-"
5505 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5506 col)
5507 (unless (save-excursion (end-of-line 1)
5508 (re-search-forward prohibit end t))
5509 (while (and (< (point) end)
5510 (re-search-forward "^[ \t]+" end t))
5511 (goto-char (match-end 0))
5512 (setq col (current-column))
5513 (if (< diff 0) (replace-match ""))
5514 (org-indent-to-column (+ diff col))))
5515 (move-marker end nil))))
5517 (defun org-convert-to-odd-levels ()
5518 "Convert an org-mode file with all levels allowed to one with odd levels.
5519 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5520 level 5 etc."
5521 (interactive)
5522 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5523 (let ((org-odd-levels-only nil) n)
5524 (save-excursion
5525 (goto-char (point-min))
5526 (while (re-search-forward "^\\*\\*+ " nil t)
5527 (setq n (- (length (match-string 0)) 2))
5528 (while (>= (setq n (1- n)) 0)
5529 (org-demote))
5530 (end-of-line 1))))))
5533 (defun org-convert-to-oddeven-levels ()
5534 "Convert an org-mode file with only odd levels to one with odd and even levels.
5535 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5536 section with an even level, conversion would destroy the structure of the file. An error
5537 is signaled in this case."
5538 (interactive)
5539 (goto-char (point-min))
5540 ;; First check if there are no even levels
5541 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5542 (org-show-context t)
5543 (error "Not all levels are odd in this file. Conversion not possible."))
5544 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5545 (let ((org-odd-levels-only nil) n)
5546 (save-excursion
5547 (goto-char (point-min))
5548 (while (re-search-forward "^\\*\\*+ " nil t)
5549 (setq n (/ (1- (length (match-string 0))) 2))
5550 (while (>= (setq n (1- n)) 0)
5551 (org-promote))
5552 (end-of-line 1))))))
5554 (defun org-tr-level (n)
5555 "Make N odd if required."
5556 (if org-odd-levels-only (1+ (/ n 2)) n))
5558 ;;; Vertical tree motion, cutting and pasting of subtrees
5560 (defun org-move-subtree-up (&optional arg)
5561 "Move the current subtree up past ARG headlines of the same level."
5562 (interactive "p")
5563 (org-move-subtree-down (- (prefix-numeric-value arg))))
5565 (defun org-move-subtree-down (&optional arg)
5566 "Move the current subtree down past ARG headlines of the same level."
5567 (interactive "p")
5568 (setq arg (prefix-numeric-value arg))
5569 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5570 'outline-get-last-sibling))
5571 (ins-point (make-marker))
5572 (cnt (abs arg))
5573 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5574 ;; Select the tree
5575 (org-back-to-heading)
5576 (setq beg0 (point))
5577 (save-excursion
5578 (setq ne-beg (org-back-over-empty-lines))
5579 (setq beg (point)))
5580 (save-match-data
5581 (save-excursion (outline-end-of-heading)
5582 (setq folded (org-invisible-p)))
5583 (outline-end-of-subtree))
5584 (outline-next-heading)
5585 (setq ne-end (org-back-over-empty-lines))
5586 (setq end (point))
5587 (goto-char beg0)
5588 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5589 ;; include less whitespace
5590 (save-excursion
5591 (goto-char beg)
5592 (forward-line (- ne-beg ne-end))
5593 (setq beg (point))))
5594 ;; Find insertion point, with error handling
5595 (while (> cnt 0)
5596 (or (and (funcall movfunc) (looking-at outline-regexp))
5597 (progn (goto-char beg0)
5598 (error "Cannot move past superior level or buffer limit")))
5599 (setq cnt (1- cnt)))
5600 (if (> arg 0)
5601 ;; Moving forward - still need to move over subtree
5602 (progn (org-end-of-subtree t t)
5603 (save-excursion
5604 (org-back-over-empty-lines)
5605 (or (bolp) (newline)))))
5606 (setq ne-ins (org-back-over-empty-lines))
5607 (move-marker ins-point (point))
5608 (setq txt (buffer-substring beg end))
5609 (org-save-markers-in-region beg end)
5610 (delete-region beg end)
5611 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5612 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5613 (and (not (bolp)) (looking-at "\n") (forward-char 1))
5614 (let ((bbb (point)))
5615 (insert-before-markers txt)
5616 (org-reinstall-markers-in-region bbb)
5617 (move-marker ins-point bbb))
5618 (or (bolp) (insert "\n"))
5619 (setq ins-end (point))
5620 (goto-char ins-point)
5621 (org-skip-whitespace)
5622 (when (and (< arg 0)
5623 (org-first-sibling-p)
5624 (> ne-ins ne-beg))
5625 ;; Move whitespace back to beginning
5626 (save-excursion
5627 (goto-char ins-end)
5628 (let ((kill-whole-line t))
5629 (kill-line (- ne-ins ne-beg)) (point)))
5630 (insert (make-string (- ne-ins ne-beg) ?\n)))
5631 (move-marker ins-point nil)
5632 (org-compact-display-after-subtree-move)
5633 (org-show-empty-lines-in-parent)
5634 (unless folded
5635 (org-show-entry)
5636 (show-children)
5637 (org-cycle-hide-drawers 'children))))
5639 (defvar org-subtree-clip ""
5640 "Clipboard for cut and paste of subtrees.
5641 This is actually only a copy of the kill, because we use the normal kill
5642 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5644 (defvar org-subtree-clip-folded nil
5645 "Was the last copied subtree folded?
5646 This is used to fold the tree back after pasting.")
5648 (defun org-cut-subtree (&optional n)
5649 "Cut the current subtree into the clipboard.
5650 With prefix arg N, cut this many sequential subtrees.
5651 This is a short-hand for marking the subtree and then cutting it."
5652 (interactive "p")
5653 (org-copy-subtree n 'cut))
5655 (defun org-copy-subtree (&optional n cut force-store-markers)
5656 "Cut the current subtree into the clipboard.
5657 With prefix arg N, cut this many sequential subtrees.
5658 This is a short-hand for marking the subtree and then copying it.
5659 If CUT is non-nil, actually cut the subtree.
5660 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5661 of some markers in the region, even if CUT is non-nil. This is
5662 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5663 (interactive "p")
5664 (let (beg end folded (beg0 (point)))
5665 (if (interactive-p)
5666 (org-back-to-heading nil) ; take what looks like a subtree
5667 (org-back-to-heading t)) ; take what is really there
5668 (org-back-over-empty-lines)
5669 (setq beg (point))
5670 (skip-chars-forward " \t\r\n")
5671 (save-match-data
5672 (save-excursion (outline-end-of-heading)
5673 (setq folded (org-invisible-p)))
5674 (condition-case nil
5675 (outline-forward-same-level (1- n))
5676 (error nil))
5677 (org-end-of-subtree t t))
5678 (org-back-over-empty-lines)
5679 (setq end (point))
5680 (goto-char beg0)
5681 (when (> end beg)
5682 (setq org-subtree-clip-folded folded)
5683 (when (or cut force-store-markers)
5684 (org-save-markers-in-region beg end))
5685 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5686 (setq org-subtree-clip (current-kill 0))
5687 (message "%s: Subtree(s) with %d characters"
5688 (if cut "Cut" "Copied")
5689 (length org-subtree-clip)))))
5691 (defun org-paste-subtree (&optional level tree for-yank)
5692 "Paste the clipboard as a subtree, with modification of headline level.
5693 The entire subtree is promoted or demoted in order to match a new headline
5694 level.
5696 If the cursor is at the beginning of a headline, the same level as
5697 that headline is used to paste the tree
5699 If not, the new level is derived from the *visible* headings
5700 before and after the insertion point, and taken to be the inferior headline
5701 level of the two. So if the previous visible heading is level 3 and the
5702 next is level 4 (or vice versa), level 4 will be used for insertion.
5703 This makes sure that the subtree remains an independent subtree and does
5704 not swallow low level entries.
5706 You can also force a different level, either by using a numeric prefix
5707 argument, or by inserting the heading marker by hand. For example, if the
5708 cursor is after \"*****\", then the tree will be shifted to level 5.
5710 If optional TREE is given, use this text instead of the kill ring.
5712 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5713 move back over whitespace before inserting, and move point to the end of
5714 the inserted text when done."
5715 (interactive "P")
5716 (unless (org-kill-is-subtree-p tree)
5717 (error "%s"
5718 (substitute-command-keys
5719 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5720 (let* ((visp (not (org-invisible-p)))
5721 (txt (or tree (and kill-ring (current-kill 0))))
5722 (^re (concat "^\\(" outline-regexp "\\)"))
5723 (re (concat "\\(" outline-regexp "\\)"))
5724 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5726 (old-level (if (string-match ^re txt)
5727 (- (match-end 0) (match-beginning 0) 1)
5728 -1))
5729 (force-level (cond (level (prefix-numeric-value level))
5730 ((and (looking-at "[ \t]*$")
5731 (string-match
5732 ^re_ (buffer-substring
5733 (point-at-bol) (point))))
5734 (- (match-end 1) (match-beginning 1)))
5735 ((and (bolp)
5736 (looking-at org-outline-regexp))
5737 (- (match-end 0) (point) 1))
5738 (t nil)))
5739 (previous-level (save-excursion
5740 (condition-case nil
5741 (progn
5742 (outline-previous-visible-heading 1)
5743 (if (looking-at re)
5744 (- (match-end 0) (match-beginning 0) 1)
5746 (error 1))))
5747 (next-level (save-excursion
5748 (condition-case nil
5749 (progn
5750 (or (looking-at outline-regexp)
5751 (outline-next-visible-heading 1))
5752 (if (looking-at re)
5753 (- (match-end 0) (match-beginning 0) 1)
5755 (error 1))))
5756 (new-level (or force-level (max previous-level next-level)))
5757 (shift (if (or (= old-level -1)
5758 (= new-level -1)
5759 (= old-level new-level))
5761 (- new-level old-level)))
5762 (delta (if (> shift 0) -1 1))
5763 (func (if (> shift 0) 'org-demote 'org-promote))
5764 (org-odd-levels-only nil)
5765 beg end newend)
5766 ;; Remove the forced level indicator
5767 (if force-level
5768 (delete-region (point-at-bol) (point)))
5769 ;; Paste
5770 (beginning-of-line 1)
5771 (unless for-yank (org-back-over-empty-lines))
5772 (setq beg (point))
5773 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5774 (insert-before-markers txt)
5775 (unless (string-match "\n\\'" txt) (insert "\n"))
5776 (setq newend (point))
5777 (org-reinstall-markers-in-region beg)
5778 (setq end (point))
5779 (goto-char beg)
5780 (skip-chars-forward " \t\n\r")
5781 (setq beg (point))
5782 (if (and (org-invisible-p) visp)
5783 (save-excursion (outline-show-heading)))
5784 ;; Shift if necessary
5785 (unless (= shift 0)
5786 (save-restriction
5787 (narrow-to-region beg end)
5788 (while (not (= shift 0))
5789 (org-map-region func (point-min) (point-max))
5790 (setq shift (+ delta shift)))
5791 (goto-char (point-min))
5792 (setq newend (point-max))))
5793 (when (or (interactive-p) for-yank)
5794 (message "Clipboard pasted as level %d subtree" new-level))
5795 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5796 kill-ring
5797 (eq org-subtree-clip (current-kill 0))
5798 org-subtree-clip-folded)
5799 ;; The tree was folded before it was killed/copied
5800 (hide-subtree))
5801 (and for-yank (goto-char newend))))
5803 (defun org-kill-is-subtree-p (&optional txt)
5804 "Check if the current kill is an outline subtree, or a set of trees.
5805 Returns nil if kill does not start with a headline, or if the first
5806 headline level is not the largest headline level in the tree.
5807 So this will actually accept several entries of equal levels as well,
5808 which is OK for `org-paste-subtree'.
5809 If optional TXT is given, check this string instead of the current kill."
5810 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5811 (start-level (and kill
5812 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5813 org-outline-regexp "\\)")
5814 kill)
5815 (- (match-end 2) (match-beginning 2) 1)))
5816 (re (concat "^" org-outline-regexp))
5817 (start (1+ (or (match-beginning 2) -1))))
5818 (if (not start-level)
5819 (progn
5820 nil) ;; does not even start with a heading
5821 (catch 'exit
5822 (while (setq start (string-match re kill (1+ start)))
5823 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5824 (throw 'exit nil)))
5825 t))))
5827 (defvar org-markers-to-move nil
5828 "Markers that should be moved with a cut-and-paste operation.
5829 Those markers are stored together with their positions relative to
5830 the start of the region.")
5832 (defun org-save-markers-in-region (beg end)
5833 "Check markers in region.
5834 If these markers are between BEG and END, record their position relative
5835 to BEG, so that after moving the block of text, we can put the markers back
5836 into place.
5837 This function gets called just before an entry or tree gets cut from the
5838 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5839 called immediately, to move the markers with the entries."
5840 (setq org-markers-to-move nil)
5841 (when (featurep 'org-clock)
5842 (org-clock-save-markers-for-cut-and-paste beg end))
5843 (when (featurep 'org-agenda)
5844 (org-agenda-save-markers-for-cut-and-paste beg end)))
5846 (defun org-check-and-save-marker (marker beg end)
5847 "Check if MARKER is between BEG and END.
5848 If yes, remember the marker and the distance to BEG."
5849 (when (and (marker-buffer marker)
5850 (equal (marker-buffer marker) (current-buffer)))
5851 (if (and (>= marker beg) (< marker end))
5852 (push (cons marker (- marker beg)) org-markers-to-move))))
5854 (defun org-reinstall-markers-in-region (beg)
5855 "Move all remembered markers to their position relative to BEG."
5856 (mapc (lambda (x)
5857 (move-marker (car x) (+ beg (cdr x))))
5858 org-markers-to-move)
5859 (setq org-markers-to-move nil))
5861 (defun org-narrow-to-subtree ()
5862 "Narrow buffer to the current subtree."
5863 (interactive)
5864 (save-excursion
5865 (save-match-data
5866 (narrow-to-region
5867 (progn (org-back-to-heading) (point))
5868 (progn (org-end-of-subtree t) (point))))))
5870 (defun org-clone-subtree-with-time-shift (n &optional shift)
5871 "Clone the task (subtree) at point N times.
5872 The clones will be inserted as siblings.
5874 In interactive use, the user will be prompted for the number of clones
5875 to be produced, and for a time SHIFT, which may be a repeater as used
5876 in time stamps, for example `+3d'.
5878 When a valid repeater is given and the entry contains any time stamps,
5879 the clones will become a sequence in time, with time stamps in the
5880 subtree shifted for each clone produced. If SHIFT is nil or the
5881 empty string, time stamps will be left alone.
5883 If the original subtree did contain time stamps with a repeater,
5884 the following will happen:
5885 - the repeater will be removed in each clone
5886 - an additional clone will be produced, with the current, unshifted
5887 date(s) in the entry.
5888 - the original entry will be placed *after* all the clones, with
5889 repeater intact.
5890 - the start days in the repeater in the original entry will be shifted
5891 to past the last clone.
5892 I this way you can spell out a number of instances of a repeating task,
5893 and still retain the repeater to cover future instances of the task."
5894 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
5895 (let (beg end template task
5896 shift-n shift-what doshift nmin nmax (n-no-remove -1))
5897 (if (not (and (integerp n) (> n 0)))
5898 (error "Invalid number of replications %s" n))
5899 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
5900 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
5901 shift)))
5902 (error "Invalid shift specification %s" shift))
5903 (when doshift
5904 (setq shift-n (string-to-number (match-string 1 shift))
5905 shift-what (cdr (assoc (match-string 2 shift)
5906 '(("d" . day) ("w" . week)
5907 ("m" . month) ("y" . year))))))
5908 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
5909 (setq nmin 1 nmax n)
5910 (org-back-to-heading t)
5911 (setq beg (point))
5912 (org-end-of-subtree t t)
5913 (setq end (point))
5914 (setq template (buffer-substring beg end))
5915 (when (and doshift
5916 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
5917 (delete-region beg end)
5918 (setq end beg)
5919 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
5920 (goto-char end)
5921 (loop for n from nmin to nmax do
5922 (if (not doshift)
5923 (setq task template)
5924 (with-temp-buffer
5925 (insert template)
5926 (org-mode)
5927 (goto-char (point-min))
5928 (while (re-search-forward org-ts-regexp nil t)
5929 (org-timestamp-change (* n shift-n) shift-what))
5930 (unless (= n n-no-remove)
5931 (goto-char (point-min))
5932 (while (re-search-forward org-ts-regexp nil t)
5933 (save-excursion
5934 (goto-char (match-beginning 0))
5935 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
5936 (delete-region (match-beginning 1) (match-end 1))))))
5937 (setq task (buffer-string))))
5938 (insert task))
5939 (goto-char beg)))
5941 ;;; Outline Sorting
5943 (defun org-sort (with-case)
5944 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5945 Optional argument WITH-CASE means sort case-sensitively.
5946 With a double prefix argument, also remove duplicate entries."
5947 (interactive "P")
5948 (if (org-at-table-p)
5949 (org-call-with-arg 'org-table-sort-lines with-case)
5950 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5952 (defun org-sort-remove-invisible (s)
5953 (remove-text-properties 0 (length s) org-rm-props s)
5954 (while (string-match org-bracket-link-regexp s)
5955 (setq s (replace-match (if (match-end 2)
5956 (match-string 3 s)
5957 (match-string 1 s)) t t s)))
5960 (defvar org-priority-regexp) ; defined later in the file
5962 (defun org-sort-entries-or-items
5963 (&optional with-case sorting-type getkey-func compare-func property)
5964 "Sort entries on a certain level of an outline tree.
5965 If there is an active region, the entries in the region are sorted.
5966 Else, if the cursor is before the first entry, sort the top-level items.
5967 Else, the children of the entry at point are sorted.
5969 Sorting can be alphabetically, numerically, and by date/time as given by
5970 the first time stamp in the entry. The command prompts for the sorting
5971 type unless it has been given to the function through the SORTING-TYPE
5972 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5973 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5974 called with point at the beginning of the record. It must return either
5975 a string or a number that should serve as the sorting key for that record.
5977 Comparing entries ignores case by default. However, with an optional argument
5978 WITH-CASE, the sorting considers case as well."
5979 (interactive "P")
5980 (let ((case-func (if with-case 'identity 'downcase))
5981 start beg end stars re re2
5982 txt what tmp plain-list-p)
5983 ;; Find beginning and end of region to sort
5984 (cond
5985 ((org-region-active-p)
5986 ;; we will sort the region
5987 (setq end (region-end)
5988 what "region")
5989 (goto-char (region-beginning))
5990 (if (not (org-on-heading-p)) (outline-next-heading))
5991 (setq start (point)))
5992 ((org-at-item-p)
5993 ;; we will sort this plain list
5994 (org-beginning-of-item-list) (setq start (point))
5995 (org-end-of-item-list) (setq end (point))
5996 (goto-char start)
5997 (setq plain-list-p t
5998 what "plain list"))
5999 ((or (org-on-heading-p)
6000 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6001 ;; we will sort the children of the current headline
6002 (org-back-to-heading)
6003 (setq start (point)
6004 end (progn (org-end-of-subtree t t)
6005 (org-back-over-empty-lines)
6006 (point))
6007 what "children")
6008 (goto-char start)
6009 (show-subtree)
6010 (outline-next-heading))
6012 ;; we will sort the top-level entries in this file
6013 (goto-char (point-min))
6014 (or (org-on-heading-p) (outline-next-heading))
6015 (setq start (point) end (point-max) what "top-level")
6016 (goto-char start)
6017 (show-all)))
6019 (setq beg (point))
6020 (if (>= beg end) (error "Nothing to sort"))
6022 (unless plain-list-p
6023 (looking-at "\\(\\*+\\)")
6024 (setq stars (match-string 1)
6025 re (concat "^" (regexp-quote stars) " +")
6026 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6027 txt (buffer-substring beg end))
6028 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6029 (if (and (not (equal stars "*")) (string-match re2 txt))
6030 (error "Region to sort contains a level above the first entry")))
6032 (unless sorting-type
6033 (message
6034 (if plain-list-p
6035 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6036 "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:")
6037 what)
6038 (setq sorting-type (read-char-exclusive))
6040 (and (= (downcase sorting-type) ?f)
6041 (setq getkey-func
6042 (org-ido-completing-read "Sort using function: "
6043 obarray 'fboundp t nil nil))
6044 (setq getkey-func (intern getkey-func)))
6046 (and (= (downcase sorting-type) ?r)
6047 (setq property
6048 (org-ido-completing-read "Property: "
6049 (mapcar 'list (org-buffer-property-keys t))
6050 nil t))))
6052 (message "Sorting entries...")
6054 (save-restriction
6055 (narrow-to-region start end)
6057 (let ((dcst (downcase sorting-type))
6058 (now (current-time)))
6059 (sort-subr
6060 (/= dcst sorting-type)
6061 ;; This function moves to the beginning character of the "record" to
6062 ;; be sorted.
6063 (if plain-list-p
6064 (lambda nil
6065 (if (org-at-item-p) t (goto-char (point-max))))
6066 (lambda nil
6067 (if (re-search-forward re nil t)
6068 (goto-char (match-beginning 0))
6069 (goto-char (point-max)))))
6070 ;; This function moves to the last character of the "record" being
6071 ;; sorted.
6072 (if plain-list-p
6073 'org-end-of-item
6074 (lambda nil
6075 (save-match-data
6076 (condition-case nil
6077 (outline-forward-same-level 1)
6078 (error
6079 (goto-char (point-max)))))))
6081 ;; This function returns the value that gets sorted against.
6082 (if plain-list-p
6083 (lambda nil
6084 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6085 (cond
6086 ((= dcst ?n)
6087 (string-to-number (buffer-substring (match-end 0)
6088 (point-at-eol))))
6089 ((= dcst ?a)
6090 (buffer-substring (match-end 0) (point-at-eol)))
6091 ((= dcst ?t)
6092 (if (re-search-forward org-ts-regexp
6093 (point-at-eol) t)
6094 (org-time-string-to-time (match-string 0))
6095 now))
6096 ((= dcst ?f)
6097 (if getkey-func
6098 (progn
6099 (setq tmp (funcall getkey-func))
6100 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6101 tmp)
6102 (error "Invalid key function `%s'" getkey-func)))
6103 (t (error "Invalid sorting type `%c'" sorting-type)))))
6104 (lambda nil
6105 (cond
6106 ((= dcst ?n)
6107 (if (looking-at org-complex-heading-regexp)
6108 (string-to-number (match-string 4))
6109 nil))
6110 ((= dcst ?a)
6111 (if (looking-at org-complex-heading-regexp)
6112 (funcall case-func (match-string 4))
6113 nil))
6114 ((= dcst ?t)
6115 (if (re-search-forward org-ts-regexp
6116 (save-excursion
6117 (forward-line 2)
6118 (point)) t)
6119 (org-time-string-to-time (match-string 0))
6120 now))
6121 ((= dcst ?p)
6122 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6123 (string-to-char (match-string 2))
6124 org-default-priority))
6125 ((= dcst ?r)
6126 (or (org-entry-get nil property) ""))
6127 ((= dcst ?o)
6128 (if (looking-at org-complex-heading-regexp)
6129 (- 9999 (length (member (match-string 2)
6130 org-todo-keywords-1)))))
6131 ((= dcst ?f)
6132 (if getkey-func
6133 (progn
6134 (setq tmp (funcall getkey-func))
6135 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6136 tmp)
6137 (error "Invalid key function `%s'" getkey-func)))
6138 (t (error "Invalid sorting type `%c'" sorting-type)))))
6140 (cond
6141 ((= dcst ?a) 'string<)
6142 ((= dcst ?t) 'time-less-p)
6143 ((= dcst ?f) compare-func)
6144 (t nil)))))
6145 (message "Sorting entries...done")))
6147 (defun org-do-sort (table what &optional with-case sorting-type)
6148 "Sort TABLE of WHAT according to SORTING-TYPE.
6149 The user will be prompted for the SORTING-TYPE if the call to this
6150 function does not specify it. WHAT is only for the prompt, to indicate
6151 what is being sorted. The sorting key will be extracted from
6152 the car of the elements of the table.
6153 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6154 (unless sorting-type
6155 (message
6156 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6157 what)
6158 (setq sorting-type (read-char-exclusive)))
6159 (let ((dcst (downcase sorting-type))
6160 extractfun comparefun)
6161 ;; Define the appropriate functions
6162 (cond
6163 ((= dcst ?n)
6164 (setq extractfun 'string-to-number
6165 comparefun (if (= dcst sorting-type) '< '>)))
6166 ((= dcst ?a)
6167 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6168 (lambda(x) (downcase (org-sort-remove-invisible x))))
6169 comparefun (if (= dcst sorting-type)
6170 'string<
6171 (lambda (a b) (and (not (string< a b))
6172 (not (string= a b)))))))
6173 ((= dcst ?t)
6174 (setq extractfun
6175 (lambda (x)
6176 (if (or (string-match org-ts-regexp x)
6177 (string-match org-ts-regexp-both x))
6178 (time-to-seconds
6179 (org-time-string-to-time (match-string 0 x)))
6181 comparefun (if (= dcst sorting-type) '< '>)))
6182 (t (error "Invalid sorting type `%c'" sorting-type)))
6184 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6185 table)
6186 (lambda (a b) (funcall comparefun (car a) (car b))))))
6188 ;;; Editing source examples
6190 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6191 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6192 (defvar org-edit-src-force-single-line nil)
6193 (defvar org-edit-src-from-org-mode nil)
6194 (defvar org-edit-src-picture nil)
6196 (define-minor-mode org-exit-edit-mode
6197 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6199 (defun org-edit-src-code ()
6200 "Edit the source code example at point.
6201 An indirect buffer is created, and that buffer is then narrowed to the
6202 example at point and switched to the correct language mode. When done,
6203 exit by killing the buffer with \\[org-edit-src-exit]."
6204 (interactive)
6205 (let ((line (org-current-line))
6206 (case-fold-search t)
6207 (msg (substitute-command-keys
6208 "Edit, then exit with C-c ' (C-c and single quote)"))
6209 (info (org-edit-src-find-region-and-lang))
6210 (org-mode-p (eq major-mode 'org-mode))
6211 beg end lang lang-f single lfmt)
6212 (if (not info)
6214 (setq beg (nth 0 info)
6215 end (nth 1 info)
6216 lang (nth 2 info)
6217 single (nth 3 info)
6218 lfmt (nth 4 info)
6219 lang-f (intern (concat lang "-mode")))
6220 (unless (functionp lang-f)
6221 (error "No such language mode: %s" lang-f))
6222 (goto-line line)
6223 (if (get-buffer "*Org Edit Src Example*")
6224 (kill-buffer "*Org Edit Src Example*"))
6225 (switch-to-buffer (make-indirect-buffer (current-buffer)
6226 "*Org Edit Src Example*"))
6227 (narrow-to-region beg end)
6228 (remove-text-properties beg end '(display nil invisible nil
6229 intangible nil))
6230 (let ((org-inhibit-startup t))
6231 (funcall lang-f))
6232 (set (make-local-variable 'org-edit-src-force-single-line) single)
6233 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6234 (when lfmt
6235 (set (make-local-variable 'org-coderef-label-format) lfmt))
6236 (when org-mode-p
6237 (goto-char (point-min))
6238 (while (re-search-forward "^," nil t)
6239 (replace-match "")))
6240 (goto-line line)
6241 (org-exit-edit-mode)
6242 (org-set-local 'header-line-format msg)
6243 (message "%s" msg)
6244 t)))
6246 (defun org-edit-fixed-width-region ()
6247 "Edit the fixed-width ascii drawing at point.
6248 This must be a region where each line starts with a colon followed by
6249 a space character.
6250 An indirect buffer is created, and that buffer is then narrowed to the
6251 example at point and switched to artist-mode. When done,
6252 exit by killing the buffer with \\[org-edit-src-exit]."
6253 (interactive)
6254 (let ((line (org-current-line))
6255 (case-fold-search t)
6256 (msg (substitute-command-keys
6257 "Edit, then exit with C-c ' (C-c and single quote)"))
6258 (org-mode-p (eq major-mode 'org-mode))
6259 beg end)
6260 (beginning-of-line 1)
6261 (if (looking-at "[ \t]*[^:\n \t]")
6263 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6264 (setq beg (point) end beg)
6265 (save-excursion
6266 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6267 (setq beg (point-at-bol 2))
6268 (setq beg (point))))
6269 (save-excursion
6270 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6271 (setq end (1- (match-beginning 0)))
6272 (setq end (point))))
6273 (goto-line line))
6274 (if (get-buffer "*Org Edit Picture*")
6275 (kill-buffer "*Org Edit Picture*"))
6276 (switch-to-buffer (make-indirect-buffer (current-buffer)
6277 "*Org Edit Picture*"))
6278 (narrow-to-region beg end)
6279 (remove-text-properties beg end '(display nil invisible nil
6280 intangible nil))
6281 (when (fboundp 'font-lock-unfontify-region)
6282 (font-lock-unfontify-region (point-min) (point-max)))
6283 (cond
6284 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6285 (fundamental-mode)
6286 (artist-mode 1))
6287 (t (funcall org-edit-fixed-width-region-mode)))
6288 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6289 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6290 (set (make-local-variable 'org-edit-src-picture) t)
6291 (goto-char (point-min))
6292 (while (re-search-forward "^[ \t]*: ?" nil t)
6293 (replace-match ""))
6294 (goto-line line)
6295 (org-exit-edit-mode)
6296 (org-set-local 'header-line-format msg)
6297 (message "%s" msg)
6298 t)))
6301 (defun org-edit-src-find-region-and-lang ()
6302 "Find the region and language for a local edit.
6303 Return a list with beginning and end of the region, a string representing
6304 the language, a switch telling of the content should be in a single line."
6305 (let ((re-list
6306 (append
6307 org-edit-src-region-extra
6309 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6310 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6311 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6312 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6313 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6314 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6315 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6316 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6317 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6318 ("^#\\+html:" "\n" "html" single-line)
6319 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6320 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6321 ("^#\\+latex:" "\n" "latex" single-line)
6322 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6323 ("^#\\+ascii:" "\n" "ascii" single-line)
6325 (pos (point))
6326 re1 re2 single beg end lang lfmt match-re1)
6327 (catch 'exit
6328 (while (setq entry (pop re-list))
6329 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6330 single (nth 3 entry))
6331 (save-excursion
6332 (if (or (looking-at re1)
6333 (re-search-backward re1 nil t))
6334 (progn
6335 (setq match-re1 (match-string 0))
6336 (setq beg (match-end 0)
6337 lang (org-edit-src-get-lang lang)
6338 lfmt (org-edit-src-get-label-format match-re1))
6339 (if (and (re-search-forward re2 nil t)
6340 (>= (match-end 0) pos))
6341 (throw 'exit (list beg (match-beginning 0)
6342 lang single lfmt))))
6343 (if (or (looking-at re2)
6344 (re-search-forward re2 nil t))
6345 (progn
6346 (setq end (match-beginning 0))
6347 (if (and (re-search-backward re1 nil t)
6348 (<= (match-beginning 0) pos))
6349 (progn
6350 (setq lfmt (org-edit-src-get-label-format
6351 (match-string 0)))
6352 (throw 'exit
6353 (list (match-end 0) end
6354 (org-edit-src-get-lang lang)
6355 single lfmt))))))))))))
6357 (defun org-edit-src-get-lang (lang)
6358 "Extract the src language."
6359 (let ((m (match-string 0)))
6360 (cond
6361 ((stringp lang) lang)
6362 ((integerp lang) (match-string lang))
6363 ((and (eq lang 'lang)
6364 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6365 (match-string 1 m))
6366 ((and (eq lang 'style)
6367 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6368 (match-string 1 m))
6369 (t "fundamental"))))
6371 (defun org-edit-src-get-label-format (s)
6372 "Extract the label format."
6373 (save-match-data
6374 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6375 (match-string 1 s))))
6377 (defun org-edit-src-exit ()
6378 "Exit special edit and protect problematic lines."
6379 (interactive)
6380 (unless (buffer-base-buffer (current-buffer))
6381 (error "This is not an indirect buffer, something is wrong..."))
6382 (unless (> (point-min) 1)
6383 (error "This buffer is not narrowed, something is wrong..."))
6384 (goto-char (point-min))
6385 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6386 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6387 (when (org-bound-and-true-p org-edit-src-force-single-line)
6388 (goto-char (point-min))
6389 (while (re-search-forward "\n" nil t)
6390 (replace-match " "))
6391 (goto-char (point-min))
6392 (if (looking-at "\\s-*") (replace-match " "))
6393 (if (re-search-forward "\\s-+\\'" nil t)
6394 (replace-match "")))
6395 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6396 (goto-char (point-min))
6397 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6398 (replace-match ",\\1"))
6399 (when font-lock-mode
6400 (font-lock-unfontify-region (point-min) (point-max)))
6401 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6402 (when (org-bound-and-true-p org-edit-src-picture)
6403 (untabify (point-min) (point-max))
6404 (goto-char (point-min))
6405 (while (re-search-forward "^" nil t)
6406 (replace-match ": "))
6407 (when font-lock-mode
6408 (font-lock-unfontify-region (point-min) (point-max)))
6409 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6410 (kill-buffer (current-buffer))
6411 (and (org-mode-p) (org-restart-font-lock)))
6414 ;;; The orgstruct minor mode
6416 ;; Define a minor mode which can be used in other modes in order to
6417 ;; integrate the org-mode structure editing commands.
6419 ;; This is really a hack, because the org-mode structure commands use
6420 ;; keys which normally belong to the major mode. Here is how it
6421 ;; works: The minor mode defines all the keys necessary to operate the
6422 ;; structure commands, but wraps the commands into a function which
6423 ;; tests if the cursor is currently at a headline or a plain list
6424 ;; item. If that is the case, the structure command is used,
6425 ;; temporarily setting many Org-mode variables like regular
6426 ;; expressions for filling etc. However, when any of those keys is
6427 ;; used at a different location, function uses `key-binding' to look
6428 ;; up if the key has an associated command in another currently active
6429 ;; keymap (minor modes, major mode, global), and executes that
6430 ;; command. There might be problems if any of the keys is otherwise
6431 ;; used as a prefix key.
6433 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6434 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6435 ;; addresses this by checking explicitly for both bindings.
6437 (defvar orgstruct-mode-map (make-sparse-keymap)
6438 "Keymap for the minor `orgstruct-mode'.")
6440 (defvar org-local-vars nil
6441 "List of local variables, for use by `orgstruct-mode'")
6443 ;;;###autoload
6444 (define-minor-mode orgstruct-mode
6445 "Toggle the minor more `orgstruct-mode'.
6446 This mode is for using Org-mode structure commands in other modes.
6447 The following key behave as if Org-mode was active, if the cursor
6448 is on a headline, or on a plain list item (both in the definition
6449 of Org-mode).
6451 M-up Move entry/item up
6452 M-down Move entry/item down
6453 M-left Promote
6454 M-right Demote
6455 M-S-up Move entry/item up
6456 M-S-down Move entry/item down
6457 M-S-left Promote subtree
6458 M-S-right Demote subtree
6459 M-q Fill paragraph and items like in Org-mode
6460 C-c ^ Sort entries
6461 C-c - Cycle list bullet
6462 TAB Cycle item visibility
6463 M-RET Insert new heading/item
6464 S-M-RET Insert new TODO heading / Checkbox item
6465 C-c C-c Set tags / toggle checkbox"
6466 nil " OrgStruct" nil
6467 (org-load-modules-maybe)
6468 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6470 ;;;###autoload
6471 (defun turn-on-orgstruct ()
6472 "Unconditionally turn on `orgstruct-mode'."
6473 (orgstruct-mode 1))
6475 (defun orgstruct++-mode (&optional arg)
6476 "Toggle `orgstruct-mode', the enhanced version of it.
6477 In addition to setting orgstruct-mode, this also exports all indentation and
6478 autofilling variables from org-mode into the buffer. It will also
6479 recognize item context in multiline items.
6480 Note that turning off orgstruct-mode will *not* remove the
6481 indentation/paragraph settings. This can only be done by refreshing the
6482 major mode, for example with \[normal-mode]."
6483 (interactive "P")
6484 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6485 (if (< arg 1)
6486 (orgstruct-mode -1)
6487 (orgstruct-mode 1)
6488 (let (var val)
6489 (mapc
6490 (lambda (x)
6491 (when (string-match
6492 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6493 (symbol-name (car x)))
6494 (setq var (car x) val (nth 1 x))
6495 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6496 org-local-vars)
6497 (org-set-local 'orgstruct-is-++ t))))
6499 (defvar orgstruct-is-++ nil
6500 "Is orgstruct-mode in ++ version in the current-buffer?")
6501 (make-variable-buffer-local 'orgstruct-is-++)
6503 ;;;###autoload
6504 (defun turn-on-orgstruct++ ()
6505 "Unconditionally turn on `orgstruct++-mode'."
6506 (orgstruct++-mode 1))
6508 (defun orgstruct-error ()
6509 "Error when there is no default binding for a structure key."
6510 (interactive)
6511 (error "This key has no function outside structure elements"))
6513 (defun orgstruct-setup ()
6514 "Setup orgstruct keymaps."
6515 (let ((nfunc 0)
6516 (bindings
6517 (list
6518 '([(meta up)] org-metaup)
6519 '([(meta down)] org-metadown)
6520 '([(meta left)] org-metaleft)
6521 '([(meta right)] org-metaright)
6522 '([(meta shift up)] org-shiftmetaup)
6523 '([(meta shift down)] org-shiftmetadown)
6524 '([(meta shift left)] org-shiftmetaleft)
6525 '([(meta shift right)] org-shiftmetaright)
6526 '([(shift up)] org-shiftup)
6527 '([(shift down)] org-shiftdown)
6528 '([(shift left)] org-shiftleft)
6529 '([(shift right)] org-shiftright)
6530 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6531 '("\M-q" fill-paragraph)
6532 '("\C-c^" org-sort)
6533 '("\C-c-" org-cycle-list-bullet)))
6534 elt key fun cmd)
6535 (while (setq elt (pop bindings))
6536 (setq nfunc (1+ nfunc))
6537 (setq key (org-key (car elt))
6538 fun (nth 1 elt)
6539 cmd (orgstruct-make-binding fun nfunc key))
6540 (org-defkey orgstruct-mode-map key cmd))
6542 ;; Special treatment needed for TAB and RET
6543 (org-defkey orgstruct-mode-map [(tab)]
6544 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6545 (org-defkey orgstruct-mode-map "\C-i"
6546 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6548 (org-defkey orgstruct-mode-map "\M-\C-m"
6549 (orgstruct-make-binding 'org-insert-heading 105
6550 "\M-\C-m" [(meta return)]))
6551 (org-defkey orgstruct-mode-map [(meta return)]
6552 (orgstruct-make-binding 'org-insert-heading 106
6553 [(meta return)] "\M-\C-m"))
6555 (org-defkey orgstruct-mode-map [(shift meta return)]
6556 (orgstruct-make-binding 'org-insert-todo-heading 107
6557 [(meta return)] "\M-\C-m"))
6559 (unless org-local-vars
6560 (setq org-local-vars (org-get-local-variables)))
6564 (defun orgstruct-make-binding (fun n &rest keys)
6565 "Create a function for binding in the structure minor mode.
6566 FUN is the command to call inside a table. N is used to create a unique
6567 command name. KEYS are keys that should be checked in for a command
6568 to execute outside of tables."
6569 (eval
6570 (list 'defun
6571 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6572 '(arg)
6573 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6574 "Outside of structure, run the binding of `"
6575 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6576 "'.")
6577 '(interactive "p")
6578 (list 'if
6579 `(org-context-p 'headline 'item
6580 (and orgstruct-is-++
6581 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6582 'item-body))
6583 (list 'org-run-like-in-org-mode (list 'quote fun))
6584 (list 'let '(orgstruct-mode)
6585 (list 'call-interactively
6586 (append '(or)
6587 (mapcar (lambda (k)
6588 (list 'key-binding k))
6589 keys)
6590 '('orgstruct-error))))))))
6592 (defun org-context-p (&rest contexts)
6593 "Check if local context is any of CONTEXTS.
6594 Possible values in the list of contexts are `table', `headline', and `item'."
6595 (let ((pos (point)))
6596 (goto-char (point-at-bol))
6597 (prog1 (or (and (memq 'table contexts)
6598 (looking-at "[ \t]*|"))
6599 (and (memq 'headline contexts)
6600 ;;????????? (looking-at "\\*+"))
6601 (looking-at outline-regexp))
6602 (and (memq 'item contexts)
6603 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6604 (and (memq 'item-body contexts)
6605 (org-in-item-p)))
6606 (goto-char pos))))
6608 (defun org-get-local-variables ()
6609 "Return a list of all local variables in an org-mode buffer."
6610 (let (varlist)
6611 (with-current-buffer (get-buffer-create "*Org tmp*")
6612 (erase-buffer)
6613 (org-mode)
6614 (setq varlist (buffer-local-variables)))
6615 (kill-buffer "*Org tmp*")
6616 (delq nil
6617 (mapcar
6618 (lambda (x)
6619 (setq x
6620 (if (symbolp x)
6621 (list x)
6622 (list (car x) (list 'quote (cdr x)))))
6623 (if (string-match
6624 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6625 (symbol-name (car x)))
6626 x nil))
6627 varlist))))
6629 ;;;###autoload
6630 (defun org-run-like-in-org-mode (cmd)
6631 "Run a command, pretending that the current buffer is in Org-mode.
6632 This will temporarily bind local variables that are typically bound in
6633 Org-mode to the values they have in Org-mode, and then interactively
6634 call CMD."
6635 (org-load-modules-maybe)
6636 (unless org-local-vars
6637 (setq org-local-vars (org-get-local-variables)))
6638 (eval (list 'let org-local-vars
6639 (list 'call-interactively (list 'quote cmd)))))
6641 ;;;; Archiving
6643 (defun org-get-category (&optional pos)
6644 "Get the category applying to position POS."
6645 (get-text-property (or pos (point)) 'org-category))
6647 (defun org-refresh-category-properties ()
6648 "Refresh category text properties in the buffer."
6649 (let ((def-cat (cond
6650 ((null org-category)
6651 (if buffer-file-name
6652 (file-name-sans-extension
6653 (file-name-nondirectory buffer-file-name))
6654 "???"))
6655 ((symbolp org-category) (symbol-name org-category))
6656 (t org-category)))
6657 beg end cat pos optionp)
6658 (org-unmodified
6659 (save-excursion
6660 (save-restriction
6661 (widen)
6662 (goto-char (point-min))
6663 (put-text-property (point) (point-max) 'org-category def-cat)
6664 (while (re-search-forward
6665 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6666 (setq pos (match-end 0)
6667 optionp (equal (char-after (match-beginning 0)) ?#)
6668 cat (org-trim (match-string 2)))
6669 (if optionp
6670 (setq beg (point-at-bol) end (point-max))
6671 (org-back-to-heading t)
6672 (setq beg (point) end (org-end-of-subtree t t)))
6673 (put-text-property beg end 'org-category cat)
6674 (goto-char pos)))))))
6677 ;;;; Link Stuff
6679 ;;; Link abbreviations
6681 (defun org-link-expand-abbrev (link)
6682 "Apply replacements as defined in `org-link-abbrev-alist."
6683 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6684 (let* ((key (match-string 1 link))
6685 (as (or (assoc key org-link-abbrev-alist-local)
6686 (assoc key org-link-abbrev-alist)))
6687 (tag (and (match-end 2) (match-string 3 link)))
6688 rpl)
6689 (if (not as)
6690 link
6691 (setq rpl (cdr as))
6692 (cond
6693 ((symbolp rpl) (funcall rpl tag))
6694 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6695 ((string-match "%h" rpl)
6696 (replace-match (url-hexify-string (or tag "")) t t rpl))
6697 (t (concat rpl tag)))))
6698 link))
6700 ;;; Storing and inserting links
6702 (defvar org-insert-link-history nil
6703 "Minibuffer history for links inserted with `org-insert-link'.")
6705 (defvar org-stored-links nil
6706 "Contains the links stored with `org-store-link'.")
6708 (defvar org-store-link-plist nil
6709 "Plist with info about the most recently link created with `org-store-link'.")
6711 (defvar org-link-protocols nil
6712 "Link protocols added to Org-mode using `org-add-link-type'.")
6714 (defvar org-store-link-functions nil
6715 "List of functions that are called to create and store a link.
6716 Each function will be called in turn until one returns a non-nil
6717 value. Each function should check if it is responsible for creating
6718 this link (for example by looking at the major mode).
6719 If not, it must exit and return nil.
6720 If yes, it should return a non-nil value after a calling
6721 `org-store-link-props' with a list of properties and values.
6722 Special properties are:
6724 :type The link prefix. like \"http\". This must be given.
6725 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6726 This is obligatory as well.
6727 :description Optional default description for the second pair
6728 of brackets in an Org-mode link. The user can still change
6729 this when inserting this link into an Org-mode buffer.
6731 In addition to these, any additional properties can be specified
6732 and then used in remember templates.")
6734 (defun org-add-link-type (type &optional follow export)
6735 "Add TYPE to the list of `org-link-types'.
6736 Re-compute all regular expressions depending on `org-link-types'
6738 FOLLOW and EXPORT are two functions.
6740 FOLLOW should take the link path as the single argument and do whatever
6741 is necessary to follow the link, for example find a file or display
6742 a mail message.
6744 EXPORT should format the link path for export to one of the export formats.
6745 It should be a function accepting three arguments:
6747 path the path of the link, the text after the prefix (like \"http:\")
6748 desc the description of the link, if any, nil if there was no description
6749 format the export format, a symbol like `html' or `latex'.
6751 The function may use the FORMAT information to return different values
6752 depending on the format. The return value will be put literally into
6753 the exported file.
6754 Org-mode has a built-in default for exporting links. If you are happy with
6755 this default, there is no need to define an export function for the link
6756 type. For a simple example of an export function, see `org-bbdb.el'."
6757 (add-to-list 'org-link-types type t)
6758 (org-make-link-regexps)
6759 (if (assoc type org-link-protocols)
6760 (setcdr (assoc type org-link-protocols) (list follow export))
6761 (push (list type follow export) org-link-protocols)))
6763 ;;;###autoload
6764 (defun org-store-link (arg)
6765 "\\<org-mode-map>Store an org-link to the current location.
6766 This link is added to `org-stored-links' and can later be inserted
6767 into an org-buffer with \\[org-insert-link].
6769 For some link types, a prefix arg is interpreted:
6770 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6771 For file links, arg negates `org-context-in-file-links'."
6772 (interactive "P")
6773 (org-load-modules-maybe)
6774 (setq org-store-link-plist nil) ; reset
6775 (let (link cpltxt desc description search txt)
6776 (cond
6778 ((run-hook-with-args-until-success 'org-store-link-functions)
6779 (setq link (plist-get org-store-link-plist :link)
6780 desc (or (plist-get org-store-link-plist :description) link)))
6782 ((equal (buffer-name) "*Org Edit Src Example*")
6783 (let (label gc)
6784 (while (or (not label)
6785 (save-excursion
6786 (save-restriction
6787 (widen)
6788 (goto-char (point-min))
6789 (re-search-forward
6790 (regexp-quote (format org-coderef-label-format label))
6791 nil t))))
6792 (when label (message "Label exists already") (sit-for 2))
6793 (setq label (read-string "Code line label: " label)))
6794 (end-of-line 1)
6795 (setq link (format org-coderef-label-format label))
6796 (setq gc (- 79 (length link)))
6797 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6798 (insert link)
6799 (setq link (concat "(" label ")") desc nil)))
6801 ((eq major-mode 'calendar-mode)
6802 (let ((cd (calendar-cursor-to-date)))
6803 (setq link
6804 (format-time-string
6805 (car org-time-stamp-formats)
6806 (apply 'encode-time
6807 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6808 nil nil nil))))
6809 (org-store-link-props :type "calendar" :date cd)))
6811 ((eq major-mode 'w3-mode)
6812 (setq cpltxt (if (and (buffer-name)
6813 (not (string-match "Untitled" (buffer-name))))
6814 (buffer-name)
6815 (url-view-url t))
6816 link (org-make-link (url-view-url t)))
6817 (org-store-link-props :type "w3" :url (url-view-url t)))
6819 ((eq major-mode 'w3m-mode)
6820 (setq cpltxt (or w3m-current-title w3m-current-url)
6821 link (org-make-link w3m-current-url))
6822 (org-store-link-props :type "w3m" :url (url-view-url t)))
6824 ((setq search (run-hook-with-args-until-success
6825 'org-create-file-search-functions))
6826 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6827 "::" search))
6828 (setq cpltxt (or description link)))
6830 ((eq major-mode 'image-mode)
6831 (setq cpltxt (concat "file:"
6832 (abbreviate-file-name buffer-file-name))
6833 link (org-make-link cpltxt))
6834 (org-store-link-props :type "image" :file buffer-file-name))
6836 ((eq major-mode 'dired-mode)
6837 ;; link to the file in the current line
6838 (setq cpltxt (concat "file:"
6839 (abbreviate-file-name
6840 (expand-file-name
6841 (dired-get-filename nil t))))
6842 link (org-make-link cpltxt)))
6844 ((and buffer-file-name (org-mode-p))
6845 (cond
6846 ((org-in-regexp "<<\\(.*?\\)>>")
6847 (setq cpltxt
6848 (concat "file:"
6849 (abbreviate-file-name buffer-file-name)
6850 "::" (match-string 1))
6851 link (org-make-link cpltxt)))
6852 ((and (featurep 'org-id)
6853 (or (eq org-link-to-org-use-id t)
6854 (and (eq org-link-to-org-use-id 'create-if-interactive)
6855 (interactive-p))
6856 (and org-link-to-org-use-id
6857 (condition-case nil
6858 (org-entry-get nil "ID")
6859 (error nil)))))
6860 ;; We can make a link using the ID.
6861 (setq link (condition-case nil
6862 (prog1 (org-id-store-link)
6863 (setq desc (plist-get org-store-link-plist
6864 :description)))
6865 (error
6866 ;; probably before first headline, link to file only
6867 (concat "file:"
6868 (abbreviate-file-name buffer-file-name))))))
6870 ;; Just link to current headline
6871 (setq cpltxt (concat "file:"
6872 (abbreviate-file-name buffer-file-name)))
6873 ;; Add a context search string
6874 (when (org-xor org-context-in-file-links arg)
6875 (setq txt (cond
6876 ((org-on-heading-p) nil)
6877 ((org-region-active-p)
6878 (buffer-substring (region-beginning) (region-end)))
6879 (t nil)))
6880 (when (or (null txt) (string-match "\\S-" txt))
6881 (setq cpltxt
6882 (concat cpltxt "::"
6883 (condition-case nil
6884 (org-make-org-heading-search-string txt)
6885 (error "")))
6886 desc "NONE")))
6887 (if (string-match "::\\'" cpltxt)
6888 (setq cpltxt (substring cpltxt 0 -2)))
6889 (setq link (org-make-link cpltxt)))))
6891 ((buffer-file-name (buffer-base-buffer))
6892 ;; Just link to this file here.
6893 (setq cpltxt (concat "file:"
6894 (abbreviate-file-name
6895 (buffer-file-name (buffer-base-buffer)))))
6896 ;; Add a context string
6897 (when (org-xor org-context-in-file-links arg)
6898 (setq txt (if (org-region-active-p)
6899 (buffer-substring (region-beginning) (region-end))
6900 (buffer-substring (point-at-bol) (point-at-eol))))
6901 ;; Only use search option if there is some text.
6902 (when (string-match "\\S-" txt)
6903 (setq cpltxt
6904 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6905 desc "NONE")))
6906 (setq link (org-make-link cpltxt)))
6908 ((interactive-p)
6909 (error "Cannot link to a buffer which is not visiting a file"))
6911 (t (setq link nil)))
6913 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6914 (setq link (or link cpltxt)
6915 desc (or desc cpltxt))
6916 (if (equal desc "NONE") (setq desc nil))
6918 (if (and (interactive-p) link)
6919 (progn
6920 (setq org-stored-links
6921 (cons (list link desc) org-stored-links))
6922 (message "Stored: %s" (or desc link)))
6923 (and link (org-make-link-string link desc)))))
6925 (defun org-store-link-props (&rest plist)
6926 "Store link properties, extract names and addresses."
6927 (let (x adr)
6928 (when (setq x (plist-get plist :from))
6929 (setq adr (mail-extract-address-components x))
6930 (setq plist (plist-put plist :fromname (car adr)))
6931 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6932 (when (setq x (plist-get plist :to))
6933 (setq adr (mail-extract-address-components x))
6934 (setq plist (plist-put plist :toname (car adr)))
6935 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6936 (let ((from (plist-get plist :from))
6937 (to (plist-get plist :to)))
6938 (when (and from to org-from-is-user-regexp)
6939 (setq plist
6940 (plist-put plist :fromto
6941 (if (string-match org-from-is-user-regexp from)
6942 (concat "to %t")
6943 (concat "from %f"))))))
6944 (setq org-store-link-plist plist))
6946 (defun org-add-link-props (&rest plist)
6947 "Add these properties to the link property list."
6948 (let (key value)
6949 (while plist
6950 (setq key (pop plist) value (pop plist))
6951 (setq org-store-link-plist
6952 (plist-put org-store-link-plist key value)))))
6954 (defun org-email-link-description (&optional fmt)
6955 "Return the description part of an email link.
6956 This takes information from `org-store-link-plist' and formats it
6957 according to FMT (default from `org-email-link-description-format')."
6958 (setq fmt (or fmt org-email-link-description-format))
6959 (let* ((p org-store-link-plist)
6960 (to (plist-get p :toaddress))
6961 (from (plist-get p :fromaddress))
6962 (table
6963 (list
6964 (cons "%c" (plist-get p :fromto))
6965 (cons "%F" (plist-get p :from))
6966 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6967 (cons "%T" (plist-get p :to))
6968 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6969 (cons "%s" (plist-get p :subject))
6970 (cons "%m" (plist-get p :message-id)))))
6971 (when (string-match "%c" fmt)
6972 ;; Check if the user wrote this message
6973 (if (and org-from-is-user-regexp from to
6974 (save-match-data (string-match org-from-is-user-regexp from)))
6975 (setq fmt (replace-match "to %t" t t fmt))
6976 (setq fmt (replace-match "from %f" t t fmt))))
6977 (org-replace-escapes fmt table)))
6979 (defun org-make-org-heading-search-string (&optional string heading)
6980 "Make search string for STRING or current headline."
6981 (interactive)
6982 (let ((s (or string (org-get-heading))))
6983 (unless (and string (not heading))
6984 ;; We are using a headline, clean up garbage in there.
6985 (if (string-match org-todo-regexp s)
6986 (setq s (replace-match "" t t s)))
6987 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6988 (setq s (replace-match "" t t s)))
6989 (setq s (org-trim s))
6990 (if (string-match (concat "^\\(" org-quote-string "\\|"
6991 org-comment-string "\\)") s)
6992 (setq s (replace-match "" t t s)))
6993 (while (string-match org-ts-regexp s)
6994 (setq s (replace-match "" t t s))))
6995 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6996 (setq s (replace-match " " t t s)))
6997 (or string (setq s (concat "*" s))) ; Add * for headlines
6998 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7000 (defun org-make-link (&rest strings)
7001 "Concatenate STRINGS."
7002 (apply 'concat strings))
7004 (defun org-make-link-string (link &optional description)
7005 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7006 (unless (string-match "\\S-" link)
7007 (error "Empty link"))
7008 (when (stringp description)
7009 ;; Remove brackets from the description, they are fatal.
7010 (while (string-match "\\[" description)
7011 (setq description (replace-match "{" t t description)))
7012 (while (string-match "\\]" description)
7013 (setq description (replace-match "}" t t description))))
7014 (when (equal (org-link-escape link) description)
7015 ;; No description needed, it is identical
7016 (setq description nil))
7017 (when (and (not description)
7018 (not (equal link (org-link-escape link))))
7019 (setq description (org-extract-attributes link)))
7020 (concat "[[" (org-link-escape link) "]"
7021 (if description (concat "[" description "]") "")
7022 "]"))
7024 (defconst org-link-escape-chars
7025 '((?\ . "%20")
7026 (?\[ . "%5B")
7027 (?\] . "%5D")
7028 (?\340 . "%E0") ; `a
7029 (?\342 . "%E2") ; ^a
7030 (?\347 . "%E7") ; ,c
7031 (?\350 . "%E8") ; `e
7032 (?\351 . "%E9") ; 'e
7033 (?\352 . "%EA") ; ^e
7034 (?\356 . "%EE") ; ^i
7035 (?\364 . "%F4") ; ^o
7036 (?\371 . "%F9") ; `u
7037 (?\373 . "%FB") ; ^u
7038 (?\; . "%3B")
7039 (?? . "%3F")
7040 (?= . "%3D")
7041 (?+ . "%2B")
7043 "Association list of escapes for some characters problematic in links.
7044 This is the list that is used for internal purposes.")
7046 (defconst org-link-escape-chars-browser
7047 '((?\ . "%20")) ; 32 for the SPC char
7048 "Association list of escapes for some characters problematic in links.
7049 This is the list that is used before handing over to the browser.")
7051 (defun org-link-escape (text &optional table)
7052 "Escape characters in TEXT that are problematic for links."
7053 (setq table (or table org-link-escape-chars))
7054 (when text
7055 (let ((re (mapconcat (lambda (x) (regexp-quote
7056 (char-to-string (car x))))
7057 table "\\|")))
7058 (while (string-match re text)
7059 (setq text
7060 (replace-match
7061 (cdr (assoc (string-to-char (match-string 0 text))
7062 table))
7063 t t text)))
7064 text)))
7066 (defun org-link-unescape (text &optional table)
7067 "Reverse the action of `org-link-escape'."
7068 (setq table (or table org-link-escape-chars))
7069 (when text
7070 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7071 table "\\|")))
7072 (while (string-match re text)
7073 (setq text
7074 (replace-match
7075 (char-to-string (car (rassoc (match-string 0 text) table)))
7076 t t text)))
7077 text)))
7079 (defun org-xor (a b)
7080 "Exclusive or."
7081 (if a (not b) b))
7083 (defun org-fixup-message-id-for-http (s)
7084 "Replace special characters in a message id, so it can be used in an http query."
7085 (while (string-match "<" s)
7086 (setq s (replace-match "%3C" t t s)))
7087 (while (string-match ">" s)
7088 (setq s (replace-match "%3E" t t s)))
7089 (while (string-match "@" s)
7090 (setq s (replace-match "%40" t t s)))
7093 ;;;###autoload
7094 (defun org-insert-link-global ()
7095 "Insert a link like Org-mode does.
7096 This command can be called in any mode to insert a link in Org-mode syntax."
7097 (interactive)
7098 (org-load-modules-maybe)
7099 (org-run-like-in-org-mode 'org-insert-link))
7101 (defun org-insert-link (&optional complete-file link-location)
7102 "Insert a link. At the prompt, enter the link.
7104 Completion can be used to insert any of the link protocol prefixes like
7105 http or ftp in use.
7107 The history can be used to select a link previously stored with
7108 `org-store-link'. When the empty string is entered (i.e. if you just
7109 press RET at the prompt), the link defaults to the most recently
7110 stored link. As SPC triggers completion in the minibuffer, you need to
7111 use M-SPC or C-q SPC to force the insertion of a space character.
7113 You will also be prompted for a description, and if one is given, it will
7114 be displayed in the buffer instead of the link.
7116 If there is already a link at point, this command will allow you to edit link
7117 and description parts.
7119 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7120 be selected using completion. The path to the file will be relative to the
7121 current directory if the file is in the current directory or a subdirectory.
7122 Otherwise, the link will be the absolute path as completed in the minibuffer
7123 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7124 option `org-link-file-path-type'.
7126 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7127 the current directory or below.
7129 With three \\[universal-argument] prefixes, negate the meaning of
7130 `org-keep-stored-link-after-insertion'.
7132 If `org-make-link-description-function' is non-nil, this function will be
7133 called with the link target, and the result will be the default
7134 link description.
7136 If the LINK-LOCATION parameter is non-nil, this value will be
7137 used as the link location instead of reading one interactively."
7138 (interactive "P")
7139 (let* ((wcf (current-window-configuration))
7140 (region (if (org-region-active-p)
7141 (buffer-substring (region-beginning) (region-end))))
7142 (remove (and region (list (region-beginning) (region-end))))
7143 (desc region)
7144 tmphist ; byte-compile incorrectly complains about this
7145 (link link-location)
7146 entry file)
7147 (cond
7148 (link-location) ; specified by arg, just use it.
7149 ((org-in-regexp org-bracket-link-regexp 1)
7150 ;; We do have a link at point, and we are going to edit it.
7151 (setq remove (list (match-beginning 0) (match-end 0)))
7152 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7153 (setq link (read-string "Link: "
7154 (org-link-unescape
7155 (org-match-string-no-properties 1)))))
7156 ((or (org-in-regexp org-angle-link-re)
7157 (org-in-regexp org-plain-link-re))
7158 ;; Convert to bracket link
7159 (setq remove (list (match-beginning 0) (match-end 0))
7160 link (read-string "Link: "
7161 (org-remove-angle-brackets (match-string 0)))))
7162 ((member complete-file '((4) (16)))
7163 ;; Completing read for file names.
7164 (setq file (read-file-name "File: "))
7165 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7166 (pwd1 (file-name-as-directory (abbreviate-file-name
7167 (expand-file-name ".")))))
7168 (cond
7169 ((equal complete-file '(16))
7170 (setq link (org-make-link
7171 "file:"
7172 (abbreviate-file-name (expand-file-name file)))))
7173 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7174 (setq link (org-make-link "file:" (match-string 1 file))))
7175 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7176 (expand-file-name file))
7177 (setq link (org-make-link
7178 "file:" (match-string 1 (expand-file-name file)))))
7179 (t (setq link (org-make-link "file:" file))))))
7181 ;; Read link, with completion for stored links.
7182 (with-output-to-temp-buffer "*Org Links*"
7183 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7184 (when org-stored-links
7185 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7186 (princ (mapconcat
7187 (lambda (x)
7188 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7189 (reverse org-stored-links) "\n"))))
7190 (let ((cw (selected-window)))
7191 (select-window (get-buffer-window "*Org Links*"))
7192 (setq truncate-lines t)
7193 (org-fit-window-to-buffer)
7194 (select-window cw))
7195 ;; Fake a link history, containing the stored links.
7196 (setq tmphist (append (mapcar 'car org-stored-links)
7197 org-insert-link-history))
7198 (unwind-protect
7199 (setq link
7200 (let ((org-completion-use-ido nil))
7201 (org-completing-read
7202 "Link: "
7203 (append
7204 (mapcar (lambda (x) (list (concat (car x) ":")))
7205 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7206 (mapcar (lambda (x) (list (concat x ":")))
7207 org-link-types))
7208 nil nil nil
7209 'tmphist
7210 (or (car (car org-stored-links))))))
7211 (set-window-configuration wcf)
7212 (kill-buffer "*Org Links*"))
7213 (setq entry (assoc link org-stored-links))
7214 (or entry (push link org-insert-link-history))
7215 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7216 (not org-keep-stored-link-after-insertion))
7217 (setq org-stored-links (delq (assoc link org-stored-links)
7218 org-stored-links)))
7219 (setq desc (or desc (nth 1 entry)))))
7221 (if (string-match org-plain-link-re link)
7222 ;; URL-like link, normalize the use of angular brackets.
7223 (setq link (org-make-link (org-remove-angle-brackets link))))
7225 ;; Check if we are linking to the current file with a search option
7226 ;; If yes, simplify the link by using only the search option.
7227 (when (and buffer-file-name
7228 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7229 (let* ((path (match-string 1 link))
7230 (case-fold-search nil)
7231 (search (match-string 2 link)))
7232 (save-match-data
7233 (if (equal (file-truename buffer-file-name) (file-truename path))
7234 ;; We are linking to this same file, with a search option
7235 (setq link search)))))
7237 ;; Check if we can/should use a relative path. If yes, simplify the link
7238 (when (string-match "^file:\\(.*\\)" link)
7239 (let* ((path (match-string 1 link))
7240 (origpath path)
7241 (case-fold-search nil))
7242 (cond
7243 ((or (eq org-link-file-path-type 'absolute)
7244 (equal complete-file '(16)))
7245 (setq path (abbreviate-file-name (expand-file-name path))))
7246 ((eq org-link-file-path-type 'noabbrev)
7247 (setq path (expand-file-name path)))
7248 ((eq org-link-file-path-type 'relative)
7249 (setq path (file-relative-name path)))
7251 (save-match-data
7252 (if (string-match (concat "^" (regexp-quote
7253 (file-name-as-directory
7254 (expand-file-name "."))))
7255 (expand-file-name path))
7256 ;; We are linking a file with relative path name.
7257 (setq path (substring (expand-file-name path)
7258 (match-end 0)))
7259 (setq path (abbreviate-file-name (expand-file-name path)))))))
7260 (setq link (concat "file:" path))
7261 (if (equal desc origpath)
7262 (setq desc path))))
7264 (if org-make-link-description-function
7265 (setq desc (funcall org-make-link-description-function link desc)))
7267 (setq desc (read-string "Description: " desc))
7268 (unless (string-match "\\S-" desc) (setq desc nil))
7269 (if remove (apply 'delete-region remove))
7270 (insert (org-make-link-string link desc))))
7272 (defun org-completing-read (&rest args)
7273 "Completing-read with SPACE being a normal character."
7274 (let ((minibuffer-local-completion-map
7275 (copy-keymap minibuffer-local-completion-map)))
7276 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7277 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7278 (apply 'org-ido-completing-read args)))
7280 (defun org-completing-read-no-ido (&rest args)
7281 (let (org-completion-use-ido)
7282 (apply 'org-completing-read args)))
7284 (defun org-ido-completing-read (&rest args)
7285 "Completing-read using `ido-mode' speedups if available"
7286 (if (and org-completion-use-ido
7287 (fboundp 'ido-completing-read)
7288 (boundp 'ido-mode) ido-mode
7289 (listp (second args)))
7290 (let ((ido-enter-matching-directory nil))
7291 (apply 'ido-completing-read (concat (car args))
7292 (mapcar (lambda (x) (car x)) (nth 1 args))
7293 (cddr args)))
7294 (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-extract-attributes-from-string (tag)
7310 (let (key value attr)
7311 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7312 (setq key (match-string 1 tag) value (match-string 2 tag)
7313 tag (replace-match "" t t tag)
7314 attr (plist-put attr (intern key) value)))
7315 (cons tag attr)))
7317 (defun org-attributes-to-string (plist)
7318 "Format a property list into an HTML attribute list."
7319 (let ((s "") key value)
7320 (while plist
7321 (setq key (pop plist) value (pop plist))
7322 (and value
7323 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7326 ;;; Opening/following a link
7328 (defvar org-link-search-failed nil)
7330 (defun org-next-link ()
7331 "Move forward to the next link.
7332 If the link is in hidden text, expose it."
7333 (interactive)
7334 (when (and org-link-search-failed (eq this-command last-command))
7335 (goto-char (point-min))
7336 (message "Link search wrapped back to beginning of buffer"))
7337 (setq org-link-search-failed nil)
7338 (let* ((pos (point))
7339 (ct (org-context))
7340 (a (assoc :link ct)))
7341 (if a (goto-char (nth 2 a)))
7342 (if (re-search-forward org-any-link-re nil t)
7343 (progn
7344 (goto-char (match-beginning 0))
7345 (if (org-invisible-p) (org-show-context)))
7346 (goto-char pos)
7347 (setq org-link-search-failed t)
7348 (error "No further link found"))))
7350 (defun org-previous-link ()
7351 "Move backward to the previous link.
7352 If the link is in hidden text, expose it."
7353 (interactive)
7354 (when (and org-link-search-failed (eq this-command last-command))
7355 (goto-char (point-max))
7356 (message "Link search wrapped back to end of buffer"))
7357 (setq org-link-search-failed nil)
7358 (let* ((pos (point))
7359 (ct (org-context))
7360 (a (assoc :link ct)))
7361 (if a (goto-char (nth 1 a)))
7362 (if (re-search-backward org-any-link-re nil t)
7363 (progn
7364 (goto-char (match-beginning 0))
7365 (if (org-invisible-p) (org-show-context)))
7366 (goto-char pos)
7367 (setq org-link-search-failed t)
7368 (error "No further link found"))))
7370 (defun org-translate-link (s)
7371 "Translate a link string if a translation function has been defined."
7372 (if (and org-link-translation-function
7373 (fboundp org-link-translation-function)
7374 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7375 (progn
7376 (setq s (funcall org-link-translation-function
7377 (match-string 1) (match-string 2)))
7378 (concat (car s) ":" (cdr s)))
7381 (defun org-translate-link-from-planner (type path)
7382 "Translate a link from Emacs Planner syntax so that Org can follow it.
7383 This is still an experimental function, your mileage may vary."
7384 (cond
7385 ((member type '("http" "https" "news" "ftp"))
7386 ;; standard Internet links are the same.
7387 nil)
7388 ((and (equal type "irc") (string-match "^//" path))
7389 ;; Planner has two / at the beginning of an irc link, we have 1.
7390 ;; We should have zero, actually....
7391 (setq path (substring path 1)))
7392 ((and (equal type "lisp") (string-match "^/" path))
7393 ;; Planner has a slash, we do not.
7394 (setq type "elisp" path (substring path 1)))
7395 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7396 ;; A typical message link. Planner has the id after the fina slash,
7397 ;; we separate it with a hash mark
7398 (setq path (concat (match-string 1 path) "#"
7399 (org-remove-angle-brackets (match-string 2 path)))))
7401 (cons type path))
7403 (defun org-find-file-at-mouse (ev)
7404 "Open file link or URL at mouse."
7405 (interactive "e")
7406 (mouse-set-point ev)
7407 (org-open-at-point 'in-emacs))
7409 (defun org-open-at-mouse (ev)
7410 "Open file link or URL at mouse."
7411 (interactive "e")
7412 (mouse-set-point ev)
7413 (if (eq major-mode 'org-agenda-mode)
7414 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7415 (org-open-at-point))
7417 (defvar org-window-config-before-follow-link nil
7418 "The window configuration before following a link.
7419 This is saved in case the need arises to restore it.")
7421 (defvar org-open-link-marker (make-marker)
7422 "Marker pointing to the location where `org-open-at-point; was called.")
7424 ;;;###autoload
7425 (defun org-open-at-point-global ()
7426 "Follow a link like Org-mode does.
7427 This command can be called in any mode to follow a link that has
7428 Org-mode syntax."
7429 (interactive)
7430 (org-run-like-in-org-mode 'org-open-at-point))
7432 ;;;###autoload
7433 (defun org-open-link-from-string (s &optional arg)
7434 "Open a link in the string S, as if it was in Org-mode."
7435 (interactive "sLink: \nP")
7436 (with-temp-buffer
7437 (let ((org-inhibit-startup t))
7438 (org-mode)
7439 (insert s)
7440 (goto-char (point-min))
7441 (org-open-at-point arg))))
7443 (defun org-open-at-point (&optional in-emacs)
7444 "Open link at or after point.
7445 If there is no link at point, this function will search forward up to
7446 the end of the current subtree.
7447 Normally, files will be opened by an appropriate application. If the
7448 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7449 With a double prefix argument, try to open outside of Emacs, in the
7450 application the system uses for this file type."
7451 (interactive "P")
7452 (org-load-modules-maybe)
7453 (move-marker org-open-link-marker (point))
7454 (setq org-window-config-before-follow-link (current-window-configuration))
7455 (org-remove-occur-highlights nil nil t)
7456 (cond
7457 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7458 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7459 (org-footnote-action))
7461 (let (type path link line search (pos (point)))
7462 (catch 'match
7463 (save-excursion
7464 (skip-chars-forward "^]\n\r")
7465 (when (org-in-regexp org-bracket-link-regexp)
7466 (setq link (org-extract-attributes
7467 (org-link-unescape (org-match-string-no-properties 1))))
7468 (while (string-match " *\n *" link)
7469 (setq link (replace-match " " t t link)))
7470 (setq link (org-link-expand-abbrev link))
7471 (cond
7472 ((or (file-name-absolute-p link)
7473 (string-match "^\\.\\.?/" link))
7474 (setq type "file" path link))
7475 ((string-match org-link-re-with-space3 link)
7476 (setq type (match-string 1 link) path (match-string 2 link)))
7477 (t (setq type "thisfile" path link)))
7478 (throw 'match t)))
7480 (when (get-text-property (point) 'org-linked-text)
7481 (setq type "thisfile"
7482 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7483 (1+ (point)) (point))
7484 path (buffer-substring
7485 (previous-single-property-change pos 'org-linked-text)
7486 (next-single-property-change pos 'org-linked-text)))
7487 (throw 'match t))
7489 (save-excursion
7490 (when (or (org-in-regexp org-angle-link-re)
7491 (org-in-regexp org-plain-link-re))
7492 (setq type (match-string 1) path (match-string 2))
7493 (throw 'match t)))
7494 (save-excursion
7495 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7496 (setq type "tags"
7497 path (match-string 1))
7498 (while (string-match ":" path)
7499 (setq path (replace-match "+" t t path)))
7500 (throw 'match t)))
7501 (when (org-in-regexp "<\\([^><\n]+\\)>")
7502 (setq type "tree-match"
7503 path (match-string 1))
7504 (throw 'match t)))
7505 (unless path
7506 (error "No link found"))
7507 ;; Remove any trailing spaces in path
7508 (if (string-match " +\\'" path)
7509 (setq path (replace-match "" t t path)))
7510 (if (and org-link-translation-function
7511 (fboundp org-link-translation-function))
7512 ;; Check if we need to translate the link
7513 (let ((tmp (funcall org-link-translation-function type path)))
7514 (setq type (car tmp) path (cdr tmp))))
7516 (cond
7518 ((assoc type org-link-protocols)
7519 (funcall (nth 1 (assoc type org-link-protocols)) path))
7521 ((equal type "mailto")
7522 (let ((cmd (car org-link-mailto-program))
7523 (args (cdr org-link-mailto-program)) args1
7524 (address path) (subject "") a)
7525 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7526 (setq address (match-string 1 path)
7527 subject (org-link-escape (match-string 2 path))))
7528 (while args
7529 (cond
7530 ((not (stringp (car args))) (push (pop args) args1))
7531 (t (setq a (pop args))
7532 (if (string-match "%a" a)
7533 (setq a (replace-match address t t a)))
7534 (if (string-match "%s" a)
7535 (setq a (replace-match subject t t a)))
7536 (push a args1))))
7537 (apply cmd (nreverse args1))))
7539 ((member type '("http" "https" "ftp" "news"))
7540 (browse-url (concat type ":" (org-link-escape
7541 path org-link-escape-chars-browser))))
7543 ((member type '("message"))
7544 (browse-url (concat type ":" path)))
7546 ((string= type "tags")
7547 (org-tags-view in-emacs path))
7548 ((string= type "thisfile")
7549 (if in-emacs
7550 (switch-to-buffer-other-window
7551 (org-get-buffer-for-internal-link (current-buffer)))
7552 (org-mark-ring-push))
7553 (let ((cmd `(org-link-search
7554 ,path
7555 ,(cond ((equal in-emacs '(4)) 'occur)
7556 ((equal in-emacs '(16)) 'org-occur)
7557 (t nil))
7558 ,pos)))
7559 (condition-case nil (eval cmd)
7560 (error (progn (widen) (eval cmd))))))
7562 ((string= type "tree-match")
7563 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7565 ((string= type "file")
7566 (if (string-match "::\\([0-9]+\\)\\'" path)
7567 (setq line (string-to-number (match-string 1 path))
7568 path (substring path 0 (match-beginning 0)))
7569 (if (string-match "::\\(.+\\)\\'" path)
7570 (setq search (match-string 1 path)
7571 path (substring path 0 (match-beginning 0)))))
7572 (if (string-match "[*?{]" (file-name-nondirectory path))
7573 (dired path)
7574 (org-open-file path in-emacs line search)))
7576 ((string= type "news")
7577 (require 'org-gnus)
7578 (org-gnus-follow-link path))
7580 ((string= type "shell")
7581 (let ((cmd path))
7582 (if (or (not org-confirm-shell-link-function)
7583 (funcall org-confirm-shell-link-function
7584 (format "Execute \"%s\" in shell? "
7585 (org-add-props cmd nil
7586 'face 'org-warning))))
7587 (progn
7588 (message "Executing %s" cmd)
7589 (shell-command cmd))
7590 (error "Abort"))))
7592 ((string= type "elisp")
7593 (let ((cmd path))
7594 (if (or (not org-confirm-elisp-link-function)
7595 (funcall org-confirm-elisp-link-function
7596 (format "Execute \"%s\" as elisp? "
7597 (org-add-props cmd nil
7598 'face 'org-warning))))
7599 (message "%s => %s" cmd
7600 (if (equal (string-to-char cmd) ?\()
7601 (eval (read cmd))
7602 (call-interactively (read cmd))))
7603 (error "Abort"))))
7606 (browse-url-at-point))))))
7607 (move-marker org-open-link-marker nil)
7608 (run-hook-with-args 'org-follow-link-hook))
7610 ;;;; Time estimates
7612 (defun org-get-effort (&optional pom)
7613 "Get the effort estimate for the current entry."
7614 (org-entry-get pom org-effort-property))
7616 ;;; File search
7618 (defvar org-create-file-search-functions nil
7619 "List of functions to construct the right search string for a file link.
7620 These functions are called in turn with point at the location to
7621 which the link should point.
7623 A function in the hook should first test if it would like to
7624 handle this file type, for example by checking the major-mode or
7625 the file extension. If it decides not to handle this file, it
7626 should just return nil to give other functions a chance. If it
7627 does handle the file, it must return the search string to be used
7628 when following the link. The search string will be part of the
7629 file link, given after a double colon, and `org-open-at-point'
7630 will automatically search for it. If special measures must be
7631 taken to make the search successful, another function should be
7632 added to the companion hook `org-execute-file-search-functions',
7633 which see.
7635 A function in this hook may also use `setq' to set the variable
7636 `description' to provide a suggestion for the descriptive text to
7637 be used for this link when it gets inserted into an Org-mode
7638 buffer with \\[org-insert-link].")
7640 (defvar org-execute-file-search-functions nil
7641 "List of functions to execute a file search triggered by a link.
7643 Functions added to this hook must accept a single argument, the
7644 search string that was part of the file link, the part after the
7645 double colon. The function must first check if it would like to
7646 handle this search, for example by checking the major-mode or the
7647 file extension. If it decides not to handle this search, it
7648 should just return nil to give other functions a chance. If it
7649 does handle the search, it must return a non-nil value to keep
7650 other functions from trying.
7652 Each function can access the current prefix argument through the
7653 variable `current-prefix-argument'. Note that a single prefix is
7654 used to force opening a link in Emacs, so it may be good to only
7655 use a numeric or double prefix to guide the search function.
7657 In case this is needed, a function in this hook can also restore
7658 the window configuration before `org-open-at-point' was called using:
7660 (set-window-configuration org-window-config-before-follow-link)")
7662 (defun org-link-search (s &optional type avoid-pos)
7663 "Search for a link search option.
7664 If S is surrounded by forward slashes, it is interpreted as a
7665 regular expression. In org-mode files, this will create an `org-occur'
7666 sparse tree. In ordinary files, `occur' will be used to list matches.
7667 If the current buffer is in `dired-mode', grep will be used to search
7668 in all files. If AVOID-POS is given, ignore matches near that position."
7669 (let ((case-fold-search t)
7670 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7671 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7672 (append '(("") (" ") ("\t") ("\n"))
7673 org-emphasis-alist)
7674 "\\|") "\\)"))
7675 (pos (point))
7676 (pre nil) (post nil)
7677 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7678 (cond
7679 ;; First check if there are any special
7680 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7681 ;; Now try the builtin stuff
7682 ((save-excursion
7683 (goto-char (point-min))
7684 (and
7685 (re-search-forward
7686 (concat "<<" (regexp-quote s0) ">>") nil t)
7687 (setq type 'dedicated
7688 pos (match-beginning 0))))
7689 ;; There is an exact target for this
7690 (goto-char pos))
7691 ((and (string-match "^(\\(.*\\))$" s0)
7692 (save-excursion
7693 (goto-char (point-min))
7694 (and
7695 (re-search-forward
7696 (concat "[^[]" (regexp-quote
7697 (format org-coderef-label-format
7698 (match-string 1 s0))))
7699 nil t)
7700 (setq type 'dedicated
7701 pos (1+ (match-beginning 0))))))
7702 ;; There is a coderef target for this
7703 (goto-char pos))
7704 ((string-match "^/\\(.*\\)/$" s)
7705 ;; A regular expression
7706 (cond
7707 ((org-mode-p)
7708 (org-occur (match-string 1 s)))
7709 ;;((eq major-mode 'dired-mode)
7710 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7711 (t (org-do-occur (match-string 1 s)))))
7713 ;; A normal search strings
7714 (when (equal (string-to-char s) ?*)
7715 ;; Anchor on headlines, post may include tags.
7716 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7717 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7718 s (substring s 1)))
7719 (remove-text-properties
7720 0 (length s)
7721 '(face nil mouse-face nil keymap nil fontified nil) s)
7722 ;; Make a series of regular expressions to find a match
7723 (setq words (org-split-string s "[ \n\r\t]+")
7725 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7726 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7727 "\\)" markers)
7728 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7729 re2a (concat "[ \t\r\n]" re2a_)
7730 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7731 re4 (concat "[^a-zA-Z_]" re4_)
7733 re1 (concat pre re2 post)
7734 re3 (concat pre (if pre re4_ re4) post)
7735 re5 (concat pre ".*" re4)
7736 re2 (concat pre re2)
7737 re2a (concat pre (if pre re2a_ re2a))
7738 re4 (concat pre (if pre re4_ re4))
7739 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7740 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7741 re5 "\\)"
7743 (cond
7744 ((eq type 'org-occur) (org-occur reall))
7745 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7746 (t (goto-char (point-min))
7747 (setq type 'fuzzy)
7748 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7749 (org-search-not-self 1 re1 nil t)
7750 (org-search-not-self 1 re2 nil t)
7751 (org-search-not-self 1 re2a nil t)
7752 (org-search-not-self 1 re3 nil t)
7753 (org-search-not-self 1 re4 nil t)
7754 (org-search-not-self 1 re5 nil t)
7756 (goto-char (match-beginning 1))
7757 (goto-char pos)
7758 (error "No match")))))
7760 ;; Normal string-search
7761 (goto-char (point-min))
7762 (if (search-forward s nil t)
7763 (goto-char (match-beginning 0))
7764 (error "No match"))))
7765 (and (org-mode-p) (org-show-context 'link-search))
7766 type))
7768 (defun org-search-not-self (group &rest args)
7769 "Execute `re-search-forward', but only accept matches that do not
7770 enclose the position of `org-open-link-marker'."
7771 (let ((m org-open-link-marker))
7772 (catch 'exit
7773 (while (apply 're-search-forward args)
7774 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7775 (goto-char (match-end group))
7776 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7777 (> (match-beginning 0) (marker-position m))
7778 (< (match-end 0) (marker-position m)))
7779 (save-match-data
7780 (or (not (org-in-regexp
7781 org-bracket-link-analytic-regexp 1))
7782 (not (match-end 4)) ; no description
7783 (and (<= (match-beginning 4) (point))
7784 (>= (match-end 4) (point))))))
7785 (throw 'exit (point))))))))
7787 (defun org-get-buffer-for-internal-link (buffer)
7788 "Return a buffer to be used for displaying the link target of internal links."
7789 (cond
7790 ((not org-display-internal-link-with-indirect-buffer)
7791 buffer)
7792 ((string-match "(Clone)$" (buffer-name buffer))
7793 (message "Buffer is already a clone, not making another one")
7794 ;; we also do not modify visibility in this case
7795 buffer)
7796 (t ; make a new indirect buffer for displaying the link
7797 (let* ((bn (buffer-name buffer))
7798 (ibn (concat bn "(Clone)"))
7799 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7800 (with-current-buffer ib (org-overview))
7801 ib))))
7803 (defun org-do-occur (regexp &optional cleanup)
7804 "Call the Emacs command `occur'.
7805 If CLEANUP is non-nil, remove the printout of the regular expression
7806 in the *Occur* buffer. This is useful if the regex is long and not useful
7807 to read."
7808 (occur regexp)
7809 (when cleanup
7810 (let ((cwin (selected-window)) win beg end)
7811 (when (setq win (get-buffer-window "*Occur*"))
7812 (select-window win))
7813 (goto-char (point-min))
7814 (when (re-search-forward "match[a-z]+" nil t)
7815 (setq beg (match-end 0))
7816 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7817 (setq end (1- (match-beginning 0)))))
7818 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7819 (goto-char (point-min))
7820 (select-window cwin))))
7822 ;;; The mark ring for links jumps
7824 (defvar org-mark-ring nil
7825 "Mark ring for positions before jumps in Org-mode.")
7826 (defvar org-mark-ring-last-goto nil
7827 "Last position in the mark ring used to go back.")
7828 ;; Fill and close the ring
7829 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7830 (loop for i from 1 to org-mark-ring-length do
7831 (push (make-marker) org-mark-ring))
7832 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7833 org-mark-ring)
7835 (defun org-mark-ring-push (&optional pos buffer)
7836 "Put the current position or POS into the mark ring and rotate it."
7837 (interactive)
7838 (setq pos (or pos (point)))
7839 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7840 (move-marker (car org-mark-ring)
7841 (or pos (point))
7842 (or buffer (current-buffer)))
7843 (message "%s"
7844 (substitute-command-keys
7845 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7847 (defun org-mark-ring-goto (&optional n)
7848 "Jump to the previous position in the mark ring.
7849 With prefix arg N, jump back that many stored positions. When
7850 called several times in succession, walk through the entire ring.
7851 Org-mode commands jumping to a different position in the current file,
7852 or to another Org-mode file, automatically push the old position
7853 onto the ring."
7854 (interactive "p")
7855 (let (p m)
7856 (if (eq last-command this-command)
7857 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7858 (setq p org-mark-ring))
7859 (setq org-mark-ring-last-goto p)
7860 (setq m (car p))
7861 (switch-to-buffer (marker-buffer m))
7862 (goto-char m)
7863 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7865 (defun org-remove-angle-brackets (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)))
7869 (defun org-add-angle-brackets (s)
7870 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7871 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7873 (defun org-remove-double-quotes (s)
7874 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7875 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7878 ;;; Following specific links
7880 (defun org-follow-timestamp-link ()
7881 (cond
7882 ((org-at-date-range-p t)
7883 (let ((org-agenda-start-on-weekday)
7884 (t1 (match-string 1))
7885 (t2 (match-string 2)))
7886 (setq t1 (time-to-days (org-time-string-to-time t1))
7887 t2 (time-to-days (org-time-string-to-time t2)))
7888 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7889 ((org-at-timestamp-p t)
7890 (org-agenda-list nil (time-to-days (org-time-string-to-time
7891 (substring (match-string 1) 0 10)))
7893 (t (error "This should not happen"))))
7896 ;;; Following file links
7897 (defvar org-wait nil)
7898 (defun org-open-file (path &optional in-emacs line search)
7899 "Open the file at PATH.
7900 First, this expands any special file name abbreviations. Then the
7901 configuration variable `org-file-apps' is checked if it contains an
7902 entry for this file type, and if yes, the corresponding command is launched.
7904 If no application is found, Emacs simply visits the file.
7906 With optional prefix argument IN-EMACS, Emacs will visit the file.
7907 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7908 and o use an external application to visit the file.
7910 Optional LINE specifies a line to go to, optional SEARCH a string to
7911 search for. If LINE or SEARCH is given, the file will always be
7912 opened in Emacs.
7913 If the file does not exist, an error is thrown."
7914 (setq in-emacs (or in-emacs line search))
7915 (let* ((file (if (equal path "")
7916 buffer-file-name
7917 (substitute-in-file-name (expand-file-name path))))
7918 (apps (append org-file-apps (org-default-apps)))
7919 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7920 (dirp (if remp nil (file-directory-p file)))
7921 (file (if (and dirp org-open-directory-means-index-dot-org)
7922 (concat (file-name-as-directory file) "index.org")
7923 file))
7924 (a-m-a-p (assq 'auto-mode apps))
7925 (dfile (downcase file))
7926 (old-buffer (current-buffer))
7927 (old-pos (point))
7928 (old-mode major-mode)
7929 ext cmd)
7930 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7931 (setq ext (match-string 1 dfile))
7932 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7933 (setq ext (match-string 1 dfile))))
7934 (cond
7935 ((equal in-emacs '(16))
7936 (setq cmd (cdr (assoc 'system apps))))
7937 (in-emacs (setq cmd 'emacs))
7939 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7940 (and dirp (cdr (assoc 'directory apps)))
7941 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7942 'string-match)
7943 (cdr (assoc ext apps))
7944 (cdr (assoc t apps))))))
7945 (when (eq cmd 'system)
7946 (setq cmd (cdr (assoc 'system apps))))
7947 (when (eq cmd 'default)
7948 (setq cmd (cdr (assoc t apps))))
7949 (when (eq cmd 'mailcap)
7950 (require 'mailcap)
7951 (mailcap-parse-mailcaps)
7952 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7953 (command (mailcap-mime-info mime-type)))
7954 (if (stringp command)
7955 (setq cmd command)
7956 (setq cmd 'emacs))))
7957 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7958 (not (file-exists-p file))
7959 (not org-open-non-existing-files))
7960 (error "No such file: %s" file))
7961 (cond
7962 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7963 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7964 (while (string-match "['\"]%s['\"]" cmd)
7965 (setq cmd (replace-match "%s" t t cmd)))
7966 (while (string-match "%s" cmd)
7967 (setq cmd (replace-match
7968 (save-match-data
7969 (shell-quote-argument
7970 (convert-standard-filename file)))
7971 t t cmd)))
7972 (save-window-excursion
7973 (start-process-shell-command cmd nil cmd)
7974 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7976 ((or (stringp cmd)
7977 (eq cmd 'emacs))
7978 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7979 (widen)
7980 (if line (goto-line line)
7981 (if search (org-link-search search))))
7982 ((consp cmd)
7983 (let ((file (convert-standard-filename file)))
7984 (eval cmd)))
7985 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7986 (and (org-mode-p) (eq old-mode 'org-mode)
7987 (or (not (equal old-buffer (current-buffer)))
7988 (not (equal old-pos (point))))
7989 (org-mark-ring-push old-pos old-buffer))))
7991 (defun org-default-apps ()
7992 "Return the default applications for this operating system."
7993 (cond
7994 ((eq system-type 'darwin)
7995 org-file-apps-defaults-macosx)
7996 ((eq system-type 'windows-nt)
7997 org-file-apps-defaults-windowsnt)
7998 (t org-file-apps-defaults-gnu)))
8000 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8001 "Convert extensions to regular expressions in the cars of LIST.
8002 Also, weed out any non-string entries, because the return value is used
8003 only for regexp matching.
8004 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8005 point to the symbol `emacs', indicating that the file should
8006 be opened in Emacs."
8007 (append
8008 (delq nil
8009 (mapcar (lambda (x)
8010 (if (not (stringp (car x)))
8012 (if (string-match "\\W" (car x))
8014 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8015 list))
8016 (if add-auto-mode
8017 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8019 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8020 (defun org-file-remote-p (file)
8021 "Test whether FILE specifies a location on a remote system.
8022 Return non-nil if the location is indeed remote.
8024 For example, the filename \"/user@host:/foo\" specifies a location
8025 on the system \"/user@host:\"."
8026 (cond ((fboundp 'file-remote-p)
8027 (file-remote-p file))
8028 ((fboundp 'tramp-handle-file-remote-p)
8029 (tramp-handle-file-remote-p file))
8030 ((and (boundp 'ange-ftp-name-format)
8031 (string-match (car ange-ftp-name-format) file))
8033 (t nil)))
8036 ;;;; Refiling
8038 (defun org-get-org-file ()
8039 "Read a filename, with default directory `org-directory'."
8040 (let ((default (or org-default-notes-file remember-data-file)))
8041 (read-file-name (format "File name [%s]: " default)
8042 (file-name-as-directory org-directory)
8043 default)))
8045 (defun org-notes-order-reversed-p ()
8046 "Check if the current file should receive notes in reversed order."
8047 (cond
8048 ((not org-reverse-note-order) nil)
8049 ((eq t org-reverse-note-order) t)
8050 ((not (listp org-reverse-note-order)) nil)
8051 (t (catch 'exit
8052 (let ((all org-reverse-note-order)
8053 entry)
8054 (while (setq entry (pop all))
8055 (if (string-match (car entry) buffer-file-name)
8056 (throw 'exit (cdr entry))))
8057 nil)))))
8059 (defvar org-refile-target-table nil
8060 "The list of refile targets, created by `org-refile'.")
8062 (defvar org-agenda-new-buffers nil
8063 "Buffers created to visit agenda files.")
8065 (defun org-get-refile-targets (&optional default-buffer)
8066 "Produce a table with refile targets."
8067 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8068 targets txt re files f desc descre fast-path-p level)
8069 (message "Getting targets...")
8070 (with-current-buffer (or default-buffer (current-buffer))
8071 (while (setq entry (pop entries))
8072 (setq files (car entry) desc (cdr entry))
8073 (setq fast-path-p nil)
8074 (cond
8075 ((null files) (setq files (list (current-buffer))))
8076 ((eq files 'org-agenda-files)
8077 (setq files (org-agenda-files 'unrestricted)))
8078 ((and (symbolp files) (fboundp files))
8079 (setq files (funcall files)))
8080 ((and (symbolp files) (boundp files))
8081 (setq files (symbol-value files))))
8082 (if (stringp files) (setq files (list files)))
8083 (cond
8084 ((eq (car desc) :tag)
8085 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8086 ((eq (car desc) :todo)
8087 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8088 ((eq (car desc) :regexp)
8089 (setq descre (cdr desc)))
8090 ((eq (car desc) :level)
8091 (setq descre (concat "^\\*\\{" (number-to-string
8092 (if org-odd-levels-only
8093 (1- (* 2 (cdr desc)))
8094 (cdr desc)))
8095 "\\}[ \t]")))
8096 ((eq (car desc) :maxlevel)
8097 (setq fast-path-p t)
8098 (setq descre (concat "^\\*\\{1," (number-to-string
8099 (if org-odd-levels-only
8100 (1- (* 2 (cdr desc)))
8101 (cdr desc)))
8102 "\\}[ \t]")))
8103 (t (error "Bad refiling target description %s" desc)))
8104 (while (setq f (pop files))
8105 (save-excursion
8106 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8107 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8108 (setq f (expand-file-name f))
8109 (save-excursion
8110 (save-restriction
8111 (widen)
8112 (goto-char (point-min))
8113 (while (re-search-forward descre nil t)
8114 (goto-char (point-at-bol))
8115 (when (looking-at org-complex-heading-regexp)
8116 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8117 txt (org-link-display-format (match-string 4))
8118 re (concat "^" (regexp-quote
8119 (buffer-substring (match-beginning 1)
8120 (match-end 4)))))
8121 (if (match-end 5) (setq re (concat re "[ \t]+"
8122 (regexp-quote
8123 (match-string 5)))))
8124 (setq re (concat re "[ \t]*$"))
8125 (when org-refile-use-outline-path
8126 (setq txt (mapconcat 'org-protect-slash
8127 (append
8128 (if (eq org-refile-use-outline-path 'file)
8129 (list (file-name-nondirectory
8130 (buffer-file-name (buffer-base-buffer))))
8131 (if (eq org-refile-use-outline-path 'full-file-path)
8132 (list (buffer-file-name (buffer-base-buffer)))))
8133 (org-get-outline-path fast-path-p level txt)
8134 (list txt))
8135 "/")))
8136 (push (list txt f re (point)) targets))
8137 (goto-char (point-at-eol))))))))
8138 (message "Getting targets...done")
8139 (nreverse targets))))
8141 (defun org-protect-slash (s)
8142 (while (string-match "/" s)
8143 (setq s (replace-match "\\" t t s)))
8146 (defvar org-olpa (make-vector 20 nil))
8148 (defun org-get-outline-path (&optional fastp level heading)
8149 "Return the outline path to the current entry, as a list."
8150 (if fastp
8151 (progn
8152 (if (> level 19)
8153 (error "Outline path failure, more than 19 levels."))
8154 (loop for i from level upto 19 do
8155 (aset org-olpa i nil))
8156 (prog1
8157 (delq nil (append org-olpa nil))
8158 (aset org-olpa level heading)))
8159 (let (rtn)
8160 (save-excursion
8161 (while (org-up-heading-safe)
8162 (when (looking-at org-complex-heading-regexp)
8163 (push (org-match-string-no-properties 4) rtn)))
8164 rtn))))
8166 (defvar org-refile-history nil
8167 "History for refiling operations.")
8169 (defun org-refile (&optional goto default-buffer)
8170 "Move the entry at point to another heading.
8171 The list of target headings is compiled using the information in
8172 `org-refile-targets', which see. This list is created before each use
8173 and will therefore always be up-to-date.
8175 At the target location, the entry is filed as a subitem of the target heading.
8176 Depending on `org-reverse-note-order', the new subitem will either be the
8177 first or the last subitem.
8179 If there is an active region, all entries in that region will be moved.
8180 However, the region must fulfil the requirement that the first heading
8181 is the first one sets the top-level of the moved text - at most siblings
8182 below it are allowed.
8184 With prefix arg GOTO, the command will only visit the target location,
8185 not actually move anything.
8186 With a double prefix `C-u C-u', go to the location where the last refiling
8187 operation has put the subtree."
8188 (interactive "P")
8189 (let* ((cbuf (current-buffer))
8190 (regionp (org-region-active-p))
8191 (region-start (and regionp (region-beginning)))
8192 (region-end (and regionp (region-end)))
8193 (region-length (and regionp (- region-end region-start)))
8194 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8195 pos it nbuf file re level reversed)
8196 (when regionp (goto-char region-start)
8197 (unless (org-kill-is-subtree-p
8198 (buffer-substring region-start region-end))
8199 (error "The region is not a (sequence of) subtree(s)")))
8200 (if (equal goto '(16))
8201 (org-refile-goto-last-stored)
8202 (when (setq it (org-refile-get-location
8203 (if goto "Goto: " "Refile to: ") default-buffer))
8204 (setq file (nth 1 it)
8205 re (nth 2 it)
8206 pos (nth 3 it))
8207 (if (and (not goto)
8208 (equal (buffer-file-name) file)
8209 (if regionp
8210 (and (>= pos region-start)
8211 (<= pos region-end))
8212 (and (>= pos (point))
8213 (< pos (save-excursion
8214 (org-end-of-subtree t t))))))
8215 (error "Cannot refile to position inside the tree or region"))
8217 (setq nbuf (or (find-buffer-visiting file)
8218 (find-file-noselect file)))
8219 (if goto
8220 (progn
8221 (switch-to-buffer nbuf)
8222 (goto-char pos)
8223 (org-show-context 'org-goto))
8224 (if regionp
8225 (progn
8226 (kill-new (buffer-substring region-start region-end))
8227 (org-save-markers-in-region region-start region-end))
8228 (org-copy-subtree 1 nil t))
8229 (save-excursion
8230 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8231 (find-file-noselect file))))
8232 (setq reversed (org-notes-order-reversed-p))
8233 (save-excursion
8234 (save-restriction
8235 (widen)
8236 (goto-char pos)
8237 (looking-at outline-regexp)
8238 (setq level (org-get-valid-level (funcall outline-level) 1))
8239 (goto-char
8240 (if reversed
8241 (or (outline-next-heading) (point-max))
8242 (or (save-excursion (outline-get-next-sibling))
8243 (org-end-of-subtree t t)
8244 (point-max))))
8245 (if (not (bolp)) (newline))
8246 (bookmark-set "org-refile-last-stored")
8247 (org-paste-subtree level))))
8248 (if regionp
8249 (delete-region (point) (+ (point) region-length))
8250 (org-cut-subtree))
8251 (setq org-markers-to-move nil)
8252 (message "Refiled to \"%s\"" (car it)))))))
8254 (defun org-refile-goto-last-stored ()
8255 "Go to the location where the last refile was stored."
8256 (interactive)
8257 (bookmark-jump "org-refile-last-stored")
8258 (message "This is the location of the last refile"))
8260 (defun org-refile-get-location (&optional prompt default-buffer)
8261 "Prompt the user for a refile location, using PROMPT."
8262 (let ((org-refile-targets org-refile-targets)
8263 (org-refile-use-outline-path org-refile-use-outline-path))
8264 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8265 (unless org-refile-target-table
8266 (error "No refile targets"))
8267 (let* ((cbuf (current-buffer))
8268 (partial-completion-mode nil)
8269 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8270 (cfunc (if (and org-refile-use-outline-path
8271 org-outline-path-complete-in-steps)
8272 'org-olpath-completing-read
8273 'org-ido-completing-read))
8274 (extra (if org-refile-use-outline-path "/" ""))
8275 (filename (and cfn (expand-file-name cfn)))
8276 (tbl (mapcar
8277 (lambda (x)
8278 (if (and (not (member org-refile-use-outline-path
8279 '(file full-file-path)))
8280 (not (equal filename (nth 1 x))))
8281 (cons (concat (car x) extra " ("
8282 (file-name-nondirectory (nth 1 x)) ")")
8283 (cdr x))
8284 (cons (concat (car x) extra) (cdr x))))
8285 org-refile-target-table))
8286 (completion-ignore-case t))
8287 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
8288 tbl)))
8290 (defun org-olpath-completing-read (prompt collection &rest args)
8291 "Read an outline path like a file name."
8292 (let ((thetable collection)
8293 (org-completion-use-ido nil)) ; does not work with ido.
8294 (apply
8295 'org-ido-completing-read prompt
8296 (lambda (string predicate &optional flag)
8297 (let (rtn r f (l (length string)))
8298 (cond
8299 ((eq flag nil)
8300 ;; try completion
8301 (try-completion string thetable))
8302 ((eq flag t)
8303 ;; all-completions
8304 (setq rtn (all-completions string thetable predicate))
8305 (mapcar
8306 (lambda (x)
8307 (setq r (substring x l))
8308 (if (string-match " ([^)]*)$" x)
8309 (setq f (match-string 0 x))
8310 (setq f ""))
8311 (if (string-match "/" r)
8312 (concat string (substring r 0 (match-end 0)) f)
8314 rtn))
8315 ((eq flag 'lambda)
8316 ;; exact match?
8317 (assoc string thetable)))
8319 args)))
8321 ;;;; Dynamic blocks
8323 (defun org-find-dblock (name)
8324 "Find the first dynamic block with name NAME in the buffer.
8325 If not found, stay at current position and return nil."
8326 (let (pos)
8327 (save-excursion
8328 (goto-char (point-min))
8329 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8330 nil t)
8331 (match-beginning 0))))
8332 (if pos (goto-char pos))
8333 pos))
8335 (defconst org-dblock-start-re
8336 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8337 "Matches the startline of a dynamic block, with parameters.")
8339 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8340 "Matches the end of a dynamic block.")
8342 (defun org-create-dblock (plist)
8343 "Create a dynamic block section, with parameters taken from PLIST.
8344 PLIST must contain a :name entry which is used as name of the block."
8345 (unless (bolp) (newline))
8346 (let ((name (plist-get plist :name)))
8347 (insert "#+BEGIN: " name)
8348 (while plist
8349 (if (eq (car plist) :name)
8350 (setq plist (cddr plist))
8351 (insert " " (prin1-to-string (pop plist)))))
8352 (insert "\n\n#+END:\n")
8353 (beginning-of-line -2)))
8355 (defun org-prepare-dblock ()
8356 "Prepare dynamic block for refresh.
8357 This empties the block, puts the cursor at the insert position and returns
8358 the property list including an extra property :name with the block name."
8359 (unless (looking-at org-dblock-start-re)
8360 (error "Not at a dynamic block"))
8361 (let* ((begdel (1+ (match-end 0)))
8362 (name (org-no-properties (match-string 1)))
8363 (params (append (list :name name)
8364 (read (concat "(" (match-string 3) ")")))))
8365 (unless (re-search-forward org-dblock-end-re nil t)
8366 (error "Dynamic block not terminated"))
8367 (setq params
8368 (append params
8369 (list :content (buffer-substring
8370 begdel (match-beginning 0)))))
8371 (delete-region begdel (match-beginning 0))
8372 (goto-char begdel)
8373 (open-line 1)
8374 params))
8376 (defun org-map-dblocks (&optional command)
8377 "Apply COMMAND to all dynamic blocks in the current buffer.
8378 If COMMAND is not given, use `org-update-dblock'."
8379 (let ((cmd (or command 'org-update-dblock))
8380 pos)
8381 (save-excursion
8382 (goto-char (point-min))
8383 (while (re-search-forward org-dblock-start-re nil t)
8384 (goto-char (setq pos (match-beginning 0)))
8385 (condition-case nil
8386 (funcall cmd)
8387 (error (message "Error during update of dynamic block")))
8388 (goto-char pos)
8389 (unless (re-search-forward org-dblock-end-re nil t)
8390 (error "Dynamic block not terminated"))))))
8392 (defun org-dblock-update (&optional arg)
8393 "User command for updating dynamic blocks.
8394 Update the dynamic block at point. With prefix ARG, update all dynamic
8395 blocks in the buffer."
8396 (interactive "P")
8397 (if arg
8398 (org-update-all-dblocks)
8399 (or (looking-at org-dblock-start-re)
8400 (org-beginning-of-dblock))
8401 (org-update-dblock)))
8403 (defun org-update-dblock ()
8404 "Update the dynamic block at point
8405 This means to empty the block, parse for parameters and then call
8406 the correct writing function."
8407 (save-window-excursion
8408 (let* ((pos (point))
8409 (line (org-current-line))
8410 (params (org-prepare-dblock))
8411 (name (plist-get params :name))
8412 (cmd (intern (concat "org-dblock-write:" name))))
8413 (message "Updating dynamic block `%s' at line %d..." name line)
8414 (funcall cmd params)
8415 (message "Updating dynamic block `%s' at line %d...done" name line)
8416 (goto-char pos))))
8418 (defun org-beginning-of-dblock ()
8419 "Find the beginning of the dynamic block at point.
8420 Error if there is no such block at point."
8421 (let ((pos (point))
8422 beg)
8423 (end-of-line 1)
8424 (if (and (re-search-backward org-dblock-start-re nil t)
8425 (setq beg (match-beginning 0))
8426 (re-search-forward org-dblock-end-re nil t)
8427 (> (match-end 0) pos))
8428 (goto-char beg)
8429 (goto-char pos)
8430 (error "Not in a dynamic block"))))
8432 (defun org-update-all-dblocks ()
8433 "Update all dynamic blocks in the buffer.
8434 This function can be used in a hook."
8435 (when (org-mode-p)
8436 (org-map-dblocks 'org-update-dblock)))
8439 ;;;; Completion
8441 (defconst org-additional-option-like-keywords
8442 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8443 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8444 "BEGIN_EXAMPLE" "END_EXAMPLE"
8445 "BEGIN_QUOTE" "END_QUOTE"
8446 "BEGIN_VERSE" "END_VERSE"
8447 "BEGIN_CENTER" "END_CENTER"
8448 "BEGIN_SRC" "END_SRC"
8449 "CATEGORY" "COLUMNS"
8450 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8452 (defcustom org-structure-template-alist
8454 ("s" "#+begin_src ?\n\n#+end_src"
8455 "<src lang=\"?\">\n\n</src>")
8456 ("e" "#+begin_example\n?\n#+end_example"
8457 "<example>\n?\n</example>")
8458 ("q" "#+begin_quote\n?\n#+end_quote"
8459 "<quote>\n?\n</quote>")
8460 ("v" "#+begin_verse\n?\n#+end_verse"
8461 "<verse>\n?\n/verse>")
8462 ("c" "#+begin_center\n?\n#+end_center"
8463 "<center>\n?\n/center>")
8464 ("l" "#+begin_latex\n?\n#+end_latex"
8465 "<literal style=\"latex\">\n?\n</literal>")
8466 ("L" "#+latex: "
8467 "<literal style=\"latex\">?</literal>")
8468 ("h" "#+begin_html\n?\n#+end_html"
8469 "<literal style=\"html\">\n?\n</literal>")
8470 ("H" "#+html: "
8471 "<literal style=\"html\">?</literal>")
8472 ("a" "#+begin_ascii\n?\n#+end_ascii")
8473 ("A" "#+ascii: ")
8474 ("i" "#+include %file ?"
8475 "<include file=%file markup=\"?\">")
8477 "Structure completion elements.
8478 This is a list of abbreviation keys and values. The value gets inserted
8479 it you type @samp{.} followed by the key and then the completion key,
8480 usually `M-TAB'. %file will be replaced by a file name after prompting
8481 for the file using completion.
8482 There are two templates for each key, the first uses the original Org syntax,
8483 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8484 the default when the /org-mtags.el/ module has been loaded. See also the
8485 variable `org-mtags-prefer-muse-templates'.
8486 This is an experimental feature, it is undecided if it is going to stay in."
8487 :group 'org-completion
8488 :type '(repeat
8489 (string :tag "Key")
8490 (string :tag "Template")
8491 (string :tag "Muse Template")))
8493 (defun org-try-structure-completion ()
8494 "Try to complete a structure template before point.
8495 This looks for strings like \"<e\" on an otherwise empty line and
8496 expands them."
8497 (let ((l (buffer-substring (point-at-bol) (point)))
8499 (when (and (looking-at "[ \t]*$")
8500 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8501 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8502 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8503 (match-beginning 1)) a)
8504 t)))
8506 (defun org-complete-expand-structure-template (start cell)
8507 "Expand a structure template."
8508 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8509 (rpl (nth (if musep 2 1) cell)))
8510 (delete-region start (point))
8511 (when (string-match "\\`#\\+" rpl)
8512 (cond
8513 ((bolp))
8514 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8515 (delete-region (point-at-bol) (point)))
8516 (t (newline))))
8517 (setq start (point))
8518 (if (string-match "%file" rpl)
8519 (setq rpl (replace-match
8520 (concat
8521 "\""
8522 (save-match-data
8523 (abbreviate-file-name (read-file-name "Include file: ")))
8524 "\"")
8525 t t rpl)))
8526 (insert rpl)
8527 (if (re-search-backward "\\?" start t) (delete-char 1))))
8530 (defun org-complete (&optional arg)
8531 "Perform completion on word at point.
8532 At the beginning of a headline, this completes TODO keywords as given in
8533 `org-todo-keywords'.
8534 If the current word is preceded by a backslash, completes the TeX symbols
8535 that are supported for HTML support.
8536 If the current word is preceded by \"#+\", completes special words for
8537 setting file options.
8538 In the line after \"#+STARTUP:, complete valid keywords.\"
8539 At all other locations, this simply calls the value of
8540 `org-completion-fallback-command'."
8541 (interactive "P")
8542 (org-without-partial-completion
8543 (catch 'exit
8544 (let* ((a nil)
8545 (end (point))
8546 (beg1 (save-excursion
8547 (skip-chars-backward (org-re "[:alnum:]_@"))
8548 (point)))
8549 (beg (save-excursion
8550 (skip-chars-backward "a-zA-Z0-9_:$")
8551 (point)))
8552 (confirm (lambda (x) (stringp (car x))))
8553 (searchhead (equal (char-before beg) ?*))
8554 (struct
8555 (when (and (member (char-before beg1) '(?. ?<))
8556 (setq a (assoc (buffer-substring beg1 (point))
8557 org-structure-template-alist)))
8558 (org-complete-expand-structure-template (1- beg1) a)
8559 (throw 'exit t)))
8560 (tag (and (equal (char-before beg1) ?:)
8561 (equal (char-after (point-at-bol)) ?*)))
8562 (prop (and (equal (char-before beg1) ?:)
8563 (not (equal (char-after (point-at-bol)) ?*))))
8564 (texp (equal (char-before beg) ?\\))
8565 (link (equal (char-before beg) ?\[))
8566 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8567 beg)
8568 "#+"))
8569 (startup (string-match "^#\\+STARTUP:.*"
8570 (buffer-substring (point-at-bol) (point))))
8571 (completion-ignore-case opt)
8572 (type nil)
8573 (tbl nil)
8574 (table (cond
8575 (opt
8576 (setq type :opt)
8577 (require 'org-exp)
8578 (append
8579 (mapcar
8580 (lambda (x)
8581 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8582 (cons (match-string 2 x) (match-string 1 x)))
8583 (org-split-string (org-get-current-options) "\n"))
8584 (mapcar 'list org-additional-option-like-keywords)))
8585 (startup
8586 (setq type :startup)
8587 org-startup-options)
8588 (link (append org-link-abbrev-alist-local
8589 org-link-abbrev-alist))
8590 (texp
8591 (setq type :tex)
8592 org-html-entities)
8593 ((string-match "\\`\\*+[ \t]+\\'"
8594 (buffer-substring (point-at-bol) beg))
8595 (setq type :todo)
8596 (mapcar 'list org-todo-keywords-1))
8597 (searchhead
8598 (setq type :searchhead)
8599 (save-excursion
8600 (goto-char (point-min))
8601 (while (re-search-forward org-todo-line-regexp nil t)
8602 (push (list
8603 (org-make-org-heading-search-string
8604 (match-string 3) t))
8605 tbl)))
8606 tbl)
8607 (tag (setq type :tag beg beg1)
8608 (or org-tag-alist (org-get-buffer-tags)))
8609 (prop (setq type :prop beg beg1)
8610 (mapcar 'list (org-buffer-property-keys nil t t)))
8611 (t (progn
8612 (call-interactively org-completion-fallback-command)
8613 (throw 'exit nil)))))
8614 (pattern (buffer-substring-no-properties beg end))
8615 (completion (try-completion pattern table confirm)))
8616 (cond ((eq completion t)
8617 (if (not (assoc (upcase pattern) table))
8618 (message "Already complete")
8619 (if (and (equal type :opt)
8620 (not (member (car (assoc (upcase pattern) table))
8621 org-additional-option-like-keywords)))
8622 (insert (substring (cdr (assoc (upcase pattern) table))
8623 (length pattern)))
8624 (if (memq type '(:tag :prop)) (insert ":")))))
8625 ((null completion)
8626 (message "Can't find completion for \"%s\"" pattern)
8627 (ding))
8628 ((not (string= pattern completion))
8629 (delete-region beg end)
8630 (if (string-match " +$" completion)
8631 (setq completion (replace-match "" t t completion)))
8632 (insert completion)
8633 (if (get-buffer-window "*Completions*")
8634 (delete-window (get-buffer-window "*Completions*")))
8635 (if (assoc completion table)
8636 (if (eq type :todo) (insert " ")
8637 (if (memq type '(:tag :prop)) (insert ":"))))
8638 (if (and (equal type :opt) (assoc completion table))
8639 (message "%s" (substitute-command-keys
8640 "Press \\[org-complete] again to insert example settings"))))
8642 (message "Making completion list...")
8643 (let ((list (sort (all-completions pattern table confirm)
8644 'string<)))
8645 (with-output-to-temp-buffer "*Completions*"
8646 (condition-case nil
8647 ;; Protection needed for XEmacs and emacs 21
8648 (display-completion-list list pattern)
8649 (error (display-completion-list list)))))
8650 (message "Making completion list...%s" "done")))))))
8652 ;;;; TODO, DEADLINE, Comments
8654 (defun org-toggle-comment ()
8655 "Change the COMMENT state of an entry."
8656 (interactive)
8657 (save-excursion
8658 (org-back-to-heading)
8659 (let (case-fold-search)
8660 (if (looking-at (concat outline-regexp
8661 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8662 (replace-match "" t t nil 1)
8663 (if (looking-at outline-regexp)
8664 (progn
8665 (goto-char (match-end 0))
8666 (insert org-comment-string " ")))))))
8668 (defvar org-last-todo-state-is-todo nil
8669 "This is non-nil when the last TODO state change led to a TODO state.
8670 If the last change removed the TODO tag or switched to DONE, then
8671 this is nil.")
8673 (defvar org-setting-tags nil) ; dynamically skipped
8675 (defun org-parse-local-options (string var)
8676 "Parse STRING for startup setting relevant for variable VAR."
8677 (let ((rtn (symbol-value var))
8678 e opts)
8679 (save-match-data
8680 (if (or (not string) (not (string-match "\\S-" string)))
8682 (setq opts (delq nil (mapcar (lambda (x)
8683 (setq e (assoc x org-startup-options))
8684 (if (eq (nth 1 e) var) e nil))
8685 (org-split-string string "[ \t]+"))))
8686 (if (not opts)
8688 (setq rtn nil)
8689 (while (setq e (pop opts))
8690 (if (not (nth 3 e))
8691 (setq rtn (nth 2 e))
8692 (if (not (listp rtn)) (setq rtn nil))
8693 (push (nth 2 e) rtn)))
8694 rtn)))))
8696 (defvar org-todo-setup-filter-hook nil
8697 "Hook for functions that pre-filter todo specs.
8699 Each function takes a todo spec and returns either `nil' or the spec
8700 transformed into canonical form." )
8702 (defvar org-todo-get-default-hook nil
8703 "Hook for functions that get a default item for todo.
8705 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8706 `nil' or a string to be used for the todo mark." )
8708 (defvar org-agenda-headline-snapshot-before-repeat)
8709 (defun org-todo (&optional arg)
8710 "Change the TODO state of an item.
8711 The state of an item is given by a keyword at the start of the heading,
8712 like
8713 *** TODO Write paper
8714 *** DONE Call mom
8716 The different keywords are specified in the variable `org-todo-keywords'.
8717 By default the available states are \"TODO\" and \"DONE\".
8718 So for this example: when the item starts with TODO, it is changed to DONE.
8719 When it starts with DONE, the DONE is removed. And when neither TODO nor
8720 DONE are present, add TODO at the beginning of the heading.
8722 With C-u prefix arg, use completion to determine the new state.
8723 With numeric prefix arg, switch to that state.
8724 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8725 With a tripple C-u prefix, circumvent any state blocking.
8727 For calling through lisp, arg is also interpreted in the following way:
8728 'none -> empty state
8729 \"\"(empty string) -> switch to empty state
8730 'done -> switch to DONE
8731 'nextset -> switch to the next set of keywords
8732 'previousset -> switch to the previous set of keywords
8733 \"WAITING\" -> switch to the specified keyword, but only if it
8734 really is a member of `org-todo-keywords'."
8735 (interactive "P")
8736 (if (equal arg '(16)) (setq arg 'nextset))
8737 (let ((org-blocker-hook org-blocker-hook))
8738 (when (equal arg '(64))
8739 (setq arg nil org-blocker-hook nil))
8740 (save-excursion
8741 (catch 'exit
8742 (org-back-to-heading)
8743 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8744 (or (looking-at (concat " +" org-todo-regexp " *"))
8745 (looking-at " *"))
8746 (let* ((match-data (match-data))
8747 (startpos (point-at-bol))
8748 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8749 (org-log-done org-log-done)
8750 (org-log-repeat org-log-repeat)
8751 (org-todo-log-states org-todo-log-states)
8752 (this (match-string 1))
8753 (hl-pos (match-beginning 0))
8754 (head (org-get-todo-sequence-head this))
8755 (ass (assoc head org-todo-kwd-alist))
8756 (interpret (nth 1 ass))
8757 (done-word (nth 3 ass))
8758 (final-done-word (nth 4 ass))
8759 (last-state (or this ""))
8760 (completion-ignore-case t)
8761 (member (member this org-todo-keywords-1))
8762 (tail (cdr member))
8763 (state (cond
8764 ((and org-todo-key-trigger
8765 (or (and (equal arg '(4))
8766 (eq org-use-fast-todo-selection 'prefix))
8767 (and (not arg) org-use-fast-todo-selection
8768 (not (eq org-use-fast-todo-selection
8769 'prefix)))))
8770 ;; Use fast selection
8771 (org-fast-todo-selection))
8772 ((and (equal arg '(4))
8773 (or (not org-use-fast-todo-selection)
8774 (not org-todo-key-trigger)))
8775 ;; Read a state with completion
8776 (org-ido-completing-read
8777 "State: " (mapcar (lambda(x) (list x))
8778 org-todo-keywords-1)
8779 nil t))
8780 ((eq arg 'right)
8781 (if this
8782 (if tail (car tail) nil)
8783 (car org-todo-keywords-1)))
8784 ((eq arg 'left)
8785 (if (equal member org-todo-keywords-1)
8787 (if this
8788 (nth (- (length org-todo-keywords-1)
8789 (length tail) 2)
8790 org-todo-keywords-1)
8791 (org-last org-todo-keywords-1))))
8792 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8793 (setq arg nil))) ; hack to fall back to cycling
8794 (arg
8795 ;; user or caller requests a specific state
8796 (cond
8797 ((equal arg "") nil)
8798 ((eq arg 'none) nil)
8799 ((eq arg 'done) (or done-word (car org-done-keywords)))
8800 ((eq arg 'nextset)
8801 (or (car (cdr (member head org-todo-heads)))
8802 (car org-todo-heads)))
8803 ((eq arg 'previousset)
8804 (let ((org-todo-heads (reverse org-todo-heads)))
8805 (or (car (cdr (member head org-todo-heads)))
8806 (car org-todo-heads))))
8807 ((car (member arg org-todo-keywords-1)))
8808 ((nth (1- (prefix-numeric-value arg))
8809 org-todo-keywords-1))))
8810 ((null member) (or head (car org-todo-keywords-1)))
8811 ((equal this final-done-word) nil) ;; -> make empty
8812 ((null tail) nil) ;; -> first entry
8813 ((memq interpret '(type priority))
8814 (if (eq this-command last-command)
8815 (car tail)
8816 (if (> (length tail) 0)
8817 (or done-word (car org-done-keywords))
8818 nil)))
8820 (car tail))))
8821 (state (or
8822 (run-hook-with-args-until-success
8823 'org-todo-get-default-hook state last-state)
8824 state))
8825 (next (if state (concat " " state " ") " "))
8826 (change-plist (list :type 'todo-state-change :from this :to state
8827 :position startpos))
8828 dolog now-done-p)
8829 (when org-blocker-hook
8830 (setq org-last-todo-state-is-todo
8831 (not (member this org-done-keywords)))
8832 (unless (save-excursion
8833 (save-match-data
8834 (run-hook-with-args-until-failure
8835 'org-blocker-hook change-plist)))
8836 (if (interactive-p)
8837 (error "TODO state change from %s to %s blocked" this state)
8838 ;; fail silently
8839 (message "TODO state change from %s to %s blocked" this state)
8840 (throw 'exit nil))))
8841 (store-match-data match-data)
8842 (replace-match next t t)
8843 (unless (pos-visible-in-window-p hl-pos)
8844 (message "TODO state changed to %s" (org-trim next)))
8845 (unless head
8846 (setq head (org-get-todo-sequence-head state)
8847 ass (assoc head org-todo-kwd-alist)
8848 interpret (nth 1 ass)
8849 done-word (nth 3 ass)
8850 final-done-word (nth 4 ass)))
8851 (when (memq arg '(nextset previousset))
8852 (message "Keyword-Set %d/%d: %s"
8853 (- (length org-todo-sets) -1
8854 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8855 (length org-todo-sets)
8856 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8857 (setq org-last-todo-state-is-todo
8858 (not (member state org-done-keywords)))
8859 (setq now-done-p (and (member state org-done-keywords)
8860 (not (member this org-done-keywords))))
8861 (and logging (org-local-logging logging))
8862 (when (and (or org-todo-log-states org-log-done)
8863 (not (memq arg '(nextset previousset))))
8864 ;; we need to look at recording a time and note
8865 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8866 (nth 2 (assoc this org-todo-log-states))))
8867 (when (and state
8868 (member state org-not-done-keywords)
8869 (not (member this org-not-done-keywords)))
8870 ;; This is now a todo state and was not one before
8871 ;; If there was a CLOSED time stamp, get rid of it.
8872 (org-add-planning-info nil nil 'closed))
8873 (when (and now-done-p org-log-done)
8874 ;; It is now done, and it was not done before
8875 (org-add-planning-info 'closed (org-current-time))
8876 (if (and (not dolog) (eq 'note org-log-done))
8877 (org-add-log-setup 'done state this 'findpos 'note)))
8878 (when (and state dolog)
8879 ;; This is a non-nil state, and we need to log it
8880 (org-add-log-setup 'state state this 'findpos dolog)))
8881 ;; Fixup tag positioning
8882 (org-todo-trigger-tag-changes state)
8883 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8884 (when org-provide-todo-statistics
8885 (org-update-parent-todo-statistics))
8886 (run-hooks 'org-after-todo-state-change-hook)
8887 (if (and arg (not (member state org-done-keywords)))
8888 (setq head (org-get-todo-sequence-head state)))
8889 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8890 ;; Do we need to trigger a repeat?
8891 (when now-done-p
8892 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8893 ;; This is for the agenda, take a snapshot of the headline.
8894 (save-match-data
8895 (setq org-agenda-headline-snapshot-before-repeat
8896 (org-get-heading))))
8897 (org-auto-repeat-maybe state))
8898 ;; Fixup cursor location if close to the keyword
8899 (if (and (outline-on-heading-p)
8900 (not (bolp))
8901 (save-excursion (beginning-of-line 1)
8902 (looking-at org-todo-line-regexp))
8903 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8904 (progn
8905 (goto-char (or (match-end 2) (match-end 1)))
8906 (just-one-space)))
8907 (when org-trigger-hook
8908 (save-excursion
8909 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8911 (defun org-block-todo-from-children-or-siblings (change-plist)
8912 "Block turning an entry into a TODO, using the hierarchy.
8913 This checks whether the current task should be blocked from state
8914 changes. Such blocking occurs when:
8916 1. The task has children which are not all in a completed state.
8918 2. A task has a parent with the property :ORDERED:, and there
8919 are siblings prior to the current task with incomplete
8920 status."
8921 (catch 'dont-block
8922 ;; If this is not a todo state change, or if this entry is already DONE,
8923 ;; do not block
8924 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8925 (member (plist-get change-plist :from)
8926 (cons 'done org-done-keywords))
8927 (member (plist-get change-plist :to)
8928 (cons 'todo org-not-done-keywords)))
8929 (throw 'dont-block t))
8930 ;; If this task has children, and any are undone, it's blocked
8931 (save-excursion
8932 (org-back-to-heading t)
8933 (let ((this-level (funcall outline-level)))
8934 (outline-next-heading)
8935 (let ((child-level (funcall outline-level)))
8936 (while (and (not (eobp))
8937 (> child-level this-level))
8938 ;; this todo has children, check whether they are all
8939 ;; completed
8940 (if (and (not (org-entry-is-done-p))
8941 (org-entry-is-todo-p))
8942 (throw 'dont-block nil))
8943 (outline-next-heading)
8944 (setq child-level (funcall outline-level))))))
8945 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8946 ;; any previous siblings are undone, it's blocked
8947 (save-excursion
8948 (org-back-to-heading t)
8949 (when (save-excursion
8950 (ignore-errors
8951 (org-up-heading-all 1)
8952 (org-entry-get (point) "ORDERED")))
8953 (let* ((this-level (funcall outline-level))
8954 (current-level this-level))
8955 (while (and (not (bobp))
8956 (>= current-level this-level))
8957 (outline-previous-heading)
8958 (setq current-level (funcall outline-level))
8959 (if (= current-level this-level)
8960 ;; This is a younger sibling, check if it is completed
8961 (if (and (not (org-entry-is-done-p))
8962 (org-entry-is-todo-p))
8963 (throw 'dont-block nil)))))))
8964 t)) ; don't block
8966 (defcustom org-track-ordered-property-with-tag nil
8967 "Should the ORDERED property also be shown as a tag?
8968 The ORDERED property decides if an entry should require subtasks to be
8969 completed in sequence. Since a property is not very visible, setting
8970 this option means that toggling the ORDERED property with the command
8971 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
8972 not relevant for the behavior, but it makes things more visible.
8974 Note that toggling the tag with tags commands will not change the property
8975 and therefore not influence behavior!
8977 This can be t, meaning the tag ORDERED should be used, It can also be a
8978 string to select a different tag for this task."
8979 :group 'org-todo
8980 :type '(choice
8981 (const :tag "No tracking" nil)
8982 (const :tag "Track with ORDERED tag" t)
8983 (string :tag "Use other tag")))
8985 (defun org-toggle-ordered-property ()
8986 "Toggle the ORDERED property of the current entry.
8987 For better visibility, you can track the value of this property with a tag.
8988 See variable `org-track-ordered-property-with-tag'."
8989 (interactive)
8990 (let* ((t1 org-track-ordered-property-with-tag)
8991 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
8992 (save-excursion
8993 (org-back-to-heading)
8994 (if (org-entry-get nil "ORDERED")
8995 (progn
8996 (org-delete-property "ORDERED")
8997 (and tag (org-toggle-tag tag 'off))
8998 (message "Subtasks can be completed in arbitrary order"))
8999 (org-entry-put nil "ORDERED" "t")
9000 (and tag (org-toggle-tag tag 'on))
9001 (message "Subtasks must be completed in sequence")))))
9003 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9004 (defun org-block-todo-from-checkboxes (change-plist)
9005 "Block turning an entry into a TODO, using checkboxes.
9006 This checks whether the current task should be blocked from state
9007 changes because there are uncheckd boxes in this entry."
9008 (catch 'dont-block
9009 ;; If this is not a todo state change, or if this entry is already DONE,
9010 ;; do not block
9011 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9012 (member (plist-get change-plist :from)
9013 (cons 'done org-done-keywords))
9014 (member (plist-get change-plist :to)
9015 (cons 'todo org-not-done-keywords)))
9016 (throw 'dont-block t))
9017 ;; If this task has checkboxes that are not checked, it's blocked
9018 (save-excursion
9019 (org-back-to-heading t)
9020 (let ((beg (point)) end)
9021 (outline-next-heading)
9022 (setq end (point))
9023 (goto-char beg)
9024 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9025 end t)
9026 (progn
9027 (if (boundp 'org-blocked-by-checkboxes)
9028 (setq org-blocked-by-checkboxes t))
9029 (throw 'dont-block nil)))))
9030 t)) ; do not block
9032 (defun org-update-parent-todo-statistics ()
9033 "Update any statistics cookie in the parent of the current headline."
9034 (interactive)
9035 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9036 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9037 (catch 'exit
9038 (save-excursion
9039 (setq level (org-up-heading-safe))
9040 (unless level
9041 (throw 'exit nil))
9042 (while (re-search-forward box-re (point-at-eol) t)
9043 (setq cnt-all 0 cnt-done 0 cookie-present t)
9044 (setq is-percent (match-end 2))
9045 (save-match-data
9046 (unless (outline-next-heading) (throw 'exit nil))
9047 (while (looking-at org-todo-line-regexp)
9048 (setq kwd (match-string 2))
9049 (and kwd (setq cnt-all (1+ cnt-all)))
9050 (and (member kwd org-done-keywords)
9051 (setq cnt-done (1+ cnt-done)))
9052 (condition-case nil
9053 (org-forward-same-level 1)
9054 (error (end-of-line 1)))))
9055 (replace-match
9056 (if is-percent
9057 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9058 (format "[%d/%d]" cnt-done cnt-all))))
9059 (when cookie-present
9060 (run-hook-with-args 'org-after-todo-statistics-hook
9061 cnt-done (- cnt-all cnt-done)))))))
9063 (defvar org-after-todo-statistics-hook nil
9064 "Hook that is called after a TODO statistics cookie has been updated.
9065 Each function is called with two arguments: the number of not-done entries
9066 and the number of done entries.
9068 For example, the following function, when added to this hook, will switch
9069 an entry to DONE when all children are done, and back to TODO when new
9070 entries are set to a TODO status. Note that this hook is only called
9071 when there is a statistics cookie in the headline!
9073 (defun org-summary-todo (n-done n-not-done)
9074 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9075 (let (org-log-done org-log-states) ; turn off logging
9076 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9079 (defun org-todo-trigger-tag-changes (state)
9080 "Apply the changes defined in `org-todo-state-tags-triggers'."
9081 (let ((l org-todo-state-tags-triggers)
9082 changes)
9083 (when (or (not state) (equal state ""))
9084 (setq changes (append changes (cdr (assoc "" l)))))
9085 (when (and (stringp state) (> (length state) 0))
9086 (setq changes (append changes (cdr (assoc state l)))))
9087 (when (member state org-not-done-keywords)
9088 (setq changes (append changes (cdr (assoc 'todo l)))))
9089 (when (member state org-done-keywords)
9090 (setq changes (append changes (cdr (assoc 'done l)))))
9091 (dolist (c changes)
9092 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9094 (defun org-local-logging (value)
9095 "Get logging settings from a property VALUE."
9096 (let* (words w a)
9097 ;; directly set the variables, they are already local.
9098 (setq org-log-done nil
9099 org-log-repeat nil
9100 org-todo-log-states nil)
9101 (setq words (org-split-string value))
9102 (while (setq w (pop words))
9103 (cond
9104 ((setq a (assoc w org-startup-options))
9105 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9106 (set (nth 1 a) (nth 2 a))))
9107 ((setq a (org-extract-log-state-settings w))
9108 (and (member (car a) org-todo-keywords-1)
9109 (push a org-todo-log-states)))))))
9111 (defun org-get-todo-sequence-head (kwd)
9112 "Return the head of the TODO sequence to which KWD belongs.
9113 If KWD is not set, check if there is a text property remembering the
9114 right sequence."
9115 (let (p)
9116 (cond
9117 ((not kwd)
9118 (or (get-text-property (point-at-bol) 'org-todo-head)
9119 (progn
9120 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9121 nil (point-at-eol)))
9122 (get-text-property p 'org-todo-head))))
9123 ((not (member kwd org-todo-keywords-1))
9124 (car org-todo-keywords-1))
9125 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9127 (defun org-fast-todo-selection ()
9128 "Fast TODO keyword selection with single keys.
9129 Returns the new TODO keyword, or nil if no state change should occur."
9130 (let* ((fulltable org-todo-key-alist)
9131 (done-keywords org-done-keywords) ;; needed for the faces.
9132 (maxlen (apply 'max (mapcar
9133 (lambda (x)
9134 (if (stringp (car x)) (string-width (car x)) 0))
9135 fulltable)))
9136 (expert nil)
9137 (fwidth (+ maxlen 3 1 3))
9138 (ncol (/ (- (window-width) 4) fwidth))
9139 tg cnt e c tbl
9140 groups ingroup)
9141 (save-excursion
9142 (save-window-excursion
9143 (if expert
9144 (set-buffer (get-buffer-create " *Org todo*"))
9145 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9146 (erase-buffer)
9147 (org-set-local 'org-done-keywords done-keywords)
9148 (setq tbl fulltable cnt 0)
9149 (while (setq e (pop tbl))
9150 (cond
9151 ((equal e '(:startgroup))
9152 (push '() groups) (setq ingroup t)
9153 (when (not (= cnt 0))
9154 (setq cnt 0)
9155 (insert "\n"))
9156 (insert "{ "))
9157 ((equal e '(:endgroup))
9158 (setq ingroup nil cnt 0)
9159 (insert "}\n"))
9160 ((equal e '(:newline))
9161 (when (not (= cnt 0))
9162 (setq cnt 0)
9163 (insert "\n")
9164 (setq e (car tbl))
9165 (while (equal (car tbl) '(:newline))
9166 (insert "\n")
9167 (setq tbl (cdr tbl)))))
9169 (setq tg (car e) c (cdr e))
9170 (if ingroup (push tg (car groups)))
9171 (setq tg (org-add-props tg nil 'face
9172 (org-get-todo-face tg)))
9173 (if (and (= cnt 0) (not ingroup)) (insert " "))
9174 (insert "[" c "] " tg (make-string
9175 (- fwidth 4 (length tg)) ?\ ))
9176 (when (= (setq cnt (1+ cnt)) ncol)
9177 (insert "\n")
9178 (if ingroup (insert " "))
9179 (setq cnt 0)))))
9180 (insert "\n")
9181 (goto-char (point-min))
9182 (if (not expert) (org-fit-window-to-buffer))
9183 (message "[a-z..]:Set [SPC]:clear")
9184 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9185 (cond
9186 ((or (= c ?\C-g)
9187 (and (= c ?q) (not (rassoc c fulltable))))
9188 (setq quit-flag t))
9189 ((= c ?\ ) nil)
9190 ((setq e (rassoc c fulltable) tg (car e))
9192 (t (setq quit-flag t)))))))
9194 (defun org-entry-is-todo-p ()
9195 (member (org-get-todo-state) org-not-done-keywords))
9197 (defun org-entry-is-done-p ()
9198 (member (org-get-todo-state) org-done-keywords))
9200 (defun org-get-todo-state ()
9201 (save-excursion
9202 (org-back-to-heading t)
9203 (and (looking-at org-todo-line-regexp)
9204 (match-end 2)
9205 (match-string 2))))
9207 (defun org-at-date-range-p (&optional inactive-ok)
9208 "Is the cursor inside a date range?"
9209 (interactive)
9210 (save-excursion
9211 (catch 'exit
9212 (let ((pos (point)))
9213 (skip-chars-backward "^[<\r\n")
9214 (skip-chars-backward "<[")
9215 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9216 (>= (match-end 0) pos)
9217 (throw 'exit t))
9218 (skip-chars-backward "^<[\r\n")
9219 (skip-chars-backward "<[")
9220 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9221 (>= (match-end 0) pos)
9222 (throw 'exit t)))
9223 nil)))
9225 (defun org-get-repeat ()
9226 "Check if there is a deadline/schedule with repeater in this entry."
9227 (save-match-data
9228 (save-excursion
9229 (org-back-to-heading t)
9230 (if (re-search-forward
9231 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9232 (match-string 1)))))
9234 (defvar org-last-changed-timestamp)
9235 (defvar org-last-inserted-timestamp)
9236 (defvar org-log-post-message)
9237 (defvar org-log-note-purpose)
9238 (defvar org-log-note-how)
9239 (defvar org-log-note-extra)
9240 (defun org-auto-repeat-maybe (done-word)
9241 "Check if the current headline contains a repeated deadline/schedule.
9242 If yes, set TODO state back to what it was and change the base date
9243 of repeating deadline/scheduled time stamps to new date.
9244 This function is run automatically after each state change to a DONE state."
9245 ;; last-state is dynamically scoped into this function
9246 (let* ((repeat (org-get-repeat))
9247 (aa (assoc last-state org-todo-kwd-alist))
9248 (interpret (nth 1 aa))
9249 (head (nth 2 aa))
9250 (whata '(("d" . day) ("m" . month) ("y" . year)))
9251 (msg "Entry repeats: ")
9252 (org-log-done nil)
9253 (org-todo-log-states nil)
9254 (nshiftmax 10) (nshift 0)
9255 re type n what ts time)
9256 (when repeat
9257 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9258 (org-todo (if (eq interpret 'type) last-state head))
9259 (when org-log-repeat
9260 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9261 (memq 'org-add-log-note post-command-hook))
9262 ;; OK, we are already setup for some record
9263 (if (eq org-log-repeat 'note)
9264 ;; make sure we take a note, not only a time stamp
9265 (setq org-log-note-how 'note))
9266 ;; Set up for taking a record
9267 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9268 last-state
9269 'findpos org-log-repeat)))
9270 (org-back-to-heading t)
9271 (org-add-planning-info nil nil 'closed)
9272 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9273 org-deadline-time-regexp "\\)\\|\\("
9274 org-ts-regexp "\\)"))
9275 (while (re-search-forward
9276 re (save-excursion (outline-next-heading) (point)) t)
9277 (setq type (if (match-end 1) org-scheduled-string
9278 (if (match-end 3) org-deadline-string "Plain:"))
9279 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9280 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9281 (setq n (string-to-number (match-string 2 ts))
9282 what (match-string 3 ts))
9283 (if (equal what "w") (setq n (* n 7) what "d"))
9284 ;; Preparation, see if we need to modify the start date for the change
9285 (when (match-end 1)
9286 (setq time (save-match-data (org-time-string-to-time ts)))
9287 (cond
9288 ((equal (match-string 1 ts) ".")
9289 ;; Shift starting date to today
9290 (org-timestamp-change
9291 (- (time-to-days (current-time)) (time-to-days time))
9292 'day))
9293 ((equal (match-string 1 ts) "+")
9294 (while (or (= nshift 0)
9295 (<= (time-to-days time) (time-to-days (current-time))))
9296 (when (= (incf nshift) nshiftmax)
9297 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9298 (error "Abort")))
9299 (org-timestamp-change n (cdr (assoc what whata)))
9300 (org-at-timestamp-p t)
9301 (setq ts (match-string 1))
9302 (setq time (save-match-data (org-time-string-to-time ts))))
9303 (org-timestamp-change (- n) (cdr (assoc what whata)))
9304 ;; rematch, so that we have everything in place for the real shift
9305 (org-at-timestamp-p t)
9306 (setq ts (match-string 1))
9307 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9308 (org-timestamp-change n (cdr (assoc what whata)))
9309 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9310 (setq org-log-post-message msg)
9311 (message "%s" msg))))
9313 (defun org-show-todo-tree (arg)
9314 "Make a compact tree which shows all headlines marked with TODO.
9315 The tree will show the lines where the regexp matches, and all higher
9316 headlines above the match.
9317 With a \\[universal-argument] prefix, also show the DONE entries.
9318 With a numeric prefix N, construct a sparse tree for the Nth element
9319 of `org-todo-keywords-1'."
9320 (interactive "P")
9321 (let ((case-fold-search nil)
9322 (kwd-re
9323 (cond ((null arg) org-not-done-regexp)
9324 ((equal arg '(4))
9325 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9326 (mapcar 'list org-todo-keywords-1))))
9327 (concat "\\("
9328 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9329 "\\)\\>")))
9330 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9331 (regexp-quote (nth (1- (prefix-numeric-value arg))
9332 org-todo-keywords-1)))
9333 (t (error "Invalid prefix argument: %s" arg)))))
9334 (message "%d TODO entries found"
9335 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9337 (defun org-deadline (&optional remove time)
9338 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9339 With argument REMOVE, remove any deadline from the item.
9340 When TIME is set, it should be an internal time specification, and the
9341 scheduling will use the corresponding date."
9342 (interactive "P")
9343 (if remove
9344 (progn
9345 (org-remove-timestamp-with-keyword org-deadline-string)
9346 (message "Item no longer has a deadline."))
9347 (if (org-get-repeat)
9348 (error "Cannot change deadline on task with repeater, please do that by hand")
9349 (org-add-planning-info 'deadline time 'closed)
9350 (message "Deadline on %s" org-last-inserted-timestamp))))
9352 (defun org-schedule (&optional remove time)
9353 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9354 With argument REMOVE, remove any scheduling date from the item.
9355 When TIME is set, it should be an internal time specification, and the
9356 scheduling will use the corresponding date."
9357 (interactive "P")
9358 (if remove
9359 (progn
9360 (org-remove-timestamp-with-keyword org-scheduled-string)
9361 (message "Item is no longer scheduled."))
9362 (if (org-get-repeat)
9363 (error "Cannot reschedule task with repeater, please do that by hand")
9364 (org-add-planning-info 'scheduled time 'closed)
9365 (message "Scheduled to %s" org-last-inserted-timestamp))))
9367 (defun org-get-scheduled-time (pom &optional inherit)
9368 "Get the scheduled time as a time tuple, of a format suitable
9369 for calling org-schedule with, or if there is no scheduling,
9370 returns nil."
9371 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9372 (when time
9373 (apply 'encode-time (org-parse-time-string time)))))
9375 (defun org-get-deadline-time (pom &optional inherit)
9376 "Get the deadine as a time tuple, of a format suitable for
9377 calling org-deadlin with, or if there is no scheduling, returns
9378 nil."
9379 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9380 (when time
9381 (apply 'encode-time (org-parse-time-string time)))))
9383 (defun org-remove-timestamp-with-keyword (keyword)
9384 "Remove all time stamps with KEYWORD in the current entry."
9385 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9386 beg)
9387 (save-excursion
9388 (org-back-to-heading t)
9389 (setq beg (point))
9390 (org-end-of-subtree t t)
9391 (while (re-search-backward re beg t)
9392 (replace-match "")
9393 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9394 (equal (char-before) ?\ ))
9395 (backward-delete-char 1)
9396 (if (string-match "^[ \t]*$" (buffer-substring
9397 (point-at-bol) (point-at-eol)))
9398 (delete-region (point-at-bol)
9399 (min (point-max) (1+ (point-at-eol))))))))))
9401 (defun org-add-planning-info (what &optional time &rest remove)
9402 "Insert new timestamp with keyword in the line directly after the headline.
9403 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9404 If non is given, the user is prompted for a date.
9405 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9406 be removed."
9407 (interactive)
9408 (let (org-time-was-given org-end-time-was-given ts
9409 end default-time default-input)
9411 (catch 'exit
9412 (when (and (not time) (memq what '(scheduled deadline)))
9413 ;; Try to get a default date/time from existing timestamp
9414 (save-excursion
9415 (org-back-to-heading t)
9416 (setq end (save-excursion (outline-next-heading) (point)))
9417 (when (re-search-forward (if (eq what 'scheduled)
9418 org-scheduled-time-regexp
9419 org-deadline-time-regexp)
9420 end t)
9421 (setq ts (match-string 1)
9422 default-time
9423 (apply 'encode-time (org-parse-time-string ts))
9424 default-input (and ts (org-get-compact-tod ts))))))
9425 (when what
9426 ;; If necessary, get the time from the user
9427 (setq time (or time (org-read-date nil 'to-time nil nil
9428 default-time default-input))))
9430 (when (and org-insert-labeled-timestamps-at-point
9431 (member what '(scheduled deadline)))
9432 (insert
9433 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9434 (org-insert-time-stamp time org-time-was-given
9435 nil nil nil (list org-end-time-was-given))
9436 (setq what nil))
9437 (save-excursion
9438 (save-restriction
9439 (let (col list elt ts buffer-invisibility-spec)
9440 (org-back-to-heading t)
9441 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9442 (goto-char (match-end 1))
9443 (setq col (current-column))
9444 (goto-char (match-end 0))
9445 (if (eobp) (insert "\n") (forward-char 1))
9446 (when (and (not what)
9447 (not (looking-at
9448 (concat "[ \t]*"
9449 org-keyword-time-not-clock-regexp))))
9450 ;; Nothing to add, nothing to remove...... :-)
9451 (throw 'exit nil))
9452 (if (and (not (looking-at outline-regexp))
9453 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9454 "[^\r\n]*"))
9455 (not (equal (match-string 1) org-clock-string)))
9456 (narrow-to-region (match-beginning 0) (match-end 0))
9457 (insert-before-markers "\n")
9458 (backward-char 1)
9459 (narrow-to-region (point) (point))
9460 (and org-adapt-indentation (org-indent-to-column col)))
9461 ;; Check if we have to remove something.
9462 (setq list (cons what remove))
9463 (while list
9464 (setq elt (pop list))
9465 (goto-char (point-min))
9466 (when (or (and (eq elt 'scheduled)
9467 (re-search-forward org-scheduled-time-regexp nil t))
9468 (and (eq elt 'deadline)
9469 (re-search-forward org-deadline-time-regexp nil t))
9470 (and (eq elt 'closed)
9471 (re-search-forward org-closed-time-regexp nil t)))
9472 (replace-match "")
9473 (if (looking-at "--+<[^>]+>") (replace-match ""))
9474 (if (looking-at " +") (replace-match ""))))
9475 (goto-char (point-max))
9476 (when what
9477 (insert
9478 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9479 (cond ((eq what 'scheduled) org-scheduled-string)
9480 ((eq what 'deadline) org-deadline-string)
9481 ((eq what 'closed) org-closed-string))
9482 " ")
9483 (setq ts (org-insert-time-stamp
9484 time
9485 (or org-time-was-given
9486 (and (eq what 'closed) org-log-done-with-time))
9487 (eq what 'closed)
9488 nil nil (list org-end-time-was-given)))
9489 (end-of-line 1))
9490 (goto-char (point-min))
9491 (widen)
9492 (if (and (looking-at "[ \t]+\n")
9493 (equal (char-before) ?\n))
9494 (delete-region (1- (point)) (point-at-eol)))
9495 ts))))))
9497 (defvar org-log-note-marker (make-marker))
9498 (defvar org-log-note-purpose nil)
9499 (defvar org-log-note-state nil)
9500 (defvar org-log-note-previous-state nil)
9501 (defvar org-log-note-how nil)
9502 (defvar org-log-note-extra nil)
9503 (defvar org-log-note-window-configuration nil)
9504 (defvar org-log-note-return-to (make-marker))
9505 (defvar org-log-post-message nil
9506 "Message to be displayed after a log note has been stored.
9507 The auto-repeater uses this.")
9509 (defun org-add-note ()
9510 "Add a note to the current entry.
9511 This is done in the same way as adding a state change note."
9512 (interactive)
9513 (org-add-log-setup 'note nil nil 'findpos nil))
9515 (defvar org-property-end-re)
9516 (defun org-add-log-setup (&optional purpose state prev-state
9517 findpos how &optional extra)
9518 "Set up the post command hook to take a note.
9519 If this is about to TODO state change, the new state is expected in STATE.
9520 When FINDPOS is non-nil, find the correct position for the note in
9521 the current entry. If not, assume that it can be inserted at point.
9522 HOW is an indicator what kind of note should be created.
9523 EXTRA is additional text that will be inserted into the notes buffer."
9524 (let ((drawer (cond ((stringp org-log-into-drawer)
9525 org-log-into-drawer)
9526 (org-log-into-drawer "LOGBOOK")
9527 (t nil))))
9528 (save-restriction
9529 (save-excursion
9530 (when findpos
9531 (org-back-to-heading t)
9532 (narrow-to-region (point) (save-excursion
9533 (outline-next-heading) (point)))
9534 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9535 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9536 "[^\r\n]*\\)?"))
9537 (goto-char (match-end 0))
9538 (cond
9539 (drawer
9540 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9541 nil t)
9542 (progn
9543 (goto-char (match-end 0))
9544 (or org-log-states-order-reversed
9545 (and (re-search-forward org-property-end-re nil t)
9546 (goto-char (1- (match-beginning 0))))))
9547 (insert "\n:" drawer ":\n:END:")
9548 (beginning-of-line 0)
9549 (org-indent-line-function)
9550 (beginning-of-line 2)
9551 (org-indent-line-function)
9552 (end-of-line 0)))
9553 ((and org-log-state-notes-insert-after-drawers
9554 (save-excursion
9555 (forward-line) (looking-at org-drawer-regexp)))
9556 (forward-line)
9557 (while (looking-at org-drawer-regexp)
9558 (goto-char (match-end 0))
9559 (re-search-forward org-property-end-re (point-max) t)
9560 (forward-line))
9561 (forward-line -1)))
9562 (unless org-log-states-order-reversed
9563 (and (= (char-after) ?\n) (forward-char 1))
9564 (org-skip-over-state-notes)
9565 (skip-chars-backward " \t\n\r")))
9566 (move-marker org-log-note-marker (point))
9567 (setq org-log-note-purpose purpose
9568 org-log-note-state state
9569 org-log-note-previous-state prev-state
9570 org-log-note-how how
9571 org-log-note-extra extra)
9572 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9574 (defun org-skip-over-state-notes ()
9575 "Skip past the list of State notes in an entry."
9576 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9577 (while (looking-at "[ \t]*- State")
9578 (condition-case nil
9579 (org-next-item)
9580 (error (org-end-of-item)))))
9582 (defun org-add-log-note (&optional purpose)
9583 "Pop up a window for taking a note, and add this note later at point."
9584 (remove-hook 'post-command-hook 'org-add-log-note)
9585 (setq org-log-note-window-configuration (current-window-configuration))
9586 (delete-other-windows)
9587 (move-marker org-log-note-return-to (point))
9588 (switch-to-buffer (marker-buffer org-log-note-marker))
9589 (goto-char org-log-note-marker)
9590 (org-switch-to-buffer-other-window "*Org Note*")
9591 (erase-buffer)
9592 (if (memq org-log-note-how '(time state))
9593 (let (current-prefix-arg) (org-store-log-note))
9594 (let ((org-inhibit-startup t)) (org-mode))
9595 (insert (format "# Insert note for %s.
9596 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9597 (cond
9598 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9599 ((eq org-log-note-purpose 'done) "closed todo item")
9600 ((eq org-log-note-purpose 'state)
9601 (format "state change from \"%s\" to \"%s\""
9602 (or org-log-note-previous-state "")
9603 (or org-log-note-state "")))
9604 ((eq org-log-note-purpose 'note)
9605 "this entry")
9606 (t (error "This should not happen")))))
9607 (if org-log-note-extra (insert org-log-note-extra))
9608 (org-set-local 'org-finish-function 'org-store-log-note)))
9610 (defvar org-note-abort nil) ; dynamically scoped
9611 (defun org-store-log-note ()
9612 "Finish taking a log note, and insert it to where it belongs."
9613 (let ((txt (buffer-string))
9614 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9615 lines ind)
9616 (kill-buffer (current-buffer))
9617 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9618 (setq txt (replace-match "" t t txt)))
9619 (if (string-match "\\s-+\\'" txt)
9620 (setq txt (replace-match "" t t txt)))
9621 (setq lines (org-split-string txt "\n"))
9622 (when (and note (string-match "\\S-" note))
9623 (setq note
9624 (org-replace-escapes
9625 note
9626 (list (cons "%u" (user-login-name))
9627 (cons "%U" user-full-name)
9628 (cons "%t" (format-time-string
9629 (org-time-stamp-format 'long 'inactive)
9630 (current-time)))
9631 (cons "%s" (if org-log-note-state
9632 (concat "\"" org-log-note-state "\"")
9633 ""))
9634 (cons "%S" (if org-log-note-previous-state
9635 (concat "\"" org-log-note-previous-state "\"")
9636 "\"\"")))))
9637 (if lines (setq note (concat note " \\\\")))
9638 (push note lines))
9639 (when (or current-prefix-arg org-note-abort)
9640 (when org-log-into-drawer
9641 (org-remove-empty-drawer-at
9642 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
9643 org-log-note-marker))
9644 (setq lines nil))
9645 (when lines
9646 (save-excursion
9647 (set-buffer (marker-buffer org-log-note-marker))
9648 (save-excursion
9649 (goto-char org-log-note-marker)
9650 (move-marker org-log-note-marker nil)
9651 (end-of-line 1)
9652 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9653 (insert "- " (pop lines))
9654 (org-indent-line-function)
9655 (beginning-of-line 1)
9656 (looking-at "[ \t]*")
9657 (setq ind (concat (match-string 0) " "))
9658 (end-of-line 1)
9659 (while lines (insert "\n" ind (pop lines)))
9660 (message "Note stored")
9661 (org-back-to-heading t)
9662 (org-cycle-hide-drawers 'children)))))
9663 (set-window-configuration org-log-note-window-configuration)
9664 (with-current-buffer (marker-buffer org-log-note-return-to)
9665 (goto-char org-log-note-return-to))
9666 (move-marker org-log-note-return-to nil)
9667 (and org-log-post-message (message "%s" org-log-post-message)))
9669 (defun org-remove-empty-drawer-at (drawer pos)
9670 "Remove an emptyr DARWER drawer at position POS.
9671 POS may also be a marker."
9672 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
9673 (save-excursion
9674 (save-restriction
9675 (widen)
9676 (goto-char pos)
9677 (if (org-in-regexp
9678 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
9679 (replace-match ""))))))
9681 (defun org-sparse-tree (&optional arg)
9682 "Create a sparse tree, prompt for the details.
9683 This command can create sparse trees. You first need to select the type
9684 of match used to create the tree:
9686 t Show entries with a specific TODO keyword.
9687 m Show entries selected by a tags/property match.
9688 p Enter a property name and its value (both with completion on existing
9689 names/values) and show entries with that property.
9690 r Show entries matching a regular expression.
9691 d Show deadlines due within `org-deadline-warning-days'.
9692 b Show deadlines and scheduled items before a date.
9693 a Show deadlines and scheduled items after a date."
9694 (interactive "P")
9695 (let (ans kwd value)
9696 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
9697 (setq ans (read-char-exclusive))
9698 (cond
9699 ((equal ans ?d)
9700 (call-interactively 'org-check-deadlines))
9701 ((equal ans ?b)
9702 (call-interactively 'org-check-before-date))
9703 ((equal ans ?a)
9704 (call-interactively 'org-check-after-date))
9705 ((equal ans ?t)
9706 (org-show-todo-tree '(4)))
9707 ((member ans '(?T ?m))
9708 (call-interactively 'org-match-sparse-tree))
9709 ((member ans '(?p ?P))
9710 (setq kwd (org-ido-completing-read "Property: "
9711 (mapcar 'list (org-buffer-property-keys))))
9712 (setq value (org-ido-completing-read "Value: "
9713 (mapcar 'list (org-property-values kwd))))
9714 (unless (string-match "\\`{.*}\\'" value)
9715 (setq value (concat "\"" value "\"")))
9716 (org-match-sparse-tree arg (concat kwd "=" value)))
9717 ((member ans '(?r ?R ?/))
9718 (call-interactively 'org-occur))
9719 (t (error "No such sparse tree command \"%c\"" ans)))))
9721 (defvar org-occur-highlights nil
9722 "List of overlays used for occur matches.")
9723 (make-variable-buffer-local 'org-occur-highlights)
9724 (defvar org-occur-parameters nil
9725 "Parameters of the active org-occur calls.
9726 This is a list, each call to org-occur pushes as cons cell,
9727 containing the regular expression and the callback, onto the list.
9728 The list can contain several entries if `org-occur' has been called
9729 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9730 will only contain one set of parameters. When the highlights are
9731 removed (for example with `C-c C-c', or with the next edit (depending
9732 on `org-remove-highlights-with-change'), this variable is emptied
9733 as well.")
9734 (make-variable-buffer-local 'org-occur-parameters)
9736 (defun org-occur (regexp &optional keep-previous callback)
9737 "Make a compact tree which shows all matches of REGEXP.
9738 The tree will show the lines where the regexp matches, and all higher
9739 headlines above the match. It will also show the heading after the match,
9740 to make sure editing the matching entry is easy.
9741 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9742 call to `org-occur' will be kept, to allow stacking of calls to this
9743 command.
9744 If CALLBACK is non-nil, it is a function which is called to confirm
9745 that the match should indeed be shown."
9746 (interactive "sRegexp: \nP")
9747 (unless keep-previous
9748 (org-remove-occur-highlights nil nil t))
9749 (push (cons regexp callback) org-occur-parameters)
9750 (let ((cnt 0))
9751 (save-excursion
9752 (goto-char (point-min))
9753 (if (or (not keep-previous) ; do not want to keep
9754 (not org-occur-highlights)) ; no previous matches
9755 ;; hide everything
9756 (org-overview))
9757 (while (re-search-forward regexp nil t)
9758 (when (or (not callback)
9759 (save-match-data (funcall callback)))
9760 (setq cnt (1+ cnt))
9761 (when org-highlight-sparse-tree-matches
9762 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9763 (org-show-context 'occur-tree))))
9764 (when org-remove-highlights-with-change
9765 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9766 nil 'local))
9767 (unless org-sparse-tree-open-archived-trees
9768 (org-hide-archived-subtrees (point-min) (point-max)))
9769 (run-hooks 'org-occur-hook)
9770 (if (interactive-p)
9771 (message "%d match(es) for regexp %s" cnt regexp))
9772 cnt))
9774 (defun org-show-context (&optional key)
9775 "Make sure point and context and visible.
9776 How much context is shown depends upon the variables
9777 `org-show-hierarchy-above', `org-show-following-heading'. and
9778 `org-show-siblings'."
9779 (let ((heading-p (org-on-heading-p t))
9780 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9781 (following-p (org-get-alist-option org-show-following-heading key))
9782 (entry-p (org-get-alist-option org-show-entry-below key))
9783 (siblings-p (org-get-alist-option org-show-siblings key)))
9784 (catch 'exit
9785 ;; Show heading or entry text
9786 (if (and heading-p (not entry-p))
9787 (org-flag-heading nil) ; only show the heading
9788 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9789 (org-show-hidden-entry))) ; show entire entry
9790 (when following-p
9791 ;; Show next sibling, or heading below text
9792 (save-excursion
9793 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9794 (org-flag-heading nil))))
9795 (when siblings-p (org-show-siblings))
9796 (when hierarchy-p
9797 ;; show all higher headings, possibly with siblings
9798 (save-excursion
9799 (while (and (condition-case nil
9800 (progn (org-up-heading-all 1) t)
9801 (error nil))
9802 (not (bobp)))
9803 (org-flag-heading nil)
9804 (when siblings-p (org-show-siblings))))))))
9806 (defun org-reveal (&optional siblings)
9807 "Show current entry, hierarchy above it, and the following headline.
9808 This can be used to show a consistent set of context around locations
9809 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9810 not t for the search context.
9812 With optional argument SIBLINGS, on each level of the hierarchy all
9813 siblings are shown. This repairs the tree structure to what it would
9814 look like when opened with hierarchical calls to `org-cycle'."
9815 (interactive "P")
9816 (let ((org-show-hierarchy-above t)
9817 (org-show-following-heading t)
9818 (org-show-siblings (if siblings t org-show-siblings)))
9819 (org-show-context nil)))
9821 (defun org-highlight-new-match (beg end)
9822 "Highlight from BEG to END and mark the highlight is an occur headline."
9823 (let ((ov (org-make-overlay beg end)))
9824 (org-overlay-put ov 'face 'secondary-selection)
9825 (push ov org-occur-highlights)))
9827 (defun org-remove-occur-highlights (&optional beg end noremove)
9828 "Remove the occur highlights from the buffer.
9829 BEG and END are ignored. If NOREMOVE is nil, remove this function
9830 from the `before-change-functions' in the current buffer."
9831 (interactive)
9832 (unless org-inhibit-highlight-removal
9833 (mapc 'org-delete-overlay org-occur-highlights)
9834 (setq org-occur-highlights nil)
9835 (setq org-occur-parameters nil)
9836 (unless noremove
9837 (remove-hook 'before-change-functions
9838 'org-remove-occur-highlights 'local))))
9840 ;;;; Priorities
9842 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9843 "Regular expression matching the priority indicator.")
9845 (defvar org-remove-priority-next-time nil)
9847 (defun org-priority-up ()
9848 "Increase the priority of the current item."
9849 (interactive)
9850 (org-priority 'up))
9852 (defun org-priority-down ()
9853 "Decrease the priority of the current item."
9854 (interactive)
9855 (org-priority 'down))
9857 (defun org-priority (&optional action)
9858 "Change the priority of an item by ARG.
9859 ACTION can be `set', `up', `down', or a character."
9860 (interactive)
9861 (setq action (or action 'set))
9862 (let (current new news have remove)
9863 (save-excursion
9864 (org-back-to-heading t)
9865 (if (looking-at org-priority-regexp)
9866 (setq current (string-to-char (match-string 2))
9867 have t)
9868 (setq current org-default-priority))
9869 (cond
9870 ((or (eq action 'set)
9871 (if (featurep 'xemacs) (characterp action) (integerp action)))
9872 (if (not (eq action 'set))
9873 (setq new action)
9874 (message "Priority %c-%c, SPC to remove: "
9875 org-highest-priority org-lowest-priority)
9876 (setq new (read-char-exclusive)))
9877 (if (and (= (upcase org-highest-priority) org-highest-priority)
9878 (= (upcase org-lowest-priority) org-lowest-priority))
9879 (setq new (upcase new)))
9880 (cond ((equal new ?\ ) (setq remove t))
9881 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9882 (error "Priority must be between `%c' and `%c'"
9883 org-highest-priority org-lowest-priority))))
9884 ((eq action 'up)
9885 (if (and (not have) (eq last-command this-command))
9886 (setq new org-lowest-priority)
9887 (setq new (if (and org-priority-start-cycle-with-default (not have))
9888 org-default-priority (1- current)))))
9889 ((eq action 'down)
9890 (if (and (not have) (eq last-command this-command))
9891 (setq new org-highest-priority)
9892 (setq new (if (and org-priority-start-cycle-with-default (not have))
9893 org-default-priority (1+ current)))))
9894 (t (error "Invalid action")))
9895 (if (or (< (upcase new) org-highest-priority)
9896 (> (upcase new) org-lowest-priority))
9897 (setq remove t))
9898 (setq news (format "%c" new))
9899 (if have
9900 (if remove
9901 (replace-match "" t t nil 1)
9902 (replace-match news t t nil 2))
9903 (if remove
9904 (error "No priority cookie found in line")
9905 (looking-at org-todo-line-regexp)
9906 (if (match-end 2)
9907 (progn
9908 (goto-char (match-end 2))
9909 (insert " [#" news "]"))
9910 (goto-char (match-beginning 3))
9911 (insert "[#" news "] ")))))
9912 (org-preserve-lc (org-set-tags nil 'align))
9913 (if remove
9914 (message "Priority removed")
9915 (message "Priority of current item set to %s" news))))
9918 (defun org-get-priority (s)
9919 "Find priority cookie and return priority."
9920 (save-match-data
9921 (if (not (string-match org-priority-regexp s))
9922 (* 1000 (- org-lowest-priority org-default-priority))
9923 (* 1000 (- org-lowest-priority
9924 (string-to-char (match-string 2 s)))))))
9926 ;;;; Tags
9928 (defvar org-agenda-archives-mode)
9929 (defvar org-scanner-tags nil
9930 "The current tag list while the tags scanner is running.")
9931 (defvar org-trust-scanner-tags nil
9932 "Should `org-get-tags-at' use the tags fro the scanner.
9933 This is for internal dynamical scoping only.
9934 When this is non-nil, the function `org-get-tags-at' will return the value
9935 of `org-scanner-tags' instead of building the list by itself. This
9936 can lead to large speed-ups when the tags scanner is used in a file with
9937 many entries, and when the list of tags is retrieved, for example to
9938 obtain a list of properties. Building the tags list for each entry in such
9939 a file becomes an N^2 operation - but with this variable set, it scales
9940 as N.")
9942 (defun org-scan-tags (action matcher &optional todo-only)
9943 "Scan headline tags with inheritance and produce output ACTION.
9945 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9946 or `agenda' to produce an entry list for an agenda view. It can also be
9947 a Lisp form or a function that should be called at each matched headline, in
9948 this case the return value is a list of all return values from these calls.
9950 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9951 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9952 only lines with a TODO keyword are included in the output."
9953 (require 'org-agenda)
9954 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
9955 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9956 (org-re
9957 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9958 (props (list 'face 'default
9959 'done-face 'org-agenda-done
9960 'undone-face 'default
9961 'mouse-face 'highlight
9962 'org-not-done-regexp org-not-done-regexp
9963 'org-todo-regexp org-todo-regexp
9964 'keymap org-agenda-keymap
9965 'help-echo
9966 (format "mouse-2 or RET jump to org file %s"
9967 (abbreviate-file-name
9968 (or (buffer-file-name (buffer-base-buffer))
9969 (buffer-name (buffer-base-buffer)))))))
9970 (case-fold-search nil)
9971 lspos tags tags-list
9972 (tags-alist (list (cons 0 org-file-tags)))
9973 (llast 0) rtn rtn1 level category i txt
9974 todo marker entry priority)
9975 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9976 (setq action (list 'lambda nil action)))
9977 (save-excursion
9978 (goto-char (point-min))
9979 (when (eq action 'sparse-tree)
9980 (org-overview)
9981 (org-remove-occur-highlights))
9982 (while (re-search-forward re nil t)
9983 (catch :skip
9984 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
9985 tags (if (match-end 4) (org-match-string-no-properties 4)))
9986 (goto-char (setq lspos (match-beginning 0)))
9987 (setq level (org-reduced-level (funcall outline-level))
9988 category (org-get-category))
9989 (setq i llast llast level)
9990 ;; remove tag lists from same and sublevels
9991 (while (>= i level)
9992 (when (setq entry (assoc i tags-alist))
9993 (setq tags-alist (delete entry tags-alist)))
9994 (setq i (1- i)))
9995 ;; add the next tags
9996 (when tags
9997 (setq tags (org-split-string tags ":")
9998 tags-alist
9999 (cons (cons level tags) tags-alist)))
10000 ;; compile tags for current headline
10001 (setq tags-list
10002 (if org-use-tag-inheritance
10003 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10004 tags)
10005 org-scanner-tags tags-list)
10006 (when org-use-tag-inheritance
10007 (setcdr (car tags-alist)
10008 (mapcar (lambda (x)
10009 (setq x (copy-sequence x))
10010 (org-add-prop-inherited x))
10011 (cdar tags-alist))))
10012 (when (and tags org-use-tag-inheritance
10013 (or (not (eq t org-use-tag-inheritance))
10014 org-tags-exclude-from-inheritance))
10015 ;; selective inheritance, remove uninherited ones
10016 (setcdr (car tags-alist)
10017 (org-remove-uniherited-tags (cdar tags-alist))))
10018 (when (and (or (not todo-only)
10019 (and (member todo org-not-done-keywords)
10020 (or (not org-agenda-tags-todo-honor-ignore-options)
10021 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10022 (let ((case-fold-search t)) (eval matcher))
10024 (not (member org-archive-tag tags-list))
10025 ;; we have an archive tag, should we use this anyway?
10026 (or (not org-agenda-skip-archived-trees)
10027 (and (eq action 'agenda) org-agenda-archives-mode))))
10028 (unless (eq action 'sparse-tree) (org-agenda-skip))
10030 ;; select this headline
10032 (cond
10033 ((eq action 'sparse-tree)
10034 (and org-highlight-sparse-tree-matches
10035 (org-get-heading) (match-end 0)
10036 (org-highlight-new-match
10037 (match-beginning 0) (match-beginning 1)))
10038 (org-show-context 'tags-tree))
10039 ((eq action 'agenda)
10040 (setq txt (org-format-agenda-item
10042 (concat
10043 (if (eq org-tags-match-list-sublevels 'indented)
10044 (make-string (1- level) ?.) "")
10045 (org-get-heading))
10046 category
10047 tags-list
10049 priority (org-get-priority txt))
10050 (goto-char lspos)
10051 (setq marker (org-agenda-new-marker))
10052 (org-add-props txt props
10053 'org-marker marker 'org-hd-marker marker 'org-category category
10054 'todo-state todo
10055 'priority priority 'type "tagsmatch")
10056 (push txt rtn))
10057 ((functionp action)
10058 (save-excursion
10059 (setq rtn1 (funcall action))
10060 (push rtn1 rtn))
10061 (goto-char (point-at-eol)))
10062 (t (error "Invalid action")))
10064 ;; if we are to skip sublevels, jump to end of subtree
10065 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
10066 (when (and (eq action 'sparse-tree)
10067 (not org-sparse-tree-open-archived-trees))
10068 (org-hide-archived-subtrees (point-min) (point-max)))
10069 (nreverse rtn)))
10071 (defun org-remove-uniherited-tags (tags)
10072 "Remove all tags that are not inherited from the list TAGS."
10073 (cond
10074 ((eq org-use-tag-inheritance t)
10075 (if org-tags-exclude-from-inheritance
10076 (org-delete-all org-tags-exclude-from-inheritance tags)
10077 tags))
10078 ((not org-use-tag-inheritance) nil)
10079 ((stringp org-use-tag-inheritance)
10080 (delq nil (mapcar
10081 (lambda (x)
10082 (if (and (string-match org-use-tag-inheritance x)
10083 (not (member x org-tags-exclude-from-inheritance)))
10084 x nil))
10085 tags)))
10086 ((listp org-use-tag-inheritance)
10087 (delq nil (mapcar
10088 (lambda (x)
10089 (if (member x org-use-tag-inheritance) x nil))
10090 tags)))))
10092 (defvar todo-only) ;; dynamically scoped
10094 (defun org-match-sparse-tree (&optional todo-only match)
10095 "Create a sparse tree according to tags string MATCH.
10096 MATCH can contain positive and negative selection of tags, like
10097 \"+WORK+URGENT-WITHBOSS\".
10098 If optional argument TODO-ONLY is non-nil, only select lines that are
10099 also TODO lines."
10100 (interactive "P")
10101 (org-prepare-agenda-buffers (list (current-buffer)))
10102 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10104 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10106 (defvar org-cached-props nil)
10107 (defun org-cached-entry-get (pom property)
10108 (if (or (eq t org-use-property-inheritance)
10109 (and (stringp org-use-property-inheritance)
10110 (string-match org-use-property-inheritance property))
10111 (and (listp org-use-property-inheritance)
10112 (member property org-use-property-inheritance)))
10113 ;; Caching is not possible, check it directly
10114 (org-entry-get pom property 'inherit)
10115 ;; Get all properties, so that we can do complicated checks easily
10116 (cdr (assoc property (or org-cached-props
10117 (setq org-cached-props
10118 (org-entry-properties pom)))))))
10120 (defun org-global-tags-completion-table (&optional files)
10121 "Return the list of all tags in all agenda buffer/files."
10122 (save-excursion
10123 (org-uniquify
10124 (delq nil
10125 (apply 'append
10126 (mapcar
10127 (lambda (file)
10128 (set-buffer (find-file-noselect file))
10129 (append (org-get-buffer-tags)
10130 (mapcar (lambda (x) (if (stringp (car-safe x))
10131 (list (car-safe x)) nil))
10132 org-tag-alist)))
10133 (if (and files (car files))
10134 files
10135 (org-agenda-files))))))))
10137 (defun org-make-tags-matcher (match)
10138 "Create the TAGS//TODO matcher form for the selection string MATCH."
10139 ;; todo-only is scoped dynamically into this function, and the function
10140 ;; may change it if the matcher asks for it.
10141 (unless match
10142 ;; Get a new match request, with completion
10143 (let ((org-last-tags-completion-table
10144 (org-global-tags-completion-table)))
10145 (setq match (org-completing-read-no-ido
10146 "Match: " 'org-tags-completion-function nil nil nil
10147 'org-tags-history))))
10149 ;; Parse the string and create a lisp form
10150 (let ((match0 match)
10151 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10152 minus tag mm
10153 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10154 orterms term orlist re-p str-p level-p level-op time-p
10155 prop-p pn pv po cat-p gv rest)
10156 (if (string-match "/+" match)
10157 ;; match contains also a todo-matching request
10158 (progn
10159 (setq tagsmatch (substring match 0 (match-beginning 0))
10160 todomatch (substring match (match-end 0)))
10161 (if (string-match "^!" todomatch)
10162 (setq todo-only t todomatch (substring todomatch 1)))
10163 (if (string-match "^\\s-*$" todomatch)
10164 (setq todomatch nil)))
10165 ;; only matching tags
10166 (setq tagsmatch match todomatch nil))
10168 ;; Make the tags matcher
10169 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10170 (setq tagsmatcher t)
10171 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10172 (while (setq term (pop orterms))
10173 (while (and (equal (substring term -1) "\\") orterms)
10174 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10175 (while (string-match re term)
10176 (setq rest (substring term (match-end 0))
10177 minus (and (match-end 1)
10178 (equal (match-string 1 term) "-"))
10179 tag (match-string 2 term)
10180 re-p (equal (string-to-char tag) ?{)
10181 level-p (match-end 4)
10182 prop-p (match-end 5)
10183 mm (cond
10184 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10185 (level-p
10186 (setq level-op (org-op-to-function (match-string 3 term)))
10187 `(,level-op level ,(string-to-number
10188 (match-string 4 term))))
10189 (prop-p
10190 (setq pn (match-string 5 term)
10191 po (match-string 6 term)
10192 pv (match-string 7 term)
10193 cat-p (equal pn "CATEGORY")
10194 re-p (equal (string-to-char pv) ?{)
10195 str-p (equal (string-to-char pv) ?\")
10196 time-p (save-match-data
10197 (string-match "^\"[[<].*[]>]\"$" pv))
10198 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10199 (if time-p (setq pv (org-matcher-time pv)))
10200 (setq po (org-op-to-function po (if time-p 'time str-p)))
10201 (cond
10202 ((equal pn "CATEGORY")
10203 (setq gv '(get-text-property (point) 'org-category)))
10204 ((equal pn "TODO")
10205 (setq gv 'todo))
10207 (setq gv `(org-cached-entry-get nil ,pn))))
10208 (if re-p
10209 (if (eq po 'org<>)
10210 `(not (string-match ,pv (or ,gv "")))
10211 `(string-match ,pv (or ,gv "")))
10212 (if str-p
10213 `(,po (or ,gv "") ,pv)
10214 `(,po (string-to-number (or ,gv ""))
10215 ,(string-to-number pv) ))))
10216 (t `(member ,tag tags-list)))
10217 mm (if minus (list 'not mm) mm)
10218 term rest)
10219 (push mm tagsmatcher))
10220 (push (if (> (length tagsmatcher) 1)
10221 (cons 'and tagsmatcher)
10222 (car tagsmatcher))
10223 orlist)
10224 (setq tagsmatcher nil))
10225 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10226 (setq tagsmatcher
10227 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10228 ;; Make the todo matcher
10229 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10230 (setq todomatcher t)
10231 (setq orterms (org-split-string todomatch "|") orlist nil)
10232 (while (setq term (pop orterms))
10233 (while (string-match re term)
10234 (setq minus (and (match-end 1)
10235 (equal (match-string 1 term) "-"))
10236 kwd (match-string 2 term)
10237 re-p (equal (string-to-char kwd) ?{)
10238 term (substring term (match-end 0))
10239 mm (if re-p
10240 `(string-match ,(substring kwd 1 -1) todo)
10241 (list 'equal 'todo kwd))
10242 mm (if minus (list 'not mm) mm))
10243 (push mm todomatcher))
10244 (push (if (> (length todomatcher) 1)
10245 (cons 'and todomatcher)
10246 (car todomatcher))
10247 orlist)
10248 (setq todomatcher nil))
10249 (setq todomatcher (if (> (length orlist) 1)
10250 (cons 'or orlist) (car orlist))))
10252 ;; Return the string and lisp forms of the matcher
10253 (setq matcher (if todomatcher
10254 (list 'and tagsmatcher todomatcher)
10255 tagsmatcher))
10256 (cons match0 matcher)))
10258 (defun org-op-to-function (op &optional stringp)
10259 "Turn an operator into the appropriate function."
10260 (setq op
10261 (cond
10262 ((equal op "<" ) '(< string< org-time<))
10263 ((equal op ">" ) '(> org-string> org-time>))
10264 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10265 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10266 ((member op '("=" "==")) '(= string= org-time=))
10267 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10268 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10270 (defun org<> (a b) (not (= a b)))
10271 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10272 (defun org-string>= (a b) (not (string< a b)))
10273 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10274 (defun org-string<> (a b) (not (string= a b)))
10275 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10276 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10277 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10278 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10279 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10280 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10281 (defun org-2ft (s)
10282 "Convert S to a floating point time.
10283 If S is already a number, just return it. If it is a string, parse
10284 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10285 (cond
10286 ((numberp s) s)
10287 ((stringp s)
10288 (condition-case nil
10289 (float-time (apply 'encode-time (org-parse-time-string s)))
10290 (error 0.)))
10291 (t 0.)))
10293 (defun org-time-today ()
10294 "Time in seconds today at 0:00.
10295 Returns the float number of seconds since the beginning of the
10296 epoch to the beginning of today (00:00)."
10297 (float-time (apply 'encode-time
10298 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10300 (defun org-matcher-time (s)
10301 "Interpret a time comparison value."
10302 (save-match-data
10303 (cond
10304 ((string= s "<now>") (float-time))
10305 ((string= s "<today>") (org-time-today))
10306 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10307 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10308 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10309 (+ (org-time-today)
10310 (* (string-to-number (match-string 1 s))
10311 (cdr (assoc (match-string 2 s)
10312 '(("d" . 86400.0) ("w" . 604800.0)
10313 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10314 (t (org-2ft s)))))
10316 (defun org-match-any-p (re list)
10317 "Does re match any element of list?"
10318 (setq list (mapcar (lambda (x) (string-match re x)) list))
10319 (delq nil list))
10321 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10322 (defvar org-tags-overlay (org-make-overlay 1 1))
10323 (org-detach-overlay org-tags-overlay)
10325 (defun org-get-local-tags-at (&optional pos)
10326 "Get a list of tags defined in the current headline."
10327 (org-get-tags-at pos 'local))
10329 (defun org-get-local-tags ()
10330 "Get a list of tags defined in the current headline."
10331 (org-get-tags-at nil 'local))
10333 (defun org-get-tags-at (&optional pos local)
10334 "Get a list of all headline tags applicable at POS.
10335 POS defaults to point. If tags are inherited, the list contains
10336 the targets in the same sequence as the headlines appear, i.e.
10337 the tags of the current headline come last.
10338 When LOCAL is non-nil, only return tags from the current headline,
10339 ignore inherited ones."
10340 (interactive)
10341 (if (and org-trust-scanner-tags
10342 (or (not pos) (equal pos (point)))
10343 (not local))
10344 org-scanner-tags
10345 (let (tags ltags lastpos parent)
10346 (save-excursion
10347 (save-restriction
10348 (widen)
10349 (goto-char (or pos (point)))
10350 (save-match-data
10351 (catch 'done
10352 (condition-case nil
10353 (progn
10354 (org-back-to-heading t)
10355 (while (not (equal lastpos (point)))
10356 (setq lastpos (point))
10357 (when (looking-at
10358 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10359 (setq ltags (org-split-string
10360 (org-match-string-no-properties 1) ":"))
10361 (when parent
10362 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10363 (setq tags (append
10364 (if parent
10365 (org-remove-uniherited-tags ltags)
10366 ltags)
10367 tags)))
10368 (or org-use-tag-inheritance (throw 'done t))
10369 (if local (throw 'done t))
10370 (org-up-heading-all 1)
10371 (setq parent t)))
10372 (error nil)))))
10373 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10375 (defun org-add-prop-inherited (s)
10376 (add-text-properties 0 (length s) '(inherited t) s)
10379 (defun org-toggle-tag (tag &optional onoff)
10380 "Toggle the tag TAG for the current line.
10381 If ONOFF is `on' or `off', don't toggle but set to this state."
10382 (let (res current)
10383 (save-excursion
10384 (org-back-to-heading t)
10385 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10386 (point-at-eol) t)
10387 (progn
10388 (setq current (match-string 1))
10389 (replace-match ""))
10390 (setq current ""))
10391 (setq current (nreverse (org-split-string current ":")))
10392 (cond
10393 ((eq onoff 'on)
10394 (setq res t)
10395 (or (member tag current) (push tag current)))
10396 ((eq onoff 'off)
10397 (or (not (member tag current)) (setq current (delete tag current))))
10398 (t (if (member tag current)
10399 (setq current (delete tag current))
10400 (setq res t)
10401 (push tag current))))
10402 (end-of-line 1)
10403 (if current
10404 (progn
10405 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10406 (org-set-tags nil t))
10407 (delete-horizontal-space))
10408 (run-hooks 'org-after-tags-change-hook))
10409 res))
10411 (defun org-align-tags-here (to-col)
10412 ;; Assumes that this is a headline
10413 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10414 (beginning-of-line 1)
10415 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10416 (< pos (match-beginning 2)))
10417 (progn
10418 (setq tags-l (- (match-end 2) (match-beginning 2)))
10419 (goto-char (match-beginning 1))
10420 (insert " ")
10421 (delete-region (point) (1+ (match-beginning 2)))
10422 (setq ncol (max (1+ (current-column))
10423 (1+ col)
10424 (if (> to-col 0)
10425 to-col
10426 (- (abs to-col) tags-l))))
10427 (setq p (point))
10428 (insert (make-string (- ncol (current-column)) ?\ ))
10429 (setq ncol (current-column))
10430 (when indent-tabs-mode (tabify p (point-at-eol)))
10431 (org-move-to-column (min ncol col) t))
10432 (goto-char pos))))
10434 (defun org-set-tags-command (&optional arg just-align)
10435 "Call the set-tags command for the current entry."
10436 (interactive "P")
10437 (if (org-on-heading-p)
10438 (org-set-tags arg just-align)
10439 (save-excursion
10440 (org-back-to-heading t)
10441 (org-set-tags arg just-align))))
10443 (defun org-set-tags (&optional arg just-align)
10444 "Set the tags for the current headline.
10445 With prefix ARG, realign all tags in headings in the current buffer."
10446 (interactive "P")
10447 (let* ((re (concat "^" outline-regexp))
10448 (current (org-get-tags-string))
10449 (col (current-column))
10450 (org-setting-tags t)
10451 table current-tags inherited-tags ; computed below when needed
10452 tags p0 c0 c1 rpl)
10453 (if arg
10454 (save-excursion
10455 (goto-char (point-min))
10456 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10457 (while (re-search-forward re nil t)
10458 (org-set-tags nil t)
10459 (end-of-line 1)))
10460 (message "All tags realigned to column %d" org-tags-column))
10461 (if just-align
10462 (setq tags current)
10463 ;; Get a new set of tags from the user
10464 (save-excursion
10465 (setq table (append org-tag-persistent-alist
10466 (or org-tag-alist (org-get-buffer-tags)))
10467 org-last-tags-completion-table table
10468 current-tags (org-split-string current ":")
10469 inherited-tags (nreverse
10470 (nthcdr (length current-tags)
10471 (nreverse (org-get-tags-at))))
10472 tags
10473 (if (or (eq t org-use-fast-tag-selection)
10474 (and org-use-fast-tag-selection
10475 (delq nil (mapcar 'cdr table))))
10476 (org-fast-tag-selection
10477 current-tags inherited-tags table
10478 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10479 (let ((org-add-colon-after-tag-completion t))
10480 (org-trim
10481 (org-without-partial-completion
10482 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10483 nil nil current 'org-tags-history)))))))
10484 (while (string-match "[-+&]+" tags)
10485 ;; No boolean logic, just a list
10486 (setq tags (replace-match ":" t t tags))))
10488 (if (string-match "\\`[\t ]*\\'" tags)
10489 (setq tags "")
10490 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10491 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10493 ;; Insert new tags at the correct column
10494 (beginning-of-line 1)
10495 (cond
10496 ((and (equal current "") (equal tags "")))
10497 ((re-search-forward
10498 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10499 (point-at-eol) t)
10500 (if (equal tags "")
10501 (setq rpl "")
10502 (goto-char (match-beginning 0))
10503 (setq c0 (current-column) p0 (point)
10504 c1 (max (1+ c0) (if (> org-tags-column 0)
10505 org-tags-column
10506 (- (- org-tags-column) (length tags))))
10507 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10508 (replace-match rpl t t)
10509 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10510 tags)
10511 (t (error "Tags alignment failed")))
10512 (org-move-to-column col)
10513 (unless just-align
10514 (run-hooks 'org-after-tags-change-hook)))))
10516 (defun org-change-tag-in-region (beg end tag off)
10517 "Add or remove TAG for each entry in the region.
10518 This works in the agenda, and also in an org-mode buffer."
10519 (interactive
10520 (list (region-beginning) (region-end)
10521 (let ((org-last-tags-completion-table
10522 (if (org-mode-p)
10523 (org-get-buffer-tags)
10524 (org-global-tags-completion-table))))
10525 (org-ido-completing-read
10526 "Tag: " 'org-tags-completion-function nil nil nil
10527 'org-tags-history))
10528 (progn
10529 (message "[s]et or [r]emove? ")
10530 (equal (read-char-exclusive) ?r))))
10531 (if (fboundp 'deactivate-mark) (deactivate-mark))
10532 (let ((agendap (equal major-mode 'org-agenda-mode))
10533 l1 l2 m buf pos newhead (cnt 0))
10534 (goto-char end)
10535 (setq l2 (1- (org-current-line)))
10536 (goto-char beg)
10537 (setq l1 (org-current-line))
10538 (loop for l from l1 to l2 do
10539 (goto-line l)
10540 (setq m (get-text-property (point) 'org-hd-marker))
10541 (when (or (and (org-mode-p) (org-on-heading-p))
10542 (and agendap m))
10543 (setq buf (if agendap (marker-buffer m) (current-buffer))
10544 pos (if agendap m (point)))
10545 (with-current-buffer buf
10546 (save-excursion
10547 (save-restriction
10548 (goto-char pos)
10549 (setq cnt (1+ cnt))
10550 (org-toggle-tag tag (if off 'off 'on))
10551 (setq newhead (org-get-heading)))))
10552 (and agendap (org-agenda-change-all-lines newhead m))))
10553 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10555 (defun org-tags-completion-function (string predicate &optional flag)
10556 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10557 (confirm (lambda (x) (stringp (car x)))))
10558 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10559 (setq s1 (match-string 1 string)
10560 s2 (match-string 2 string))
10561 (setq s1 "" s2 string))
10562 (cond
10563 ((eq flag nil)
10564 ;; try completion
10565 (setq rtn (try-completion s2 ctable confirm))
10566 (if (stringp rtn)
10567 (setq rtn
10568 (concat s1 s2 (substring rtn (length s2))
10569 (if (and org-add-colon-after-tag-completion
10570 (assoc rtn ctable))
10571 ":" ""))))
10572 rtn)
10573 ((eq flag t)
10574 ;; all-completions
10575 (all-completions s2 ctable confirm)
10577 ((eq flag 'lambda)
10578 ;; exact match?
10579 (assoc s2 ctable)))
10582 (defun org-fast-tag-insert (kwd tags face &optional end)
10583 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10584 (insert (format "%-12s" (concat kwd ":"))
10585 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10586 (or end "")))
10588 (defun org-fast-tag-show-exit (flag)
10589 (save-excursion
10590 (goto-line 3)
10591 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10592 (replace-match ""))
10593 (when flag
10594 (end-of-line 1)
10595 (org-move-to-column (- (window-width) 19) t)
10596 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10598 (defun org-set-current-tags-overlay (current prefix)
10599 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10600 (if (featurep 'xemacs)
10601 (org-overlay-display org-tags-overlay (concat prefix s)
10602 'secondary-selection)
10603 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10604 (org-overlay-display org-tags-overlay (concat prefix s)))))
10606 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10607 "Fast tag selection with single keys.
10608 CURRENT is the current list of tags in the headline, INHERITED is the
10609 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10610 possibly with grouping information. TODO-TABLE is a similar table with
10611 TODO keywords, should these have keys assigned to them.
10612 If the keys are nil, a-z are automatically assigned.
10613 Returns the new tags string, or nil to not change the current settings."
10614 (let* ((fulltable (append table todo-table))
10615 (maxlen (apply 'max (mapcar
10616 (lambda (x)
10617 (if (stringp (car x)) (string-width (car x)) 0))
10618 fulltable)))
10619 (buf (current-buffer))
10620 (expert (eq org-fast-tag-selection-single-key 'expert))
10621 (buffer-tags nil)
10622 (fwidth (+ maxlen 3 1 3))
10623 (ncol (/ (- (window-width) 4) fwidth))
10624 (i-face 'org-done)
10625 (c-face 'org-todo)
10626 tg cnt e c char c1 c2 ntable tbl rtn
10627 ov-start ov-end ov-prefix
10628 (exit-after-next org-fast-tag-selection-single-key)
10629 (done-keywords org-done-keywords)
10630 groups ingroup)
10631 (save-excursion
10632 (beginning-of-line 1)
10633 (if (looking-at
10634 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10635 (setq ov-start (match-beginning 1)
10636 ov-end (match-end 1)
10637 ov-prefix "")
10638 (setq ov-start (1- (point-at-eol))
10639 ov-end (1+ ov-start))
10640 (skip-chars-forward "^\n\r")
10641 (setq ov-prefix
10642 (concat
10643 (buffer-substring (1- (point)) (point))
10644 (if (> (current-column) org-tags-column)
10646 (make-string (- org-tags-column (current-column)) ?\ ))))))
10647 (org-move-overlay org-tags-overlay ov-start ov-end)
10648 (save-window-excursion
10649 (if expert
10650 (set-buffer (get-buffer-create " *Org tags*"))
10651 (delete-other-windows)
10652 (split-window-vertically)
10653 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10654 (erase-buffer)
10655 (org-set-local 'org-done-keywords done-keywords)
10656 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10657 (org-fast-tag-insert "Current" current c-face "\n\n")
10658 (org-fast-tag-show-exit exit-after-next)
10659 (org-set-current-tags-overlay current ov-prefix)
10660 (setq tbl fulltable char ?a cnt 0)
10661 (while (setq e (pop tbl))
10662 (cond
10663 ((equal e '(:startgroup))
10664 (push '() groups) (setq ingroup t)
10665 (when (not (= cnt 0))
10666 (setq cnt 0)
10667 (insert "\n"))
10668 (insert "{ "))
10669 ((equal e '(:endgroup))
10670 (setq ingroup nil cnt 0)
10671 (insert "}\n"))
10672 ((equal e '(:newline))
10673 (when (not (= cnt 0))
10674 (setq cnt 0)
10675 (insert "\n")
10676 (setq e (car tbl))
10677 (while (equal (car tbl) '(:newline))
10678 (insert "\n")
10679 (setq tbl (cdr tbl)))))
10681 (setq tg (car e) c2 nil)
10682 (if (cdr e)
10683 (setq c (cdr e))
10684 ;; automatically assign a character.
10685 (setq c1 (string-to-char
10686 (downcase (substring
10687 tg (if (= (string-to-char tg) ?@) 1 0)))))
10688 (if (or (rassoc c1 ntable) (rassoc c1 table))
10689 (while (or (rassoc char ntable) (rassoc char table))
10690 (setq char (1+ char)))
10691 (setq c2 c1))
10692 (setq c (or c2 char)))
10693 (if ingroup (push tg (car groups)))
10694 (setq tg (org-add-props tg nil 'face
10695 (cond
10696 ((not (assoc tg table))
10697 (org-get-todo-face tg))
10698 ((member tg current) c-face)
10699 ((member tg inherited) i-face)
10700 (t nil))))
10701 (if (and (= cnt 0) (not ingroup)) (insert " "))
10702 (insert "[" c "] " tg (make-string
10703 (- fwidth 4 (length tg)) ?\ ))
10704 (push (cons tg c) ntable)
10705 (when (= (setq cnt (1+ cnt)) ncol)
10706 (insert "\n")
10707 (if ingroup (insert " "))
10708 (setq cnt 0)))))
10709 (setq ntable (nreverse ntable))
10710 (insert "\n")
10711 (goto-char (point-min))
10712 (if (not expert) (org-fit-window-to-buffer))
10713 (setq rtn
10714 (catch 'exit
10715 (while t
10716 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10717 (if groups " [!] no groups" " [!]groups")
10718 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10719 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10720 (cond
10721 ((= c ?\r) (throw 'exit t))
10722 ((= c ?!)
10723 (setq groups (not groups))
10724 (goto-char (point-min))
10725 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10726 ((= c ?\C-c)
10727 (if (not expert)
10728 (org-fast-tag-show-exit
10729 (setq exit-after-next (not exit-after-next)))
10730 (setq expert nil)
10731 (delete-other-windows)
10732 (split-window-vertically)
10733 (org-switch-to-buffer-other-window " *Org tags*")
10734 (org-fit-window-to-buffer)))
10735 ((or (= c ?\C-g)
10736 (and (= c ?q) (not (rassoc c ntable))))
10737 (org-detach-overlay org-tags-overlay)
10738 (setq quit-flag t))
10739 ((= c ?\ )
10740 (setq current nil)
10741 (if exit-after-next (setq exit-after-next 'now)))
10742 ((= c ?\t)
10743 (condition-case nil
10744 (setq tg (org-ido-completing-read
10745 "Tag: "
10746 (or buffer-tags
10747 (with-current-buffer buf
10748 (org-get-buffer-tags)))))
10749 (quit (setq tg "")))
10750 (when (string-match "\\S-" tg)
10751 (add-to-list 'buffer-tags (list tg))
10752 (if (member tg current)
10753 (setq current (delete tg current))
10754 (push tg current)))
10755 (if exit-after-next (setq exit-after-next 'now)))
10756 ((setq e (rassoc c todo-table) tg (car e))
10757 (with-current-buffer buf
10758 (save-excursion (org-todo tg)))
10759 (if exit-after-next (setq exit-after-next 'now)))
10760 ((setq e (rassoc c ntable) tg (car e))
10761 (if (member tg current)
10762 (setq current (delete tg current))
10763 (loop for g in groups do
10764 (if (member tg g)
10765 (mapc (lambda (x)
10766 (setq current (delete x current)))
10767 g)))
10768 (push tg current))
10769 (if exit-after-next (setq exit-after-next 'now))))
10771 ;; Create a sorted list
10772 (setq current
10773 (sort current
10774 (lambda (a b)
10775 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10776 (if (eq exit-after-next 'now) (throw 'exit t))
10777 (goto-char (point-min))
10778 (beginning-of-line 2)
10779 (delete-region (point) (point-at-eol))
10780 (org-fast-tag-insert "Current" current c-face)
10781 (org-set-current-tags-overlay current ov-prefix)
10782 (while (re-search-forward
10783 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10784 (setq tg (match-string 1))
10785 (add-text-properties
10786 (match-beginning 1) (match-end 1)
10787 (list 'face
10788 (cond
10789 ((member tg current) c-face)
10790 ((member tg inherited) i-face)
10791 (t (get-text-property (match-beginning 1) 'face))))))
10792 (goto-char (point-min)))))
10793 (org-detach-overlay org-tags-overlay)
10794 (if rtn
10795 (mapconcat 'identity current ":")
10796 nil))))
10798 (defun org-get-tags-string ()
10799 "Get the TAGS string in the current headline."
10800 (unless (org-on-heading-p t)
10801 (error "Not on a heading"))
10802 (save-excursion
10803 (beginning-of-line 1)
10804 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10805 (org-match-string-no-properties 1)
10806 "")))
10808 (defun org-get-tags ()
10809 "Get the list of tags specified in the current headline."
10810 (org-split-string (org-get-tags-string) ":"))
10812 (defun org-get-buffer-tags ()
10813 "Get a table of all tags used in the buffer, for completion."
10814 (let (tags)
10815 (save-excursion
10816 (goto-char (point-min))
10817 (while (re-search-forward
10818 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10819 (when (equal (char-after (point-at-bol 0)) ?*)
10820 (mapc (lambda (x) (add-to-list 'tags x))
10821 (org-split-string (org-match-string-no-properties 1) ":")))))
10822 (mapcar 'list tags)))
10824 ;;;; The mapping API
10826 ;;;###autoload
10827 (defun org-map-entries (func &optional match scope &rest skip)
10828 "Call FUNC at each headline selected by MATCH in SCOPE.
10830 FUNC is a function or a lisp form. The function will be called without
10831 arguments, with the cursor positioned at the beginning of the headline.
10832 The return values of all calls to the function will be collected and
10833 returned as a list.
10835 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10836 Only headlines that are matched by this query will be considered during
10837 the iteration. When MATCH is nil or t, all headlines will be
10838 visited by the iteration.
10840 SCOPE determines the scope of this command. It can be any of:
10842 nil The current buffer, respecting the restriction if any
10843 tree The subtree started with the entry at point
10844 file The current buffer, without restriction
10845 file-with-archives
10846 The current buffer, and any archives associated with it
10847 agenda All agenda files
10848 agenda-with-archives
10849 All agenda files with any archive files associated with them
10850 \(file1 file2 ...)
10851 If this is a list, all files in the list will be scanned
10853 The remaining args are treated as settings for the skipping facilities of
10854 the scanner. The following items can be given here:
10856 archive skip trees with the archive tag.
10857 comment skip trees with the COMMENT keyword
10858 function or Emacs Lisp form:
10859 will be used as value for `org-agenda-skip-function', so whenever
10860 the the function returns t, FUNC will not be called for that
10861 entry and search will continue from the point where the
10862 function leaves it.
10864 If your function needs to retrieve the tags including inherited tags
10865 at the *current* entry, you can use the value of the variable
10866 `org-scanner-tags' which will be much faster than getting the value
10867 with `org-get-tags-at'. If your function gets properties with
10868 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
10869 to t around the call to `org-entry-properties' to get the same speedup.
10870 Note that if your function moves around to retrieve tags and properties at
10871 a *different* entry, you cannot use these techniques."
10872 (let* ((org-agenda-archives-mode nil) ; just to make sure
10873 (org-agenda-skip-archived-trees (memq 'archive skip))
10874 (org-agenda-skip-comment-trees (memq 'comment skip))
10875 (org-agenda-skip-function
10876 (car (org-delete-all '(comment archive) skip)))
10877 (org-tags-match-list-sublevels t)
10878 matcher file res
10879 org-todo-keywords-for-agenda
10880 org-done-keywords-for-agenda
10881 org-todo-keyword-alist-for-agenda
10882 org-tag-alist-for-agenda)
10884 (cond
10885 ((eq match t) (setq matcher t))
10886 ((eq match nil) (setq matcher t))
10887 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10889 (save-excursion
10890 (save-restriction
10891 (when (eq scope 'tree)
10892 (org-back-to-heading t)
10893 (org-narrow-to-subtree)
10894 (setq scope nil))
10896 (if (not scope)
10897 (progn
10898 (org-prepare-agenda-buffers
10899 (list (buffer-file-name (current-buffer))))
10900 (setq res (org-scan-tags func matcher)))
10901 ;; Get the right scope
10902 (cond
10903 ((and scope (listp scope) (symbolp (car scope)))
10904 (setq scope (eval scope)))
10905 ((eq scope 'agenda)
10906 (setq scope (org-agenda-files t)))
10907 ((eq scope 'agenda-with-archives)
10908 (setq scope (org-agenda-files t))
10909 (setq scope (org-add-archive-files scope)))
10910 ((eq scope 'file)
10911 (setq scope (list (buffer-file-name))))
10912 ((eq scope 'file-with-archives)
10913 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10914 (org-prepare-agenda-buffers scope)
10915 (while (setq file (pop scope))
10916 (with-current-buffer (org-find-base-buffer-visiting file)
10917 (save-excursion
10918 (save-restriction
10919 (widen)
10920 (goto-char (point-min))
10921 (setq res (append res (org-scan-tags func matcher))))))))))
10922 res))
10924 ;;;; Properties
10926 ;;; Setting and retrieving properties
10928 (defconst org-special-properties
10929 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10930 "TIMESTAMP" "TIMESTAMP_IA")
10931 "The special properties valid in Org-mode.
10933 These are properties that are not defined in the property drawer,
10934 but in some other way.")
10936 (defconst org-default-properties
10937 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10938 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10939 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10940 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10941 "Some properties that are used by Org-mode for various purposes.
10942 Being in this list makes sure that they are offered for completion.")
10944 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10945 "Regular expression matching the first line of a property drawer.")
10947 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10948 "Regular expression matching the first line of a property drawer.")
10950 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10951 "Regular expression matching the first line of a property drawer.")
10953 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10954 "Regular expression matching the first line of a property drawer.")
10956 (defconst org-property-drawer-re
10957 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10958 org-property-end-re "\\)\n?")
10959 "Matches an entire property drawer.")
10961 (defconst org-clock-drawer-re
10962 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10963 org-property-end-re "\\)\n?")
10964 "Matches an entire clock drawer.")
10966 (defun org-property-action ()
10967 "Do an action on properties."
10968 (interactive)
10969 (let (c)
10970 (org-at-property-p)
10971 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10972 (setq c (read-char-exclusive))
10973 (cond
10974 ((equal c ?s)
10975 (call-interactively 'org-set-property))
10976 ((equal c ?d)
10977 (call-interactively 'org-delete-property))
10978 ((equal c ?D)
10979 (call-interactively 'org-delete-property-globally))
10980 ((equal c ?c)
10981 (call-interactively 'org-compute-property-at-point))
10982 (t (error "No such property action %c" c)))))
10984 (defun org-at-property-p ()
10985 "Is the cursor in a property line?"
10986 ;; FIXME: Does not check if we are actually in the drawer.
10987 ;; FIXME: also returns true on any drawers.....
10988 ;; This is used by C-c C-c for property action.
10989 (save-excursion
10990 (beginning-of-line 1)
10991 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10993 (defun org-get-property-block (&optional beg end force)
10994 "Return the (beg . end) range of the body of the property drawer.
10995 BEG and END can be beginning and end of subtree, if not given
10996 they will be found.
10997 If the drawer does not exist and FORCE is non-nil, create the drawer."
10998 (catch 'exit
10999 (save-excursion
11000 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11001 (end (or end (progn (outline-next-heading) (point)))))
11002 (goto-char beg)
11003 (if (re-search-forward org-property-start-re end t)
11004 (setq beg (1+ (match-end 0)))
11005 (if force
11006 (save-excursion
11007 (org-insert-property-drawer)
11008 (setq end (progn (outline-next-heading) (point))))
11009 (throw 'exit nil))
11010 (goto-char beg)
11011 (if (re-search-forward org-property-start-re end t)
11012 (setq beg (1+ (match-end 0)))))
11013 (if (re-search-forward org-property-end-re end t)
11014 (setq end (match-beginning 0))
11015 (or force (throw 'exit nil))
11016 (goto-char beg)
11017 (setq end beg)
11018 (org-indent-line-function)
11019 (insert ":END:\n"))
11020 (cons beg end)))))
11022 (defun org-entry-properties (&optional pom which)
11023 "Get all properties of the entry at point-or-marker POM.
11024 This includes the TODO keyword, the tags, time strings for deadline,
11025 scheduled, and clocking, and any additional properties defined in the
11026 entry. The return value is an alist, keys may occur multiple times
11027 if the property key was used several times.
11028 POM may also be nil, in which case the current entry is used.
11029 If WHICH is nil or `all', get all properties. If WHICH is
11030 `special' or `standard', only get that subclass."
11031 (setq which (or which 'all))
11032 (org-with-point-at pom
11033 (let ((clockstr (substring org-clock-string 0 -1))
11034 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11035 beg end range props sum-props key value string clocksum)
11036 (save-excursion
11037 (when (condition-case nil
11038 (and (org-mode-p) (org-back-to-heading t))
11039 (error nil))
11040 (setq beg (point))
11041 (setq sum-props (get-text-property (point) 'org-summaries))
11042 (setq clocksum (get-text-property (point) :org-clock-minutes))
11043 (outline-next-heading)
11044 (setq end (point))
11045 (when (memq which '(all special))
11046 ;; Get the special properties, like TODO and tags
11047 (goto-char beg)
11048 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11049 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11050 (when (looking-at org-priority-regexp)
11051 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11052 (when (and (setq value (org-get-tags-string))
11053 (string-match "\\S-" value))
11054 (push (cons "TAGS" value) props))
11055 (when (setq value (org-get-tags-at))
11056 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11057 props))
11058 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11059 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11060 string (if (equal key clockstr)
11061 (org-no-properties
11062 (org-trim
11063 (buffer-substring
11064 (match-beginning 3) (goto-char (point-at-eol)))))
11065 (substring (org-match-string-no-properties 3) 1 -1)))
11066 (unless key
11067 (if (= (char-after (match-beginning 3)) ?\[)
11068 (setq key "TIMESTAMP_IA")
11069 (setq key "TIMESTAMP")))
11070 (when (or (equal key clockstr) (not (assoc key props)))
11071 (push (cons key string) props)))
11075 (when (memq which '(all standard))
11076 ;; Get the standard properties, like :PROP: ...
11077 (setq range (org-get-property-block beg end))
11078 (when range
11079 (goto-char (car range))
11080 (while (re-search-forward
11081 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11082 (cdr range) t)
11083 (setq key (org-match-string-no-properties 1)
11084 value (org-trim (or (org-match-string-no-properties 2) "")))
11085 (unless (member key excluded)
11086 (push (cons key (or value "")) props)))))
11087 (if clocksum
11088 (push (cons "CLOCKSUM"
11089 (org-columns-number-to-string (/ (float clocksum) 60.)
11090 'add_times))
11091 props))
11092 (unless (assoc "CATEGORY" props)
11093 (setq value (or (org-get-category)
11094 (progn (org-refresh-category-properties)
11095 (org-get-category))))
11096 (push (cons "CATEGORY" value) props))
11097 (append sum-props (nreverse props)))))))
11099 (defun org-entry-get (pom property &optional inherit)
11100 "Get value of PROPERTY for entry at point-or-marker POM.
11101 If INHERIT is non-nil and the entry does not have the property,
11102 then also check higher levels of the hierarchy.
11103 If INHERIT is the symbol `selective', use inheritance only if the setting
11104 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11105 If the property is present but empty, the return value is the empty string.
11106 If the property is not present at all, nil is returned."
11107 (org-with-point-at pom
11108 (if (and inherit (if (eq inherit 'selective)
11109 (org-property-inherit-p property)
11111 (org-entry-get-with-inheritance property)
11112 (if (member property org-special-properties)
11113 ;; We need a special property. Use brute force, get all properties.
11114 (cdr (assoc property (org-entry-properties nil 'special)))
11115 (let ((range (org-get-property-block)))
11116 (if (and range
11117 (goto-char (car range))
11118 (re-search-forward
11119 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11120 (cdr range) t))
11121 ;; Found the property, return it.
11122 (if (match-end 1)
11123 (org-match-string-no-properties 1)
11124 "")))))))
11126 (defun org-property-or-variable-value (var &optional inherit)
11127 "Check if there is a property fixing the value of VAR.
11128 If yes, return this value. If not, return the current value of the variable."
11129 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11130 (if (and prop (stringp prop) (string-match "\\S-" prop))
11131 (read prop)
11132 (symbol-value var))))
11134 (defun org-entry-delete (pom property)
11135 "Delete the property PROPERTY from entry at point-or-marker POM."
11136 (org-with-point-at pom
11137 (if (member property org-special-properties)
11138 nil ; cannot delete these properties.
11139 (let ((range (org-get-property-block)))
11140 (if (and range
11141 (goto-char (car range))
11142 (re-search-forward
11143 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11144 (cdr range) t))
11145 (progn
11146 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11148 nil)))))
11150 ;; Multi-values properties are properties that contain multiple values
11151 ;; These values are assumed to be single words, separated by whitespace.
11152 (defun org-entry-add-to-multivalued-property (pom property value)
11153 "Add VALUE to the 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 (unless (member value values)
11158 (setq values (cons value values))
11159 (org-entry-put pom property
11160 (mapconcat 'identity values " ")))))
11162 (defun org-entry-remove-from-multivalued-property (pom property value)
11163 "Remove VALUE from 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 (when (member value values)
11168 (setq values (delete value values))
11169 (org-entry-put pom property
11170 (mapconcat 'identity values " ")))))
11172 (defun org-entry-member-in-multivalued-property (pom property value)
11173 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11174 (let* ((old (org-entry-get pom property))
11175 (values (and old (org-split-string old "[ \t]"))))
11176 (setq value (org-entry-protect-space value))
11177 (member value values)))
11179 (defun org-entry-get-multivalued-property (pom property)
11180 "Return a list of values in a multivalued property."
11181 (let* ((value (org-entry-get pom property))
11182 (values (and value (org-split-string value "[ \t]"))))
11183 (mapcar 'org-entry-restore-space values)))
11185 (defun org-entry-put-multivalued-property (pom property &rest values)
11186 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11187 VALUES should be a list of strings. Spaces will be protected."
11188 (org-entry-put pom property
11189 (mapconcat 'org-entry-protect-space values " "))
11190 (let* ((value (org-entry-get pom property))
11191 (values (and value (org-split-string value "[ \t]"))))
11192 (mapcar 'org-entry-restore-space values)))
11194 (defun org-entry-protect-space (s)
11195 "Protect spaces and newline in string S."
11196 (while (string-match " " s)
11197 (setq s (replace-match "%20" t t s)))
11198 (while (string-match "\n" s)
11199 (setq s (replace-match "%0A" t t s)))
11202 (defun org-entry-restore-space (s)
11203 "Restore spaces and newline in string S."
11204 (while (string-match "%20" s)
11205 (setq s (replace-match " " t t s)))
11206 (while (string-match "%0A" s)
11207 (setq s (replace-match "\n" t t s)))
11210 (defvar org-entry-property-inherited-from (make-marker)
11211 "Marker pointing to the entry from where a property was inherited.
11212 Each call to `org-entry-get-with-inheritance' will set this marker to the
11213 location of the entry where the inheritance search matched. If there was
11214 no match, the marker will point nowhere.
11215 Note that also `org-entry-get' calls this function, if the INHERIT flag
11216 is set.")
11218 (defun org-entry-get-with-inheritance (property)
11219 "Get entry property, and search higher levels if not present."
11220 (move-marker org-entry-property-inherited-from nil)
11221 (let (tmp)
11222 (save-excursion
11223 (save-restriction
11224 (widen)
11225 (catch 'ex
11226 (while t
11227 (when (setq tmp (org-entry-get nil property))
11228 (org-back-to-heading t)
11229 (move-marker org-entry-property-inherited-from (point))
11230 (throw 'ex tmp))
11231 (or (org-up-heading-safe) (throw 'ex nil)))))
11232 (or tmp
11233 (cdr (assoc property org-file-properties))
11234 (cdr (assoc property org-global-properties))
11235 (cdr (assoc property org-global-properties-fixed))))))
11237 (defun org-entry-put (pom property value)
11238 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11239 (org-with-point-at pom
11240 (org-back-to-heading t)
11241 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11242 range)
11243 (cond
11244 ((equal property "TODO")
11245 (when (and (stringp value) (string-match "\\S-" value)
11246 (not (member value org-todo-keywords-1)))
11247 (error "\"%s\" is not a valid TODO state" value))
11248 (if (or (not value)
11249 (not (string-match "\\S-" value)))
11250 (setq value 'none))
11251 (org-todo value)
11252 (org-set-tags nil 'align))
11253 ((equal property "PRIORITY")
11254 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11255 (string-to-char value) ?\ ))
11256 (org-set-tags nil 'align))
11257 ((equal property "SCHEDULED")
11258 (if (re-search-forward org-scheduled-time-regexp end t)
11259 (cond
11260 ((eq value 'earlier) (org-timestamp-change -1 'day))
11261 ((eq value 'later) (org-timestamp-change 1 'day))
11262 (t (call-interactively 'org-schedule)))
11263 (call-interactively 'org-schedule)))
11264 ((equal property "DEADLINE")
11265 (if (re-search-forward org-deadline-time-regexp end t)
11266 (cond
11267 ((eq value 'earlier) (org-timestamp-change -1 'day))
11268 ((eq value 'later) (org-timestamp-change 1 'day))
11269 (t (call-interactively 'org-deadline)))
11270 (call-interactively 'org-deadline)))
11271 ((member property org-special-properties)
11272 (error "The %s property can not yet be set with `org-entry-put'"
11273 property))
11274 (t ; a non-special property
11275 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11276 (setq range (org-get-property-block beg end 'force))
11277 (goto-char (car range))
11278 (if (re-search-forward
11279 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11280 (progn
11281 (delete-region (match-beginning 1) (match-end 1))
11282 (goto-char (match-beginning 1)))
11283 (goto-char (cdr range))
11284 (insert "\n")
11285 (backward-char 1)
11286 (org-indent-line-function)
11287 (insert ":" property ":"))
11288 (and value (insert " " value))
11289 (org-indent-line-function)))))))
11291 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11292 "Get all property keys in the current buffer.
11293 With INCLUDE-SPECIALS, also list the special properties that reflect things
11294 like tags and TODO state.
11295 With INCLUDE-DEFAULTS, also include properties that has special meaning
11296 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11297 With INCLUDE-COLUMNS, also include property names given in COLUMN
11298 formats in the current buffer."
11299 (let (rtn range cfmt s p)
11300 (save-excursion
11301 (save-restriction
11302 (widen)
11303 (goto-char (point-min))
11304 (while (re-search-forward org-property-start-re nil t)
11305 (setq range (org-get-property-block))
11306 (goto-char (car range))
11307 (while (re-search-forward
11308 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11309 (cdr range) t)
11310 (add-to-list 'rtn (org-match-string-no-properties 1)))
11311 (outline-next-heading))))
11313 (when include-specials
11314 (setq rtn (append org-special-properties rtn)))
11316 (when include-defaults
11317 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11319 (when include-columns
11320 (save-excursion
11321 (save-restriction
11322 (widen)
11323 (goto-char (point-min))
11324 (while (re-search-forward
11325 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11326 nil t)
11327 (setq cfmt (match-string 2) s 0)
11328 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11329 cfmt s)
11330 (setq s (match-end 0)
11331 p (match-string 1 cfmt))
11332 (unless (or (equal p "ITEM")
11333 (member p org-special-properties))
11334 (add-to-list 'rtn (match-string 1 cfmt))))))))
11336 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11338 (defun org-property-values (key)
11339 "Return a list of all values of property KEY."
11340 (save-excursion
11341 (save-restriction
11342 (widen)
11343 (goto-char (point-min))
11344 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11345 values)
11346 (while (re-search-forward re nil t)
11347 (add-to-list 'values (org-trim (match-string 1))))
11348 (delete "" values)))))
11350 (defun org-insert-property-drawer ()
11351 "Insert a property drawer into the current entry."
11352 (interactive)
11353 (org-back-to-heading t)
11354 (looking-at outline-regexp)
11355 (let ((indent (- (match-end 0)(match-beginning 0)))
11356 (beg (point))
11357 (re (concat "^[ \t]*" org-keyword-time-regexp))
11358 end hiddenp)
11359 (outline-next-heading)
11360 (setq end (point))
11361 (goto-char beg)
11362 (while (re-search-forward re end t))
11363 (setq hiddenp (org-invisible-p))
11364 (end-of-line 1)
11365 (and (equal (char-after) ?\n) (forward-char 1))
11366 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11367 (if (member (match-string 1) '("CLOCK:" ":END:"))
11368 ;; just skip this line
11369 (beginning-of-line 2)
11370 ;; Drawer start, find the end
11371 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11372 (beginning-of-line 1)))
11373 (org-skip-over-state-notes)
11374 (skip-chars-backward " \t\n\r")
11375 (if (eq (char-before) ?*) (forward-char 1))
11376 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11377 (beginning-of-line 0)
11378 (org-indent-to-column indent)
11379 (beginning-of-line 2)
11380 (org-indent-to-column indent)
11381 (beginning-of-line 0)
11382 (if hiddenp
11383 (save-excursion
11384 (org-back-to-heading t)
11385 (hide-entry))
11386 (org-flag-drawer t))))
11388 (defun org-set-property (property value)
11389 "In the current entry, set PROPERTY to VALUE.
11390 When called interactively, this will prompt for a property name, offering
11391 completion on existing and default properties. And then it will prompt
11392 for a value, offering completion either on allowed values (via an inherited
11393 xxx_ALL property) or on existing values in other instances of this property
11394 in the current file."
11395 (interactive
11396 (let* ((completion-ignore-case t)
11397 (keys (org-buffer-property-keys nil t t))
11398 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11399 (prop (if (member prop0 keys)
11400 prop0
11401 (or (cdr (assoc (downcase prop0)
11402 (mapcar (lambda (x) (cons (downcase x) x))
11403 keys)))
11404 prop0)))
11405 (cur (org-entry-get nil prop))
11406 (allowed (org-property-get-allowed-values nil prop 'table))
11407 (existing (mapcar 'list (org-property-values prop)))
11408 (val (if allowed
11409 (org-completing-read "Value: " allowed nil 'req-match)
11410 (let (org-completion-use-ido)
11411 (org-completing-read
11412 (concat "Value" (if (and cur (string-match "\\S-" cur))
11413 (concat "[" cur "]") "")
11414 ": ")
11415 existing nil nil "" nil cur)))))
11416 (list prop (if (equal val "") cur val))))
11417 (unless (equal (org-entry-get nil property) value)
11418 (org-entry-put nil property value)))
11420 (defun org-delete-property (property)
11421 "In the current entry, delete PROPERTY."
11422 (interactive
11423 (let* ((completion-ignore-case t)
11424 (prop (org-ido-completing-read
11425 "Property: " (org-entry-properties nil 'standard))))
11426 (list prop)))
11427 (message "Property %s %s" property
11428 (if (org-entry-delete nil property)
11429 "deleted"
11430 "was not present in the entry")))
11432 (defun org-delete-property-globally (property)
11433 "Remove PROPERTY globally, from all entries."
11434 (interactive
11435 (let* ((completion-ignore-case t)
11436 (prop (org-ido-completing-read
11437 "Globally remove property: "
11438 (mapcar 'list (org-buffer-property-keys)))))
11439 (list prop)))
11440 (save-excursion
11441 (save-restriction
11442 (widen)
11443 (goto-char (point-min))
11444 (let ((cnt 0))
11445 (while (re-search-forward
11446 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11447 nil t)
11448 (setq cnt (1+ cnt))
11449 (replace-match ""))
11450 (message "Property \"%s\" removed from %d entries" property cnt)))))
11452 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11454 (defun org-compute-property-at-point ()
11455 "Compute the property at point.
11456 This looks for an enclosing column format, extracts the operator and
11457 then applies it to the property in the column format's scope."
11458 (interactive)
11459 (unless (org-at-property-p)
11460 (error "Not at a property"))
11461 (let ((prop (org-match-string-no-properties 2)))
11462 (org-columns-get-format-and-top-level)
11463 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11464 (error "No operator defined for property %s" prop))
11465 (org-columns-compute prop)))
11467 (defun org-property-get-allowed-values (pom property &optional table)
11468 "Get allowed values for the property PROPERTY.
11469 When TABLE is non-nil, return an alist that can directly be used for
11470 completion."
11471 (let (vals)
11472 (cond
11473 ((equal property "TODO")
11474 (setq vals (org-with-point-at pom
11475 (append org-todo-keywords-1 '("")))))
11476 ((equal property "PRIORITY")
11477 (let ((n org-lowest-priority))
11478 (while (>= n org-highest-priority)
11479 (push (char-to-string n) vals)
11480 (setq n (1- n)))))
11481 ((member property org-special-properties))
11483 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11485 (when (and vals (string-match "\\S-" vals))
11486 (setq vals (car (read-from-string (concat "(" vals ")"))))
11487 (setq vals (mapcar (lambda (x)
11488 (cond ((stringp x) x)
11489 ((numberp x) (number-to-string x))
11490 ((symbolp x) (symbol-name x))
11491 (t "???")))
11492 vals)))))
11493 (if table (mapcar 'list vals) vals)))
11495 (defun org-property-previous-allowed-value (&optional previous)
11496 "Switch to the next allowed value for this property."
11497 (interactive)
11498 (org-property-next-allowed-value t))
11500 (defun org-property-next-allowed-value (&optional previous)
11501 "Switch to the next allowed value for this property."
11502 (interactive)
11503 (unless (org-at-property-p)
11504 (error "Not at a property"))
11505 (let* ((key (match-string 2))
11506 (value (match-string 3))
11507 (allowed (or (org-property-get-allowed-values (point) key)
11508 (and (member value '("[ ]" "[-]" "[X]"))
11509 '("[ ]" "[X]"))))
11510 nval)
11511 (unless allowed
11512 (error "Allowed values for this property have not been defined"))
11513 (if previous (setq allowed (reverse allowed)))
11514 (if (member value allowed)
11515 (setq nval (car (cdr (member value allowed)))))
11516 (setq nval (or nval (car allowed)))
11517 (if (equal nval value)
11518 (error "Only one allowed value for this property"))
11519 (org-at-property-p)
11520 (replace-match (concat " :" key ": " nval) t t)
11521 (org-indent-line-function)
11522 (beginning-of-line 1)
11523 (skip-chars-forward " \t")))
11525 (defun org-find-entry-with-id (ident)
11526 "Locate the entry that contains the ID property with exact value IDENT.
11527 IDENT can be a string, a symbol or a number, this function will search for
11528 the string representation of it.
11529 Return the position where this entry starts, or nil if there is no such entry."
11530 (interactive "sID: ")
11531 (let ((id (cond
11532 ((stringp ident) ident)
11533 ((symbol-name ident) (symbol-name ident))
11534 ((numberp ident) (number-to-string ident))
11535 (t (error "IDENT %s must be a string, symbol or number" ident))))
11536 (case-fold-search nil))
11537 (save-excursion
11538 (save-restriction
11539 (widen)
11540 (goto-char (point-min))
11541 (when (re-search-forward
11542 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11543 nil t)
11544 (org-back-to-heading)
11545 (point))))))
11547 ;;;; Timestamps
11549 (defvar org-last-changed-timestamp nil)
11550 (defvar org-last-inserted-timestamp nil
11551 "The last time stamp inserted with `org-insert-time-stamp'.")
11552 (defvar org-time-was-given) ; dynamically scoped parameter
11553 (defvar org-end-time-was-given) ; dynamically scoped parameter
11554 (defvar org-ts-what) ; dynamically scoped parameter
11556 (defun org-time-stamp (arg &optional inactive)
11557 "Prompt for a date/time and insert a time stamp.
11558 If the user specifies a time like HH:MM, or if this command is called
11559 with a prefix argument, the time stamp will contain date and time.
11560 Otherwise, only the date will be included. All parts of a date not
11561 specified by the user will be filled in from the current date/time.
11562 So if you press just return without typing anything, the time stamp
11563 will represent the current date/time. If there is already a timestamp
11564 at the cursor, it will be modified."
11565 (interactive "P")
11566 (let* ((ts nil)
11567 (default-time
11568 ;; Default time is either today, or, when entering a range,
11569 ;; the range start.
11570 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11571 (save-excursion
11572 (re-search-backward
11573 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11574 (- (point) 20) t)))
11575 (apply 'encode-time (org-parse-time-string (match-string 1)))
11576 (current-time)))
11577 (default-input (and ts (org-get-compact-tod ts)))
11578 org-time-was-given org-end-time-was-given time)
11579 (cond
11580 ((and (org-at-timestamp-p t)
11581 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11582 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11583 (insert "--")
11584 (setq time (let ((this-command this-command))
11585 (org-read-date arg 'totime nil nil
11586 default-time default-input)))
11587 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11588 ((org-at-timestamp-p t)
11589 (setq time (let ((this-command this-command))
11590 (org-read-date arg 'totime nil nil default-time default-input)))
11591 (when (org-at-timestamp-p t) ; just to get the match data
11592 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11593 (replace-match "")
11594 (setq org-last-changed-timestamp
11595 (org-insert-time-stamp
11596 time (or org-time-was-given arg)
11597 inactive nil nil (list org-end-time-was-given))))
11598 (message "Timestamp updated"))
11600 (setq time (let ((this-command this-command))
11601 (org-read-date arg 'totime nil nil default-time default-input)))
11602 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11603 nil nil (list org-end-time-was-given))))))
11605 ;; FIXME: can we use this for something else, like computing time differences?
11606 (defun org-get-compact-tod (s)
11607 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11608 (let* ((t1 (match-string 1 s))
11609 (h1 (string-to-number (match-string 2 s)))
11610 (m1 (string-to-number (match-string 3 s)))
11611 (t2 (and (match-end 4) (match-string 5 s)))
11612 (h2 (and t2 (string-to-number (match-string 6 s))))
11613 (m2 (and t2 (string-to-number (match-string 7 s))))
11614 dh dm)
11615 (if (not t2)
11617 (setq dh (- h2 h1) dm (- m2 m1))
11618 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11619 (concat t1 "+" (number-to-string dh)
11620 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11622 (defun org-time-stamp-inactive (&optional arg)
11623 "Insert an inactive time stamp.
11624 An inactive time stamp is enclosed in square brackets instead of angle
11625 brackets. It is inactive in the sense that it does not trigger agenda entries,
11626 does not link to the calendar and cannot be changed with the S-cursor keys.
11627 So these are more for recording a certain time/date."
11628 (interactive "P")
11629 (org-time-stamp arg 'inactive))
11631 (defvar org-date-ovl (org-make-overlay 1 1))
11632 (org-overlay-put org-date-ovl 'face 'org-warning)
11633 (org-detach-overlay org-date-ovl)
11635 (defvar org-ans1) ; dynamically scoped parameter
11636 (defvar org-ans2) ; dynamically scoped parameter
11638 (defvar org-plain-time-of-day-regexp) ; defined below
11640 (defvar org-overriding-default-time nil) ; dynamically scoped
11641 (defvar org-read-date-overlay nil)
11642 (defvar org-dcst nil) ; dynamically scoped
11643 (defvar org-read-date-history nil)
11645 (defun org-read-date (&optional with-time to-time from-string prompt
11646 default-time default-input)
11647 "Read a date, possibly a time, and make things smooth for the user.
11648 The prompt will suggest to enter an ISO date, but you can also enter anything
11649 which will at least partially be understood by `parse-time-string'.
11650 Unrecognized parts of the date will default to the current day, month, year,
11651 hour and minute. If this command is called to replace a timestamp at point,
11652 of to enter the second timestamp of a range, the default time is taken from the
11653 existing stamp. For example,
11654 3-2-5 --> 2003-02-05
11655 feb 15 --> currentyear-02-15
11656 sep 12 9 --> 2009-09-12
11657 12:45 --> today 12:45
11658 22 sept 0:34 --> currentyear-09-22 0:34
11659 12 --> currentyear-currentmonth-12
11660 Fri --> nearest Friday (today or later)
11661 etc.
11663 Furthermore you can specify a relative date by giving, as the *first* thing
11664 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11665 change in days weeks, months, years.
11666 With a single plus or minus, the date is relative to today. With a double
11667 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11668 +4d --> four days from today
11669 +4 --> same as above
11670 +2w --> two weeks from today
11671 ++5 --> five days from default date
11673 The function understands only English month and weekday abbreviations,
11674 but this can be configured with the variables `parse-time-months' and
11675 `parse-time-weekdays'.
11677 While prompting, a calendar is popped up - you can also select the
11678 date with the mouse (button 1). The calendar shows a period of three
11679 months. To scroll it to other months, use the keys `>' and `<'.
11680 If you don't like the calendar, turn it off with
11681 \(setq org-read-date-popup-calendar nil)
11683 With optional argument TO-TIME, the date will immediately be converted
11684 to an internal time.
11685 With an optional argument WITH-TIME, the prompt will suggest to also
11686 insert a time. Note that when WITH-TIME is not set, you can still
11687 enter a time, and this function will inform the calling routine about
11688 this change. The calling routine may then choose to change the format
11689 used to insert the time stamp into the buffer to include the time.
11690 With optional argument FROM-STRING, read from this string instead from
11691 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11692 the time/date that is used for everything that is not specified by the
11693 user."
11694 (require 'parse-time)
11695 (let* ((org-time-stamp-rounding-minutes
11696 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11697 (org-dcst org-display-custom-times)
11698 (ct (org-current-time))
11699 (def (or org-overriding-default-time default-time ct))
11700 (defdecode (decode-time def))
11701 (dummy (progn
11702 (when (< (nth 2 defdecode) org-extend-today-until)
11703 (setcar (nthcdr 2 defdecode) -1)
11704 (setcar (nthcdr 1 defdecode) 59)
11705 (setq def (apply 'encode-time defdecode)
11706 defdecode (decode-time def)))))
11707 (calendar-move-hook nil)
11708 (calendar-view-diary-initially-flag nil)
11709 (view-diary-entries-initially nil)
11710 (calendar-view-holidays-initially-flag nil)
11711 (view-calendar-holidays-initially nil)
11712 (timestr (format-time-string
11713 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11714 (prompt (concat (if prompt (concat prompt " ") "")
11715 (format "Date+time [%s]: " timestr)))
11716 ans (org-ans0 "") org-ans1 org-ans2 final)
11718 (cond
11719 (from-string (setq ans from-string))
11720 (org-read-date-popup-calendar
11721 (save-excursion
11722 (save-window-excursion
11723 (calendar)
11724 (calendar-forward-day (- (time-to-days def)
11725 (calendar-absolute-from-gregorian
11726 (calendar-current-date))))
11727 (org-eval-in-calendar nil t)
11728 (let* ((old-map (current-local-map))
11729 (map (copy-keymap calendar-mode-map))
11730 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11731 (org-defkey map (kbd "RET") 'org-calendar-select)
11732 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11733 'org-calendar-select-mouse)
11734 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11735 'org-calendar-select-mouse)
11736 (org-defkey minibuffer-local-map [(meta shift left)]
11737 (lambda () (interactive)
11738 (org-eval-in-calendar '(calendar-backward-month 1))))
11739 (org-defkey minibuffer-local-map [(meta shift right)]
11740 (lambda () (interactive)
11741 (org-eval-in-calendar '(calendar-forward-month 1))))
11742 (org-defkey minibuffer-local-map [(meta shift up)]
11743 (lambda () (interactive)
11744 (org-eval-in-calendar '(calendar-backward-year 1))))
11745 (org-defkey minibuffer-local-map [(meta shift down)]
11746 (lambda () (interactive)
11747 (org-eval-in-calendar '(calendar-forward-year 1))))
11748 (org-defkey minibuffer-local-map [(shift up)]
11749 (lambda () (interactive)
11750 (org-eval-in-calendar '(calendar-backward-week 1))))
11751 (org-defkey minibuffer-local-map [(shift down)]
11752 (lambda () (interactive)
11753 (org-eval-in-calendar '(calendar-forward-week 1))))
11754 (org-defkey minibuffer-local-map [(shift left)]
11755 (lambda () (interactive)
11756 (org-eval-in-calendar '(calendar-backward-day 1))))
11757 (org-defkey minibuffer-local-map [(shift right)]
11758 (lambda () (interactive)
11759 (org-eval-in-calendar '(calendar-forward-day 1))))
11760 (org-defkey minibuffer-local-map ">"
11761 (lambda () (interactive)
11762 (org-eval-in-calendar '(scroll-calendar-left 1))))
11763 (org-defkey minibuffer-local-map "<"
11764 (lambda () (interactive)
11765 (org-eval-in-calendar '(scroll-calendar-right 1))))
11766 (run-hooks 'org-read-date-minibuffer-setup-hook)
11767 (unwind-protect
11768 (progn
11769 (use-local-map map)
11770 (add-hook 'post-command-hook 'org-read-date-display)
11771 (setq org-ans0 (read-string prompt default-input
11772 'org-read-date-history nil))
11773 ;; org-ans0: from prompt
11774 ;; org-ans1: from mouse click
11775 ;; org-ans2: from calendar motion
11776 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11777 (remove-hook 'post-command-hook 'org-read-date-display)
11778 (use-local-map old-map)
11779 (when org-read-date-overlay
11780 (org-delete-overlay org-read-date-overlay)
11781 (setq org-read-date-overlay nil)))))))
11783 (t ; Naked prompt only
11784 (unwind-protect
11785 (setq ans (read-string prompt default-input
11786 'org-read-date-history timestr))
11787 (when org-read-date-overlay
11788 (org-delete-overlay org-read-date-overlay)
11789 (setq org-read-date-overlay nil)))))
11791 (setq final (org-read-date-analyze ans def defdecode))
11793 (if to-time
11794 (apply 'encode-time final)
11795 (if (and (boundp 'org-time-was-given) org-time-was-given)
11796 (format "%04d-%02d-%02d %02d:%02d"
11797 (nth 5 final) (nth 4 final) (nth 3 final)
11798 (nth 2 final) (nth 1 final))
11799 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11800 (defvar def)
11801 (defvar defdecode)
11802 (defvar with-time)
11803 (defun org-read-date-display ()
11804 "Display the current date prompt interpretation in the minibuffer."
11805 (when org-read-date-display-live
11806 (when org-read-date-overlay
11807 (org-delete-overlay org-read-date-overlay))
11808 (let ((p (point)))
11809 (end-of-line 1)
11810 (while (not (equal (buffer-substring
11811 (max (point-min) (- (point) 4)) (point))
11812 " "))
11813 (insert " "))
11814 (goto-char p))
11815 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11816 " " (or org-ans1 org-ans2)))
11817 (org-end-time-was-given nil)
11818 (f (org-read-date-analyze ans def defdecode))
11819 (fmts (if org-dcst
11820 org-time-stamp-custom-formats
11821 org-time-stamp-formats))
11822 (fmt (if (or with-time
11823 (and (boundp 'org-time-was-given) org-time-was-given))
11824 (cdr fmts)
11825 (car fmts)))
11826 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11827 (when (and org-end-time-was-given
11828 (string-match org-plain-time-of-day-regexp txt))
11829 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11830 org-end-time-was-given
11831 (substring txt (match-end 0)))))
11832 (setq org-read-date-overlay
11833 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11834 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11836 (defun org-read-date-analyze (ans def defdecode)
11837 "Analyse the combined answer of the date prompt."
11838 ;; FIXME: cleanup and comment
11839 (let (delta deltan deltaw deltadef year month day
11840 hour minute second wday pm h2 m2 tl wday1
11841 iso-year iso-weekday iso-week iso-year iso-date)
11843 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11844 (setq ans "+0"))
11846 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11847 (setq ans (replace-match "" t t ans)
11848 deltan (car delta)
11849 deltaw (nth 1 delta)
11850 deltadef (nth 2 delta)))
11852 ;; Check if there is an iso week date in there
11853 ;; If yes, sore the info and postpone interpreting it until the rest
11854 ;; of the parsing is done
11855 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11856 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11857 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11858 iso-week (string-to-number (match-string 2 ans)))
11859 (setq ans (replace-match "" t t ans)))
11861 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11862 (when (string-match
11863 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11864 (setq year (if (match-end 2)
11865 (string-to-number (match-string 2 ans))
11866 (string-to-number (format-time-string "%Y")))
11867 month (string-to-number (match-string 3 ans))
11868 day (string-to-number (match-string 4 ans)))
11869 (if (< year 100) (setq year (+ 2000 year)))
11870 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11871 t nil ans)))
11872 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11873 ;; If there is a time with am/pm, and *no* time without it, we convert
11874 ;; so that matching will be successful.
11875 (loop for i from 1 to 2 do ; twice, for end time as well
11876 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11877 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11878 (setq hour (string-to-number (match-string 1 ans))
11879 minute (if (match-end 3)
11880 (string-to-number (match-string 3 ans))
11882 pm (equal ?p
11883 (string-to-char (downcase (match-string 4 ans)))))
11884 (if (and (= hour 12) (not pm))
11885 (setq hour 0)
11886 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11887 (setq ans (replace-match (format "%02d:%02d" hour minute)
11888 t t ans))))
11890 ;; Check if a time range is given as a duration
11891 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11892 (setq hour (string-to-number (match-string 1 ans))
11893 h2 (+ hour (string-to-number (match-string 3 ans)))
11894 minute (string-to-number (match-string 2 ans))
11895 m2 (+ minute (if (match-end 5) (string-to-number
11896 (match-string 5 ans))0)))
11897 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11898 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11899 t t ans)))
11901 ;; Check if there is a time range
11902 (when (boundp 'org-end-time-was-given)
11903 (setq org-time-was-given nil)
11904 (when (and (string-match org-plain-time-of-day-regexp ans)
11905 (match-end 8))
11906 (setq org-end-time-was-given (match-string 8 ans))
11907 (setq ans (concat (substring ans 0 (match-beginning 7))
11908 (substring ans (match-end 7))))))
11910 (setq tl (parse-time-string ans)
11911 day (or (nth 3 tl) (nth 3 defdecode))
11912 month (or (nth 4 tl)
11913 (if (and org-read-date-prefer-future
11914 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11915 (1+ (nth 4 defdecode))
11916 (nth 4 defdecode)))
11917 year (or (nth 5 tl)
11918 (if (and org-read-date-prefer-future
11919 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11920 (1+ (nth 5 defdecode))
11921 (nth 5 defdecode)))
11922 hour (or (nth 2 tl) (nth 2 defdecode))
11923 minute (or (nth 1 tl) (nth 1 defdecode))
11924 second (or (nth 0 tl) 0)
11925 wday (nth 6 tl))
11927 ;; Special date definitions below
11928 (cond
11929 (iso-week
11930 ;; There was an iso week
11931 (setq year (or iso-year year)
11932 day (or iso-weekday wday 1)
11933 wday nil ; to make sure that the trigger below does not match
11934 iso-date (calendar-gregorian-from-absolute
11935 (calendar-absolute-from-iso
11936 (list iso-week day year))))
11937 ; FIXME: Should we also push ISO weeks into the future?
11938 ; (when (and org-read-date-prefer-future
11939 ; (not iso-year)
11940 ; (< (calendar-absolute-from-gregorian iso-date)
11941 ; (time-to-days (current-time))))
11942 ; (setq year (1+ year)
11943 ; iso-date (calendar-gregorian-from-absolute
11944 ; (calendar-absolute-from-iso
11945 ; (list iso-week day year)))))
11946 (setq month (car iso-date)
11947 year (nth 2 iso-date)
11948 day (nth 1 iso-date)))
11949 (deltan
11950 (unless deltadef
11951 (let ((now (decode-time (current-time))))
11952 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11953 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11954 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11955 ((equal deltaw "m") (setq month (+ month deltan)))
11956 ((equal deltaw "y") (setq year (+ year deltan)))))
11957 ((and wday (not (nth 3 tl)))
11958 ;; Weekday was given, but no day, so pick that day in the week
11959 ;; on or after the derived date.
11960 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11961 (unless (equal wday wday1)
11962 (setq day (+ day (% (- wday wday1 -7) 7))))))
11963 (if (and (boundp 'org-time-was-given)
11964 (nth 2 tl))
11965 (setq org-time-was-given t))
11966 (if (< year 100) (setq year (+ 2000 year)))
11967 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11968 (list second minute hour day month year)))
11970 (defvar parse-time-weekdays)
11972 (defun org-read-date-get-relative (s today default)
11973 "Check string S for special relative date string.
11974 TODAY and DEFAULT are internal times, for today and for a default.
11975 Return shift list (N what def-flag)
11976 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11977 N is the number of WHATs to shift.
11978 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11979 the DEFAULT date rather than TODAY."
11980 (when (and
11981 (string-match
11982 (concat
11983 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11984 "\\([0-9]+\\)?"
11985 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11986 "\\([ \t]\\|$\\)") s)
11987 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11988 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11989 (string-to-char (substring (match-string 1 s) -1))
11990 ?+))
11991 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11992 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11993 (what (if (match-end 3) (match-string 3 s) "d"))
11994 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11995 (date (if rel default today))
11996 (wday (nth 6 (decode-time date)))
11997 delta)
11998 (if wday1
11999 (progn
12000 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12001 (if (= dir ?-) (setq delta (- delta 7)))
12002 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12003 (list delta "d" rel))
12004 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12006 (defun org-eval-in-calendar (form &optional keepdate)
12007 "Eval FORM in the calendar window and return to current window.
12008 Also, store the cursor date in variable org-ans2."
12009 (let ((sw (selected-window)))
12010 (select-window (get-buffer-window "*Calendar*"))
12011 (eval form)
12012 (when (and (not keepdate) (calendar-cursor-to-date))
12013 (let* ((date (calendar-cursor-to-date))
12014 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12015 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12016 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12017 (select-window sw)))
12019 (defun org-calendar-select ()
12020 "Return to `org-read-date' with the date currently selected.
12021 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12022 (interactive)
12023 (when (calendar-cursor-to-date)
12024 (let* ((date (calendar-cursor-to-date))
12025 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12026 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12027 (if (active-minibuffer-window) (exit-minibuffer))))
12029 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12030 "Insert a date stamp for the date given by the internal TIME.
12031 WITH-HM means, use the stamp format that includes the time of the day.
12032 INACTIVE means use square brackets instead of angular ones, so that the
12033 stamp will not contribute to the agenda.
12034 PRE and POST are optional strings to be inserted before and after the
12035 stamp.
12036 The command returns the inserted time stamp."
12037 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12038 stamp)
12039 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12040 (insert-before-markers (or pre ""))
12041 (insert-before-markers (setq stamp (format-time-string fmt time)))
12042 (when (listp extra)
12043 (setq extra (car extra))
12044 (if (and (stringp extra)
12045 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12046 (setq extra (format "-%02d:%02d"
12047 (string-to-number (match-string 1 extra))
12048 (string-to-number (match-string 2 extra))))
12049 (setq extra nil)))
12050 (when extra
12051 (backward-char 1)
12052 (insert-before-markers extra)
12053 (forward-char 1))
12054 (insert-before-markers (or post ""))
12055 (setq org-last-inserted-timestamp stamp)))
12057 (defun org-toggle-time-stamp-overlays ()
12058 "Toggle the use of custom time stamp formats."
12059 (interactive)
12060 (setq org-display-custom-times (not org-display-custom-times))
12061 (unless org-display-custom-times
12062 (let ((p (point-min)) (bmp (buffer-modified-p)))
12063 (while (setq p (next-single-property-change p 'display))
12064 (if (and (get-text-property p 'display)
12065 (eq (get-text-property p 'face) 'org-date))
12066 (remove-text-properties
12067 p (setq p (next-single-property-change p 'display))
12068 '(display t))))
12069 (set-buffer-modified-p bmp)))
12070 (if (featurep 'xemacs)
12071 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12072 (org-restart-font-lock)
12073 (setq org-table-may-need-update t)
12074 (if org-display-custom-times
12075 (message "Time stamps are overlayed with custom format")
12076 (message "Time stamp overlays removed")))
12078 (defun org-display-custom-time (beg end)
12079 "Overlay modified time stamp format over timestamp between BEG and END."
12080 (let* ((ts (buffer-substring beg end))
12081 t1 w1 with-hm tf time str w2 (off 0))
12082 (save-match-data
12083 (setq t1 (org-parse-time-string ts t))
12084 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12085 (setq off (- (match-end 0) (match-beginning 0)))))
12086 (setq end (- end off))
12087 (setq w1 (- end beg)
12088 with-hm (and (nth 1 t1) (nth 2 t1))
12089 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12090 time (org-fix-decoded-time t1)
12091 str (org-add-props
12092 (format-time-string
12093 (substring tf 1 -1) (apply 'encode-time time))
12094 nil 'mouse-face 'highlight)
12095 w2 (length str))
12096 (if (not (= w2 w1))
12097 (add-text-properties (1+ beg) (+ 2 beg)
12098 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12099 (if (featurep 'xemacs)
12100 (progn
12101 (put-text-property beg end 'invisible t)
12102 (put-text-property beg end 'end-glyph (make-glyph str)))
12103 (put-text-property beg end 'display str))))
12105 (defun org-translate-time (string)
12106 "Translate all timestamps in STRING to custom format.
12107 But do this only if the variable `org-display-custom-times' is set."
12108 (when org-display-custom-times
12109 (save-match-data
12110 (let* ((start 0)
12111 (re org-ts-regexp-both)
12112 t1 with-hm inactive tf time str beg end)
12113 (while (setq start (string-match re string start))
12114 (setq beg (match-beginning 0)
12115 end (match-end 0)
12116 t1 (save-match-data
12117 (org-parse-time-string (substring string beg end) t))
12118 with-hm (and (nth 1 t1) (nth 2 t1))
12119 inactive (equal (substring string beg (1+ beg)) "[")
12120 tf (funcall (if with-hm 'cdr 'car)
12121 org-time-stamp-custom-formats)
12122 time (org-fix-decoded-time t1)
12123 str (format-time-string
12124 (concat
12125 (if inactive "[" "<") (substring tf 1 -1)
12126 (if inactive "]" ">"))
12127 (apply 'encode-time time))
12128 string (replace-match str t t string)
12129 start (+ start (length str)))))))
12130 string)
12132 (defun org-fix-decoded-time (time)
12133 "Set 0 instead of nil for the first 6 elements of time.
12134 Don't touch the rest."
12135 (let ((n 0))
12136 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12138 (defun org-days-to-time (timestamp-string)
12139 "Difference between TIMESTAMP-STRING and now in days."
12140 (- (time-to-days (org-time-string-to-time timestamp-string))
12141 (time-to-days (current-time))))
12143 (defun org-deadline-close (timestamp-string &optional ndays)
12144 "Is the time in TIMESTAMP-STRING close to the current date?"
12145 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12146 (and (< (org-days-to-time timestamp-string) ndays)
12147 (not (org-entry-is-done-p))))
12149 (defun org-get-wdays (ts)
12150 "Get the deadline lead time appropriate for timestring TS."
12151 (cond
12152 ((<= org-deadline-warning-days 0)
12153 ;; 0 or negative, enforce this value no matter what
12154 (- org-deadline-warning-days))
12155 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12156 ;; lead time is specified.
12157 (floor (* (string-to-number (match-string 1 ts))
12158 (cdr (assoc (match-string 2 ts)
12159 '(("d" . 1) ("w" . 7)
12160 ("m" . 30.4) ("y" . 365.25)))))))
12161 ;; go for the default.
12162 (t org-deadline-warning-days)))
12164 (defun org-calendar-select-mouse (ev)
12165 "Return to `org-read-date' with the date currently selected.
12166 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12167 (interactive "e")
12168 (mouse-set-point ev)
12169 (when (calendar-cursor-to-date)
12170 (let* ((date (calendar-cursor-to-date))
12171 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12172 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12173 (if (active-minibuffer-window) (exit-minibuffer))))
12175 (defun org-check-deadlines (ndays)
12176 "Check if there are any deadlines due or past due.
12177 A deadline is considered due if it happens within `org-deadline-warning-days'
12178 days from today's date. If the deadline appears in an entry marked DONE,
12179 it is not shown. The prefix arg NDAYS can be used to test that many
12180 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12181 (interactive "P")
12182 (let* ((org-warn-days
12183 (cond
12184 ((equal ndays '(4)) 100000)
12185 (ndays (prefix-numeric-value ndays))
12186 (t (abs org-deadline-warning-days))))
12187 (case-fold-search nil)
12188 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12189 (callback
12190 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12192 (message "%d deadlines past-due or due within %d days"
12193 (org-occur regexp nil callback)
12194 org-warn-days)))
12196 (defun org-check-before-date (date)
12197 "Check if there are deadlines or scheduled entries before DATE."
12198 (interactive (list (org-read-date)))
12199 (let ((case-fold-search nil)
12200 (regexp (concat "\\<\\(" org-deadline-string
12201 "\\|" org-scheduled-string
12202 "\\) *<\\([^>]+\\)>"))
12203 (callback
12204 (lambda () (time-less-p
12205 (org-time-string-to-time (match-string 2))
12206 (org-time-string-to-time date)))))
12207 (message "%d entries before %s"
12208 (org-occur regexp nil callback) date)))
12210 (defun org-check-after-date (date)
12211 "Check if there are deadlines or scheduled entries after DATE."
12212 (interactive (list (org-read-date)))
12213 (let ((case-fold-search nil)
12214 (regexp (concat "\\<\\(" org-deadline-string
12215 "\\|" org-scheduled-string
12216 "\\) *<\\([^>]+\\)>"))
12217 (callback
12218 (lambda () (not
12219 (time-less-p
12220 (org-time-string-to-time (match-string 2))
12221 (org-time-string-to-time date))))))
12222 (message "%d entries after %s"
12223 (org-occur regexp nil callback) date)))
12225 (defun org-evaluate-time-range (&optional to-buffer)
12226 "Evaluate a time range by computing the difference between start and end.
12227 Normally the result is just printed in the echo area, but with prefix arg
12228 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12229 If the time range is actually in a table, the result is inserted into the
12230 next column.
12231 For time difference computation, a year is assumed to be exactly 365
12232 days in order to avoid rounding problems."
12233 (interactive "P")
12235 (org-clock-update-time-maybe)
12236 (save-excursion
12237 (unless (org-at-date-range-p t)
12238 (goto-char (point-at-bol))
12239 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12240 (if (not (org-at-date-range-p t))
12241 (error "Not at a time-stamp range, and none found in current line")))
12242 (let* ((ts1 (match-string 1))
12243 (ts2 (match-string 2))
12244 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12245 (match-end (match-end 0))
12246 (time1 (org-time-string-to-time ts1))
12247 (time2 (org-time-string-to-time ts2))
12248 (t1 (time-to-seconds time1))
12249 (t2 (time-to-seconds time2))
12250 (diff (abs (- t2 t1)))
12251 (negative (< (- t2 t1) 0))
12252 ;; (ys (floor (* 365 24 60 60)))
12253 (ds (* 24 60 60))
12254 (hs (* 60 60))
12255 (fy "%dy %dd %02d:%02d")
12256 (fy1 "%dy %dd")
12257 (fd "%dd %02d:%02d")
12258 (fd1 "%dd")
12259 (fh "%02d:%02d")
12260 y d h m align)
12261 (if havetime
12262 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12264 d (floor (/ diff ds)) diff (mod diff ds)
12265 h (floor (/ diff hs)) diff (mod diff hs)
12266 m (floor (/ diff 60)))
12267 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12269 d (floor (+ (/ diff ds) 0.5))
12270 h 0 m 0))
12271 (if (not to-buffer)
12272 (message "%s" (org-make-tdiff-string y d h m))
12273 (if (org-at-table-p)
12274 (progn
12275 (goto-char match-end)
12276 (setq align t)
12277 (and (looking-at " *|") (goto-char (match-end 0))))
12278 (goto-char match-end))
12279 (if (looking-at
12280 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12281 (replace-match ""))
12282 (if negative (insert " -"))
12283 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12284 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12285 (insert " " (format fh h m))))
12286 (if align (org-table-align))
12287 (message "Time difference inserted")))))
12289 (defun org-make-tdiff-string (y d h m)
12290 (let ((fmt "")
12291 (l nil))
12292 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12293 l (push y l)))
12294 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12295 l (push d l)))
12296 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12297 l (push h l)))
12298 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12299 l (push m l)))
12300 (apply 'format fmt (nreverse l))))
12302 (defun org-time-string-to-time (s)
12303 (apply 'encode-time (org-parse-time-string s)))
12305 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12306 "Convert a time stamp to an absolute day number.
12307 If there is a specifyer for a cyclic time stamp, get the closest date to
12308 DAYNR.
12309 PREFER and SHOW-ALL are passed through to `org-closest-date'."
12310 (cond
12311 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12312 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12313 daynr
12314 (+ daynr 1000)))
12315 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12316 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12317 (time-to-days (current-time))) (match-string 0 s)
12318 prefer show-all))
12319 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12321 (defun org-days-to-iso-week (days)
12322 "Return the iso week number."
12323 (require 'cal-iso)
12324 (car (calendar-iso-from-absolute days)))
12326 (defun org-small-year-to-year (year)
12327 "Convert 2-digit years into 4-digit years.
12328 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12329 The year 2000 cannot be abbreviated. Any year larger than 99
12330 is returned unchanged."
12331 (if (< year 38)
12332 (setq year (+ 2000 year))
12333 (if (< year 100)
12334 (setq year (+ 1900 year))))
12335 year)
12337 (defun org-time-from-absolute (d)
12338 "Return the time corresponding to date D.
12339 D may be an absolute day number, or a calendar-type list (month day year)."
12340 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12341 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12343 (defun org-calendar-holiday ()
12344 "List of holidays, for Diary display in Org-mode."
12345 (require 'holidays)
12346 (let ((hl (funcall
12347 (if (fboundp 'calendar-check-holidays)
12348 'calendar-check-holidays 'check-calendar-holidays) date)))
12349 (if hl (mapconcat 'identity hl "; "))))
12351 (defun org-diary-sexp-entry (sexp entry date)
12352 "Process a SEXP diary ENTRY for DATE."
12353 (require 'diary-lib)
12354 (let ((result (if calendar-debug-sexp
12355 (let ((stack-trace-on-error t))
12356 (eval (car (read-from-string sexp))))
12357 (condition-case nil
12358 (eval (car (read-from-string sexp)))
12359 (error
12360 (beep)
12361 (message "Bad sexp at line %d in %s: %s"
12362 (org-current-line)
12363 (buffer-file-name) sexp)
12364 (sleep-for 2))))))
12365 (cond ((stringp result) result)
12366 ((and (consp result)
12367 (stringp (cdr result))) (cdr result))
12368 (result entry)
12369 (t nil))))
12371 (defun org-diary-to-ical-string (frombuf)
12372 "Get iCalendar entries from diary entries in buffer FROMBUF.
12373 This uses the icalendar.el library."
12374 (let* ((tmpdir (if (featurep 'xemacs)
12375 (temp-directory)
12376 temporary-file-directory))
12377 (tmpfile (make-temp-name
12378 (expand-file-name "orgics" tmpdir)))
12379 buf rtn b e)
12380 (save-excursion
12381 (set-buffer frombuf)
12382 (icalendar-export-region (point-min) (point-max) tmpfile)
12383 (setq buf (find-buffer-visiting tmpfile))
12384 (set-buffer buf)
12385 (goto-char (point-min))
12386 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12387 (setq b (match-beginning 0)))
12388 (goto-char (point-max))
12389 (if (re-search-backward "^END:VEVENT" nil t)
12390 (setq e (match-end 0)))
12391 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12392 (kill-buffer buf)
12393 (delete-file tmpfile)
12394 rtn))
12396 (defun org-closest-date (start current change prefer show-all)
12397 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12398 When PREFER is `past' return a date that is either CURRENT or past.
12399 When PREFER is `future', return a date that is either CURRENT or future.
12400 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12401 ;; Make the proper lists from the dates
12402 (catch 'exit
12403 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12404 dn dw sday cday n1 n2 n0
12405 d m y y1 y2 date1 date2 nmonths nm ny m2)
12407 (setq start (org-date-to-gregorian start)
12408 current (org-date-to-gregorian
12409 (if show-all
12410 current
12411 (time-to-days (current-time))))
12412 sday (calendar-absolute-from-gregorian start)
12413 cday (calendar-absolute-from-gregorian current))
12415 (if (<= cday sday) (throw 'exit sday))
12417 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12418 (setq dn (string-to-number (match-string 1 change))
12419 dw (cdr (assoc (match-string 2 change) a1)))
12420 (error "Invalid change specifyer: %s" change))
12421 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12422 (cond
12423 ((eq dw 'day)
12424 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12425 n2 (+ n1 dn)))
12426 ((eq dw 'year)
12427 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12428 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12429 (setq date1 (list m d y1)
12430 n1 (calendar-absolute-from-gregorian date1)
12431 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12432 n2 (calendar-absolute-from-gregorian date2)))
12433 ((eq dw 'month)
12434 ;; approx number of month between the two dates
12435 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12436 ;; How often does dn fit in there?
12437 (setq d (nth 1 start) m (car start) y (nth 2 start)
12438 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12439 m (+ m nm)
12440 ny (floor (/ m 12))
12441 y (+ y ny)
12442 m (- m (* ny 12)))
12443 (while (> m 12) (setq m (- m 12) y (1+ y)))
12444 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12445 (setq m2 (+ m dn) y2 y)
12446 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12447 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12448 (while (<= n2 cday)
12449 (setq n1 n2 m m2 y y2)
12450 (setq m2 (+ m dn) y2 y)
12451 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12452 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12453 ;; Make sure n1 is the earlier date
12454 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12455 (if show-all
12456 (cond
12457 ((eq prefer 'past) n1)
12458 ((eq prefer 'future) (if (= cday n1) n1 n2))
12459 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12460 (cond
12461 ((eq prefer 'past) n1)
12462 ((eq prefer 'future) (if (= cday n1) n1 n2))
12463 (t (if (= cday n1) n1 n2)))))))
12465 (defun org-date-to-gregorian (date)
12466 "Turn any specification of DATE into a gregorian date for the calendar."
12467 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12468 ((and (listp date) (= (length date) 3)) date)
12469 ((stringp date)
12470 (setq date (org-parse-time-string date))
12471 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12472 ((listp date)
12473 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12475 (defun org-parse-time-string (s &optional nodefault)
12476 "Parse the standard Org-mode time string.
12477 This should be a lot faster than the normal `parse-time-string'.
12478 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12479 hour and minute fields will be nil if not given."
12480 (if (string-match org-ts-regexp0 s)
12481 (list 0
12482 (if (or (match-beginning 8) (not nodefault))
12483 (string-to-number (or (match-string 8 s) "0")))
12484 (if (or (match-beginning 7) (not nodefault))
12485 (string-to-number (or (match-string 7 s) "0")))
12486 (string-to-number (match-string 4 s))
12487 (string-to-number (match-string 3 s))
12488 (string-to-number (match-string 2 s))
12489 nil nil nil)
12490 (make-list 9 0)))
12492 (defun org-timestamp-up (&optional arg)
12493 "Increase the date item at the cursor by one.
12494 If the cursor is on the year, change the year. If it is on the month or
12495 the day, change that.
12496 With prefix ARG, change by that many units."
12497 (interactive "p")
12498 (org-timestamp-change (prefix-numeric-value arg)))
12500 (defun org-timestamp-down (&optional arg)
12501 "Decrease the date item at the cursor by one.
12502 If the cursor is on the year, change the year. If it is on the month or
12503 the day, change that.
12504 With prefix ARG, change by that many units."
12505 (interactive "p")
12506 (org-timestamp-change (- (prefix-numeric-value arg))))
12508 (defun org-timestamp-up-day (&optional arg)
12509 "Increase the date in the time stamp by one day.
12510 With prefix ARG, change that many days."
12511 (interactive "p")
12512 (if (and (not (org-at-timestamp-p t))
12513 (org-on-heading-p))
12514 (org-todo 'up)
12515 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12517 (defun org-timestamp-down-day (&optional arg)
12518 "Decrease the date in the time stamp by one day.
12519 With prefix ARG, change that many days."
12520 (interactive "p")
12521 (if (and (not (org-at-timestamp-p t))
12522 (org-on-heading-p))
12523 (org-todo 'down)
12524 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12526 (defun org-at-timestamp-p (&optional inactive-ok)
12527 "Determine if the cursor is in or at a timestamp."
12528 (interactive)
12529 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12530 (pos (point))
12531 (ans (or (looking-at tsr)
12532 (save-excursion
12533 (skip-chars-backward "^[<\n\r\t")
12534 (if (> (point) (point-min)) (backward-char 1))
12535 (and (looking-at tsr)
12536 (> (- (match-end 0) pos) -1))))))
12537 (and ans
12538 (boundp 'org-ts-what)
12539 (setq org-ts-what
12540 (cond
12541 ((= pos (match-beginning 0)) 'bracket)
12542 ((= pos (1- (match-end 0))) 'bracket)
12543 ((org-pos-in-match-range pos 2) 'year)
12544 ((org-pos-in-match-range pos 3) 'month)
12545 ((org-pos-in-match-range pos 7) 'hour)
12546 ((org-pos-in-match-range pos 8) 'minute)
12547 ((or (org-pos-in-match-range pos 4)
12548 (org-pos-in-match-range pos 5)) 'day)
12549 ((and (> pos (or (match-end 8) (match-end 5)))
12550 (< pos (match-end 0)))
12551 (- pos (or (match-end 8) (match-end 5))))
12552 (t 'day))))
12553 ans))
12555 (defun org-toggle-timestamp-type ()
12556 "Toggle the type (<active> or [inactive]) of a time stamp."
12557 (interactive)
12558 (when (org-at-timestamp-p t)
12559 (let ((beg (match-beginning 0)) (end (match-end 0))
12560 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12561 (save-excursion
12562 (goto-char beg)
12563 (while (re-search-forward "[][<>]" end t)
12564 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12565 t t)))
12566 (message "Timestamp is now %sactive"
12567 (if (equal (char-after beg) ?<) "" "in")))))
12569 (defun org-timestamp-change (n &optional what)
12570 "Change the date in the time stamp at point.
12571 The date will be changed by N times WHAT. WHAT can be `day', `month',
12572 `year', `minute', `second'. If WHAT is not given, the cursor position
12573 in the timestamp determines what will be changed."
12574 (let ((pos (point))
12575 with-hm inactive
12576 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12577 org-ts-what
12578 extra rem
12579 ts time time0)
12580 (if (not (org-at-timestamp-p t))
12581 (error "Not at a timestamp"))
12582 (if (and (not what) (eq org-ts-what 'bracket))
12583 (org-toggle-timestamp-type)
12584 (if (and (not what) (not (eq org-ts-what 'day))
12585 org-display-custom-times
12586 (get-text-property (point) 'display)
12587 (not (get-text-property (1- (point)) 'display)))
12588 (setq org-ts-what 'day))
12589 (setq org-ts-what (or what org-ts-what)
12590 inactive (= (char-after (match-beginning 0)) ?\[)
12591 ts (match-string 0))
12592 (replace-match "")
12593 (if (string-match
12594 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12596 (setq extra (match-string 1 ts)))
12597 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12598 (setq with-hm t))
12599 (setq time0 (org-parse-time-string ts))
12600 (when (and (eq org-ts-what 'minute)
12601 (eq current-prefix-arg nil))
12602 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12603 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12604 (setcar (cdr time0) (+ (nth 1 time0)
12605 (if (> n 0) (- rem) (- dm rem))))))
12606 (setq time
12607 (encode-time (or (car time0) 0)
12608 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12609 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12610 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12611 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12612 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12613 (nthcdr 6 time0)))
12614 (when (and (member org-ts-what '(hour minute))
12615 extra
12616 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
12617 (setq extra (org-modify-ts-extra
12618 extra
12619 (if (eq org-ts-what 'hour) 2 5)
12620 n dm)))
12621 (when (integerp org-ts-what)
12622 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12623 (if (eq what 'calendar)
12624 (let ((cal-date (org-get-date-from-calendar)))
12625 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12626 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12627 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12628 (setcar time0 (or (car time0) 0))
12629 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12630 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12631 (setq time (apply 'encode-time time0))))
12632 (setq org-last-changed-timestamp
12633 (org-insert-time-stamp time with-hm inactive nil nil extra))
12634 (org-clock-update-time-maybe)
12635 (goto-char pos)
12636 ;; Try to recenter the calendar window, if any
12637 (if (and org-calendar-follow-timestamp-change
12638 (get-buffer-window "*Calendar*" t)
12639 (memq org-ts-what '(day month year)))
12640 (org-recenter-calendar (time-to-days time))))))
12642 (defun org-modify-ts-extra (s pos n dm)
12643 "Change the different parts of the lead-time and repeat fields in timestamp."
12644 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12645 ng h m new rem)
12646 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12647 (cond
12648 ((or (org-pos-in-match-range pos 2)
12649 (org-pos-in-match-range pos 3))
12650 (setq m (string-to-number (match-string 3 s))
12651 h (string-to-number (match-string 2 s)))
12652 (if (org-pos-in-match-range pos 2)
12653 (setq h (+ h n))
12654 (setq n (* dm (org-no-warnings (signum n))))
12655 (when (not (= 0 (setq rem (% m dm))))
12656 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12657 (setq m (+ m n)))
12658 (if (< m 0) (setq m (+ m 60) h (1- h)))
12659 (if (> m 59) (setq m (- m 60) h (1+ h)))
12660 (setq h (min 24 (max 0 h)))
12661 (setq ng 1 new (format "-%02d:%02d" h m)))
12662 ((org-pos-in-match-range pos 6)
12663 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12664 ((org-pos-in-match-range pos 5)
12665 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12667 ((org-pos-in-match-range pos 9)
12668 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12669 ((org-pos-in-match-range pos 8)
12670 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12672 (when ng
12673 (setq s (concat
12674 (substring s 0 (match-beginning ng))
12676 (substring s (match-end ng))))))
12679 (defun org-recenter-calendar (date)
12680 "If the calendar is visible, recenter it to DATE."
12681 (let* ((win (selected-window))
12682 (cwin (get-buffer-window "*Calendar*" t))
12683 (calendar-move-hook nil))
12684 (when cwin
12685 (select-window cwin)
12686 (calendar-goto-date (if (listp date) date
12687 (calendar-gregorian-from-absolute date)))
12688 (select-window win))))
12690 (defun org-goto-calendar (&optional arg)
12691 "Go to the Emacs calendar at the current date.
12692 If there is a time stamp in the current line, go to that date.
12693 A prefix ARG can be used to force the current date."
12694 (interactive "P")
12695 (let ((tsr org-ts-regexp) diff
12696 (calendar-move-hook nil)
12697 (calendar-view-holidays-initially-flag nil)
12698 (view-calendar-holidays-initially nil)
12699 (calendar-view-diary-initially-flag nil)
12700 (view-diary-entries-initially nil))
12701 (if (or (org-at-timestamp-p)
12702 (save-excursion
12703 (beginning-of-line 1)
12704 (looking-at (concat ".*" tsr))))
12705 (let ((d1 (time-to-days (current-time)))
12706 (d2 (time-to-days
12707 (org-time-string-to-time (match-string 1)))))
12708 (setq diff (- d2 d1))))
12709 (calendar)
12710 (calendar-goto-today)
12711 (if (and diff (not arg)) (calendar-forward-day diff))))
12713 (defun org-get-date-from-calendar ()
12714 "Return a list (month day year) of date at point in calendar."
12715 (with-current-buffer "*Calendar*"
12716 (save-match-data
12717 (calendar-cursor-to-date))))
12719 (defun org-date-from-calendar ()
12720 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12721 If there is already a time stamp at the cursor position, update it."
12722 (interactive)
12723 (if (org-at-timestamp-p t)
12724 (org-timestamp-change 0 'calendar)
12725 (let ((cal-date (org-get-date-from-calendar)))
12726 (org-insert-time-stamp
12727 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12729 (defun org-minutes-to-hh:mm-string (m)
12730 "Compute H:MM from a number of minutes."
12731 (let ((h (/ m 60)))
12732 (setq m (- m (* 60 h)))
12733 (format org-time-clocksum-format h m)))
12735 (defun org-hh:mm-string-to-minutes (s)
12736 "Convert a string H:MM to a number of minutes."
12737 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12738 (+ (* (string-to-number (match-string 1 s)) 60)
12739 (string-to-number (match-string 2 s)))
12742 ;;;; Files
12744 (defun org-save-all-org-buffers ()
12745 "Save all Org-mode buffers without user confirmation."
12746 (interactive)
12747 (message "Saving all Org-mode buffers...")
12748 (save-some-buffers t 'org-mode-p)
12749 (when (featurep 'org-id) (org-id-locations-save))
12750 (message "Saving all Org-mode buffers... done"))
12752 (defun org-revert-all-org-buffers ()
12753 "Revert all Org-mode buffers.
12754 Prompt for confirmation when there are unsaved changes.
12755 Be sure you know what you are doing before letting this function
12756 overwrite your changes.
12758 This function is useful in a setup where one tracks org files
12759 with a version control system, to revert on one machine after pulling
12760 changes from another. I believe the procedure must be like this:
12762 1. M-x org-save-all-org-buffers
12763 2. Pull changes from the other machine, resolve conflicts
12764 3. M-x org-revert-all-org-buffers"
12765 (interactive)
12766 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
12767 (error "Abort"))
12768 (save-excursion
12769 (save-window-excursion
12770 (mapc
12771 (lambda (b)
12772 (when (and (with-current-buffer b (org-mode-p))
12773 (with-current-buffer b buffer-file-name))
12774 (switch-to-buffer b)
12775 (revert-buffer t 'no-confirm)))
12776 (buffer-list))
12777 (when (and (featurep 'org-id) org-id-track-globally)
12778 (org-id-locations-load)))))
12780 ;;;; Agenda files
12782 ;;;###autoload
12783 (defun org-iswitchb (&optional arg)
12784 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12785 With a prefix argument, restrict available to files.
12786 With two prefix arguments, restrict available buffers to agenda files.
12788 Due to some yet unresolved reason, the global function
12789 `iswitchb-mode' needs to be active for this function to work."
12790 (interactive "P")
12791 (require 'iswitchb)
12792 (let ((enabled iswitchb-mode) blist)
12793 (or enabled (iswitchb-mode 1))
12794 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12795 ((equal arg '(16)) (org-buffer-list 'agenda))
12796 (t (org-buffer-list))))
12797 (unwind-protect
12798 (let ((iswitchb-make-buflist-hook
12799 (lambda ()
12800 (setq iswitchb-temp-buflist
12801 (mapcar 'buffer-name blist)))))
12802 (switch-to-buffer
12803 (iswitchb-read-buffer
12804 "Switch-to: " nil t))
12805 (or enabled (iswitchb-mode -1))))))
12807 ;;;###autoload
12808 (defun org-ido-switchb (&optional arg)
12809 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12810 With a prefix argument, restrict available to files.
12811 With two prefix arguments, restrict available buffers to agenda files."
12812 (interactive "P")
12813 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12814 ((equal arg '(16)) (org-buffer-list 'agenda))
12815 (t (org-buffer-list)))))
12816 (switch-to-buffer
12817 (org-ido-completing-read "Org buffer: "
12818 (mapcar 'list (mapcar 'buffer-name blist))
12819 nil t))))
12821 (defun org-buffer-list (&optional predicate exclude-tmp)
12822 "Return a list of Org buffers.
12823 PREDICATE can be `export', `files' or `agenda'.
12825 export restrict the list to Export buffers.
12826 files restrict the list to buffers visiting Org files.
12827 agenda restrict the list to buffers visiting agenda files.
12829 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12830 (let* ((bfn nil)
12831 (agenda-files (and (eq predicate 'agenda)
12832 (mapcar 'file-truename (org-agenda-files t))))
12833 (filter
12834 (cond
12835 ((eq predicate 'files)
12836 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12837 ((eq predicate 'export)
12838 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12839 ((eq predicate 'agenda)
12840 (lambda (b)
12841 (with-current-buffer b
12842 (and (eq major-mode 'org-mode)
12843 (setq bfn (buffer-file-name b))
12844 (member (file-truename bfn) agenda-files)))))
12845 (t (lambda (b) (with-current-buffer b
12846 (or (eq major-mode 'org-mode)
12847 (string-match "\*Org .*Export"
12848 (buffer-name b)))))))))
12849 (delq nil
12850 (mapcar
12851 (lambda(b)
12852 (if (and (funcall filter b)
12853 (or (not exclude-tmp)
12854 (not (string-match "tmp" (buffer-name b)))))
12856 nil))
12857 (buffer-list)))))
12859 (defun org-agenda-files (&optional unrestricted archives)
12860 "Get the list of agenda files.
12861 Optional UNRESTRICTED means return the full list even if a restriction
12862 is currently in place.
12863 When ARCHIVES is t, include all archive files hat are really being
12864 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12865 `org-agenda-archives-mode' is t."
12866 (let ((files
12867 (cond
12868 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12869 ((stringp org-agenda-files) (org-read-agenda-file-list))
12870 ((listp org-agenda-files) org-agenda-files)
12871 (t (error "Invalid value of `org-agenda-files'")))))
12872 (setq files (apply 'append
12873 (mapcar (lambda (f)
12874 (if (file-directory-p f)
12875 (directory-files
12876 f t org-agenda-file-regexp)
12877 (list f)))
12878 files)))
12879 (when org-agenda-skip-unavailable-files
12880 (setq files (delq nil
12881 (mapcar (function
12882 (lambda (file)
12883 (and (file-readable-p file) file)))
12884 files))))
12885 (when (or (eq archives t)
12886 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12887 (setq files (org-add-archive-files files)))
12888 files))
12890 (defun org-edit-agenda-file-list ()
12891 "Edit the list of agenda files.
12892 Depending on setup, this either uses customize to edit the variable
12893 `org-agenda-files', or it visits the file that is holding the list. In the
12894 latter case, the buffer is set up in a way that saving it automatically kills
12895 the buffer and restores the previous window configuration."
12896 (interactive)
12897 (if (stringp org-agenda-files)
12898 (let ((cw (current-window-configuration)))
12899 (find-file org-agenda-files)
12900 (org-set-local 'org-window-configuration cw)
12901 (org-add-hook 'after-save-hook
12902 (lambda ()
12903 (set-window-configuration
12904 (prog1 org-window-configuration
12905 (kill-buffer (current-buffer))))
12906 (org-install-agenda-files-menu)
12907 (message "New agenda file list installed"))
12908 nil 'local)
12909 (message "%s" (substitute-command-keys
12910 "Edit list and finish with \\[save-buffer]")))
12911 (customize-variable 'org-agenda-files)))
12913 (defun org-store-new-agenda-file-list (list)
12914 "Set new value for the agenda file list and save it correctly."
12915 (if (stringp org-agenda-files)
12916 (let ((f org-agenda-files) b)
12917 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12918 (with-temp-file f
12919 (insert (mapconcat 'identity list "\n") "\n")))
12920 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12921 (setq org-agenda-files list)
12922 (customize-save-variable 'org-agenda-files org-agenda-files))))
12924 (defun org-read-agenda-file-list ()
12925 "Read the list of agenda files from a file."
12926 (when (file-directory-p org-agenda-files)
12927 (error "`org-agenda-files' cannot be a single directory"))
12928 (when (stringp org-agenda-files)
12929 (with-temp-buffer
12930 (insert-file-contents org-agenda-files)
12931 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12934 ;;;###autoload
12935 (defun org-cycle-agenda-files ()
12936 "Cycle through the files in `org-agenda-files'.
12937 If the current buffer visits an agenda file, find the next one in the list.
12938 If the current buffer does not, find the first agenda file."
12939 (interactive)
12940 (let* ((fs (org-agenda-files t))
12941 (files (append fs (list (car fs))))
12942 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12943 file)
12944 (unless files (error "No agenda files"))
12945 (catch 'exit
12946 (while (setq file (pop files))
12947 (if (equal (file-truename file) tcf)
12948 (when (car files)
12949 (find-file (car files))
12950 (throw 'exit t))))
12951 (find-file (car fs)))
12952 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12954 (defun org-agenda-file-to-front (&optional to-end)
12955 "Move/add the current file to the top of the agenda file list.
12956 If the file is not present in the list, it is added to the front. If it is
12957 present, it is moved there. With optional argument TO-END, add/move to the
12958 end of the list."
12959 (interactive "P")
12960 (let ((org-agenda-skip-unavailable-files nil)
12961 (file-alist (mapcar (lambda (x)
12962 (cons (file-truename x) x))
12963 (org-agenda-files t)))
12964 (ctf (file-truename buffer-file-name))
12965 x had)
12966 (setq x (assoc ctf file-alist) had x)
12968 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12969 (if to-end
12970 (setq file-alist (append (delq x file-alist) (list x)))
12971 (setq file-alist (cons x (delq x file-alist))))
12972 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12973 (org-install-agenda-files-menu)
12974 (message "File %s to %s of agenda file list"
12975 (if had "moved" "added") (if to-end "end" "front"))))
12977 (defun org-remove-file (&optional file)
12978 "Remove current file from the list of files in variable `org-agenda-files'.
12979 These are the files which are being checked for agenda entries.
12980 Optional argument FILE means, use this file instead of the current."
12981 (interactive)
12982 (let* ((org-agenda-skip-unavailable-files nil)
12983 (file (or file buffer-file-name))
12984 (true-file (file-truename file))
12985 (afile (abbreviate-file-name file))
12986 (files (delq nil (mapcar
12987 (lambda (x)
12988 (if (equal true-file
12989 (file-truename x))
12990 nil x))
12991 (org-agenda-files t)))))
12992 (if (not (= (length files) (length (org-agenda-files t))))
12993 (progn
12994 (org-store-new-agenda-file-list files)
12995 (org-install-agenda-files-menu)
12996 (message "Removed file: %s" afile))
12997 (message "File was not in list: %s (not removed)" afile))))
12999 (defun org-file-menu-entry (file)
13000 (vector file (list 'find-file file) t))
13002 (defun org-check-agenda-file (file)
13003 "Make sure FILE exists. If not, ask user what to do."
13004 (when (not (file-exists-p file))
13005 (message "non-existent file %s. [R]emove from list or [A]bort?"
13006 (abbreviate-file-name file))
13007 (let ((r (downcase (read-char-exclusive))))
13008 (cond
13009 ((equal r ?r)
13010 (org-remove-file file)
13011 (throw 'nextfile t))
13012 (t (error "Abort"))))))
13014 (defun org-get-agenda-file-buffer (file)
13015 "Get a buffer visiting FILE. If the buffer needs to be created, add
13016 it to the list of buffers which might be released later."
13017 (let ((buf (org-find-base-buffer-visiting file)))
13018 (if buf
13019 buf ; just return it
13020 ;; Make a new buffer and remember it
13021 (setq buf (find-file-noselect file))
13022 (if buf (push buf org-agenda-new-buffers))
13023 buf)))
13025 (defun org-release-buffers (blist)
13026 "Release all buffers in list, asking the user for confirmation when needed.
13027 When a buffer is unmodified, it is just killed. When modified, it is saved
13028 \(if the user agrees) and then killed."
13029 (let (buf file)
13030 (while (setq buf (pop blist))
13031 (setq file (buffer-file-name buf))
13032 (when (and (buffer-modified-p buf)
13033 file
13034 (y-or-n-p (format "Save file %s? " file)))
13035 (with-current-buffer buf (save-buffer)))
13036 (kill-buffer buf))))
13038 (defun org-prepare-agenda-buffers (files)
13039 "Create buffers for all agenda files, protect archived trees and comments."
13040 (interactive)
13041 (let ((pa '(:org-archived t))
13042 (pc '(:org-comment t))
13043 (pall '(:org-archived t :org-comment t))
13044 (inhibit-read-only t)
13045 (rea (concat ":" org-archive-tag ":"))
13046 bmp file re)
13047 (save-excursion
13048 (save-restriction
13049 (while (setq file (pop files))
13050 (if (bufferp file)
13051 (set-buffer file)
13052 (org-check-agenda-file file)
13053 (set-buffer (org-get-agenda-file-buffer file)))
13054 (widen)
13055 (setq bmp (buffer-modified-p))
13056 (org-refresh-category-properties)
13057 (setq org-todo-keywords-for-agenda
13058 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13059 (setq org-done-keywords-for-agenda
13060 (append org-done-keywords-for-agenda org-done-keywords))
13061 (setq org-todo-keyword-alist-for-agenda
13062 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13063 (setq org-tag-alist-for-agenda
13064 (append org-tag-alist-for-agenda org-tag-alist))
13066 (save-excursion
13067 (remove-text-properties (point-min) (point-max) pall)
13068 (when org-agenda-skip-archived-trees
13069 (goto-char (point-min))
13070 (while (re-search-forward rea nil t)
13071 (if (org-on-heading-p t)
13072 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13073 (goto-char (point-min))
13074 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13075 (while (re-search-forward re nil t)
13076 (add-text-properties
13077 (match-beginning 0) (org-end-of-subtree t) pc)))
13078 (set-buffer-modified-p bmp))))
13079 (setq org-todo-keyword-alist-for-agenda
13080 (org-uniquify org-todo-keyword-alist-for-agenda)
13081 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13083 ;;;; Embedded LaTeX
13085 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13086 "Keymap for the minor `org-cdlatex-mode'.")
13088 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13089 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13090 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13091 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13092 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13094 (defvar org-cdlatex-texmathp-advice-is-done nil
13095 "Flag remembering if we have applied the advice to texmathp already.")
13097 (define-minor-mode org-cdlatex-mode
13098 "Toggle the minor `org-cdlatex-mode'.
13099 This mode supports entering LaTeX environment and math in LaTeX fragments
13100 in Org-mode.
13101 \\{org-cdlatex-mode-map}"
13102 nil " OCDL" nil
13103 (when org-cdlatex-mode (require 'cdlatex))
13104 (unless org-cdlatex-texmathp-advice-is-done
13105 (setq org-cdlatex-texmathp-advice-is-done t)
13106 (defadvice texmathp (around org-math-always-on activate)
13107 "Always return t in org-mode buffers.
13108 This is because we want to insert math symbols without dollars even outside
13109 the LaTeX math segments. If Orgmode thinks that point is actually inside
13110 an embedded LaTeX fragment, let texmathp do its job.
13111 \\[org-cdlatex-mode-map]"
13112 (interactive)
13113 (let (p)
13114 (cond
13115 ((not (org-mode-p)) ad-do-it)
13116 ((eq this-command 'cdlatex-math-symbol)
13117 (setq ad-return-value t
13118 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13120 (let ((p (org-inside-LaTeX-fragment-p)))
13121 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13122 (setq ad-return-value t
13123 texmathp-why '("Org-mode embedded math" . 0))
13124 (if p ad-do-it)))))))))
13126 (defun turn-on-org-cdlatex ()
13127 "Unconditionally turn on `org-cdlatex-mode'."
13128 (org-cdlatex-mode 1))
13130 (defun org-inside-LaTeX-fragment-p ()
13131 "Test if point is inside a LaTeX fragment.
13132 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13133 sequence appearing also before point.
13134 Even though the matchers for math are configurable, this function assumes
13135 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13136 delimiters are skipped when they have been removed by customization.
13137 The return value is nil, or a cons cell with the delimiter and
13138 and the position of this delimiter.
13140 This function does a reasonably good job, but can locally be fooled by
13141 for example currency specifications. For example it will assume being in
13142 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13143 fragments that are properly closed, but during editing, we have to live
13144 with the uncertainty caused by missing closing delimiters. This function
13145 looks only before point, not after."
13146 (catch 'exit
13147 (let ((pos (point))
13148 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13149 (lim (progn
13150 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13151 (point)))
13152 dd-on str (start 0) m re)
13153 (goto-char pos)
13154 (when dodollar
13155 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13156 re (nth 1 (assoc "$" org-latex-regexps)))
13157 (while (string-match re str start)
13158 (cond
13159 ((= (match-end 0) (length str))
13160 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13161 ((= (match-end 0) (- (length str) 5))
13162 (throw 'exit nil))
13163 (t (setq start (match-end 0))))))
13164 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13165 (goto-char pos)
13166 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13167 (and (match-beginning 2) (throw 'exit nil))
13168 ;; count $$
13169 (while (re-search-backward "\\$\\$" lim t)
13170 (setq dd-on (not dd-on)))
13171 (goto-char pos)
13172 (if dd-on (cons "$$" m))))))
13175 (defun org-try-cdlatex-tab ()
13176 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13177 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13178 - inside a LaTeX fragment, or
13179 - after the first word in a line, where an abbreviation expansion could
13180 insert a LaTeX environment."
13181 (when org-cdlatex-mode
13182 (cond
13183 ((save-excursion
13184 (skip-chars-backward "a-zA-Z0-9*")
13185 (skip-chars-backward " \t")
13186 (bolp))
13187 (cdlatex-tab) t)
13188 ((org-inside-LaTeX-fragment-p)
13189 (cdlatex-tab) t)
13190 (t nil))))
13192 (defun org-cdlatex-underscore-caret (&optional arg)
13193 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13194 Revert to the normal definition outside of these fragments."
13195 (interactive "P")
13196 (if (org-inside-LaTeX-fragment-p)
13197 (call-interactively 'cdlatex-sub-superscript)
13198 (let (org-cdlatex-mode)
13199 (call-interactively (key-binding (vector last-input-event))))))
13201 (defun org-cdlatex-math-modify (&optional arg)
13202 "Execute `cdlatex-math-modify' in LaTeX fragments.
13203 Revert to the normal definition outside of these fragments."
13204 (interactive "P")
13205 (if (org-inside-LaTeX-fragment-p)
13206 (call-interactively 'cdlatex-math-modify)
13207 (let (org-cdlatex-mode)
13208 (call-interactively (key-binding (vector last-input-event))))))
13210 (defvar org-latex-fragment-image-overlays nil
13211 "List of overlays carrying the images of latex fragments.")
13212 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13214 (defun org-remove-latex-fragment-image-overlays ()
13215 "Remove all overlays with LaTeX fragment images in current buffer."
13216 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13217 (setq org-latex-fragment-image-overlays nil))
13219 (defun org-preview-latex-fragment (&optional subtree)
13220 "Preview the LaTeX fragment at point, or all locally or globally.
13221 If the cursor is in a LaTeX fragment, create the image and overlay
13222 it over the source code. If there is no fragment at point, display
13223 all fragments in the current text, from one headline to the next. With
13224 prefix SUBTREE, display all fragments in the current subtree. With a
13225 double prefix `C-u C-u', or when the cursor is before the first headline,
13226 display all fragments in the buffer.
13227 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13228 (interactive "P")
13229 (org-remove-latex-fragment-image-overlays)
13230 (save-excursion
13231 (save-restriction
13232 (let (beg end at msg)
13233 (cond
13234 ((or (equal subtree '(16))
13235 (not (save-excursion
13236 (re-search-backward (concat "^" outline-regexp) nil t))))
13237 (setq beg (point-min) end (point-max)
13238 msg "Creating images for buffer...%s"))
13239 ((equal subtree '(4))
13240 (org-back-to-heading)
13241 (setq beg (point) end (org-end-of-subtree t)
13242 msg "Creating images for subtree...%s"))
13244 (if (setq at (org-inside-LaTeX-fragment-p))
13245 (goto-char (max (point-min) (- (cdr at) 2)))
13246 (org-back-to-heading))
13247 (setq beg (point) end (progn (outline-next-heading) (point))
13248 msg (if at "Creating image...%s"
13249 "Creating images for entry...%s"))))
13250 (message msg "")
13251 (narrow-to-region beg end)
13252 (goto-char beg)
13253 (org-format-latex
13254 (concat "ltxpng/" (file-name-sans-extension
13255 (file-name-nondirectory
13256 buffer-file-name)))
13257 default-directory 'overlays msg at 'forbuffer)
13258 (message msg "done. Use `C-c C-c' to remove images.")))))
13260 (defvar org-latex-regexps
13261 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13262 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13263 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13264 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13265 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13266 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13267 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13268 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13269 "Regular expressions for matching embedded LaTeX.")
13271 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13272 "Replace LaTeX fragments with links to an image, and produce images."
13273 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13274 (let* ((prefixnodir (file-name-nondirectory prefix))
13275 (absprefix (expand-file-name prefix dir))
13276 (todir (file-name-directory absprefix))
13277 (opt org-format-latex-options)
13278 (matchers (plist-get opt :matchers))
13279 (re-list org-latex-regexps)
13280 (cnt 0) txt link beg end re e checkdir
13281 m n block linkfile movefile ov)
13282 ;; Check if there are old images files with this prefix, and remove them
13283 (when (file-directory-p todir)
13284 (mapc 'delete-file
13285 (directory-files
13286 todir 'full
13287 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13288 ;; Check the different regular expressions
13289 (while (setq e (pop re-list))
13290 (setq m (car e) re (nth 1 e) n (nth 2 e)
13291 block (if (nth 3 e) "\n\n" ""))
13292 (when (member m matchers)
13293 (goto-char (point-min))
13294 (while (re-search-forward re nil t)
13295 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13296 (not (get-text-property (match-beginning n)
13297 'org-protected)))
13298 (setq txt (match-string n)
13299 beg (match-beginning n) end (match-end n)
13300 cnt (1+ cnt)
13301 linkfile (format "%s_%04d.png" prefix cnt)
13302 movefile (format "%s_%04d.png" absprefix cnt)
13303 link (concat block "[[file:" linkfile "]]" block))
13304 (if msg (message msg cnt))
13305 (goto-char beg)
13306 (unless checkdir ; make sure the directory exists
13307 (setq checkdir t)
13308 (or (file-directory-p todir) (make-directory todir)))
13309 (org-create-formula-image
13310 txt movefile opt forbuffer)
13311 (if overlays
13312 (progn
13313 (setq ov (org-make-overlay beg end))
13314 (if (featurep 'xemacs)
13315 (progn
13316 (org-overlay-put ov 'invisible t)
13317 (org-overlay-put
13318 ov 'end-glyph
13319 (make-glyph (vector 'png :file movefile))))
13320 (org-overlay-put
13321 ov 'display
13322 (list 'image :type 'png :file movefile :ascent 'center)))
13323 (push ov org-latex-fragment-image-overlays)
13324 (goto-char end))
13325 (delete-region beg end)
13326 (insert link))))))))
13328 ;; This function borrows from Ganesh Swami's latex2png.el
13329 (defun org-create-formula-image (string tofile options buffer)
13330 (let* ((tmpdir (if (featurep 'xemacs)
13331 (temp-directory)
13332 temporary-file-directory))
13333 (texfilebase (make-temp-name
13334 (expand-file-name "orgtex" tmpdir)))
13335 (texfile (concat texfilebase ".tex"))
13336 (dvifile (concat texfilebase ".dvi"))
13337 (pngfile (concat texfilebase ".png"))
13338 (fnh (if (featurep 'xemacs)
13339 (font-height (get-face-font 'default))
13340 (face-attribute 'default :height nil)))
13341 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13342 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13343 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13344 "Black"))
13345 (bg (or (plist-get options (if buffer :background :html-background))
13346 "Transparent")))
13347 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13348 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13349 (with-temp-file texfile
13350 (insert org-format-latex-header
13351 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13352 (let ((dir default-directory))
13353 (condition-case nil
13354 (progn
13355 (cd tmpdir)
13356 (call-process "latex" nil nil nil texfile))
13357 (error nil))
13358 (cd dir))
13359 (if (not (file-exists-p dvifile))
13360 (progn (message "Failed to create dvi file from %s" texfile) nil)
13361 (condition-case nil
13362 (call-process "dvipng" nil nil nil
13363 "-E" "-fg" fg "-bg" bg
13364 "-D" dpi
13365 ;;"-x" scale "-y" scale
13366 "-T" "tight"
13367 "-o" pngfile
13368 dvifile)
13369 (error nil))
13370 (if (not (file-exists-p pngfile))
13371 (progn (message "Failed to create png file from %s" texfile) nil)
13372 ;; Use the requested file name and clean up
13373 (copy-file pngfile tofile 'replace)
13374 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13375 (delete-file (concat texfilebase e)))
13376 pngfile))))
13378 (defun org-dvipng-color (attr)
13379 "Return an rgb color specification for dvipng."
13380 (apply 'format "rgb %s %s %s"
13381 (mapcar 'org-normalize-color
13382 (color-values (face-attribute 'default attr nil)))))
13384 (defun org-normalize-color (value)
13385 "Return string to be used as color value for an RGB component."
13386 (format "%g" (/ value 65535.0)))
13388 ;;;; Key bindings
13390 ;; Make `C-c C-x' a prefix key
13391 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13393 ;; TAB key with modifiers
13394 (org-defkey org-mode-map "\C-i" 'org-cycle)
13395 (org-defkey org-mode-map [(tab)] 'org-cycle)
13396 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13397 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13398 (org-defkey org-mode-map "\M-\t" 'org-complete)
13399 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13400 ;; The following line is necessary under Suse GNU/Linux
13401 (unless (featurep 'xemacs)
13402 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13403 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13404 (define-key org-mode-map [backtab] 'org-shifttab)
13406 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13407 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13408 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13410 ;; Cursor keys with modifiers
13411 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13412 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13413 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13414 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13416 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13417 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13418 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13419 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13421 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13422 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13423 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13424 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13426 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13427 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13429 ;;; Extra keys for tty access.
13430 ;; We only set them when really needed because otherwise the
13431 ;; menus don't show the simple keys
13433 (when (or org-use-extra-keys
13434 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13435 (not window-system))
13436 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13437 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13438 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13439 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13440 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13441 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13442 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13443 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13444 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13445 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13446 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13447 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13448 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13449 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13450 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13451 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13452 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13453 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13454 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13455 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13456 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13457 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13459 ;; All the other keys
13461 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13462 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13463 (if (boundp 'narrow-map)
13464 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13465 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13466 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13467 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13468 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13469 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13470 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13471 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13472 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13473 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13474 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13475 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13476 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13477 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13478 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13479 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13480 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13481 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13482 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13483 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13484 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13485 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13486 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13487 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13488 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13489 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13490 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13491 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13492 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13493 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13494 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13495 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13496 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13497 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13498 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13499 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13500 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13501 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13502 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13503 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13504 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13505 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13506 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13507 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13508 (org-defkey org-mode-map "\C-c^" 'org-sort)
13509 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13510 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13511 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13512 (org-defkey org-mode-map "\C-m" 'org-return)
13513 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13514 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13515 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13516 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13517 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13518 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13519 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13520 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13521 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13522 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13523 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13524 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13525 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13526 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13527 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13528 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13529 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13531 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13532 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13533 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13534 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13536 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13537 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13538 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13539 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13540 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13541 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13542 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13543 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13544 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13545 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13546 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13547 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13548 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13550 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13551 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13552 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13553 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13555 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13557 (define-key org-mode-map "\C-c\C-xr" 'org-reload)
13559 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
13560 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
13562 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
13565 (when (featurep 'xemacs)
13566 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13569 (defvar org-self-insert-command-undo-counter 0)
13571 (defvar org-table-auto-blank-field) ; defined in org-table.el
13572 (defun org-self-insert-command (N)
13573 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13574 If the cursor is in a table looking at whitespace, the whitespace is
13575 overwritten, and the table is not marked as requiring realignment."
13576 (interactive "p")
13577 (if (and
13578 (org-table-p)
13579 (progn
13580 ;; check if we blank the field, and if that triggers align
13581 (and (featurep 'org-table) org-table-auto-blank-field
13582 (member last-command
13583 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13584 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13585 ;; got extra space, this field does not determine column width
13586 (let (org-table-may-need-update) (org-table-blank-field))
13587 ;; no extra space, this field may determine column width
13588 (org-table-blank-field)))
13590 (eq N 1)
13591 (looking-at "[^|\n]* |"))
13592 (let (org-table-may-need-update)
13593 (goto-char (1- (match-end 0)))
13594 (delete-backward-char 1)
13595 (goto-char (match-beginning 0))
13596 (self-insert-command N))
13597 (setq org-table-may-need-update t)
13598 (self-insert-command N)
13599 (org-fix-tags-on-the-fly)
13600 (if org-self-insert-cluster-for-undo
13601 (if (not (eq last-command 'org-self-insert-command))
13602 (setq org-self-insert-command-undo-counter 1)
13603 (if (>= org-self-insert-command-undo-counter 20)
13604 (setq org-self-insert-command-undo-counter 1)
13605 (and (> org-self-insert-command-undo-counter 0)
13606 buffer-undo-list
13607 (not (cadr buffer-undo-list)) ; remove nil entry
13608 (setcdr buffer-undo-list (cddr buffer-undo-list)))
13609 (setq org-self-insert-command-undo-counter
13610 (1+ org-self-insert-command-undo-counter)))))))
13612 (defun org-fix-tags-on-the-fly ()
13613 (when (and (equal (char-after (point-at-bol)) ?*)
13614 (org-on-heading-p))
13615 (org-align-tags-here org-tags-column)))
13617 (defun org-delete-backward-char (N)
13618 "Like `delete-backward-char', insert whitespace at field end in tables.
13619 When deleting backwards, in tables this function will insert whitespace in
13620 front of the next \"|\" separator, to keep the table aligned. The table will
13621 still be marked for re-alignment if the field did fill the entire column,
13622 because, in this case the deletion might narrow the column."
13623 (interactive "p")
13624 (if (and (org-table-p)
13625 (eq N 1)
13626 (string-match "|" (buffer-substring (point-at-bol) (point)))
13627 (looking-at ".*?|"))
13628 (let ((pos (point))
13629 (noalign (looking-at "[^|\n\r]* |"))
13630 (c org-table-may-need-update))
13631 (backward-delete-char N)
13632 (skip-chars-forward "^|")
13633 (insert " ")
13634 (goto-char (1- pos))
13635 ;; noalign: if there were two spaces at the end, this field
13636 ;; does not determine the width of the column.
13637 (if noalign (setq org-table-may-need-update c)))
13638 (backward-delete-char N)
13639 (org-fix-tags-on-the-fly)))
13641 (defun org-delete-char (N)
13642 "Like `delete-char', but insert whitespace at field end in tables.
13643 When deleting characters, in tables this function will insert whitespace in
13644 front of the next \"|\" separator, to keep the table aligned. The table will
13645 still be marked for re-alignment if the field did fill the entire column,
13646 because, in this case the deletion might narrow the column."
13647 (interactive "p")
13648 (if (and (org-table-p)
13649 (not (bolp))
13650 (not (= (char-after) ?|))
13651 (eq N 1))
13652 (if (looking-at ".*?|")
13653 (let ((pos (point))
13654 (noalign (looking-at "[^|\n\r]* |"))
13655 (c org-table-may-need-update))
13656 (replace-match (concat
13657 (substring (match-string 0) 1 -1)
13658 " |"))
13659 (goto-char pos)
13660 ;; noalign: if there were two spaces at the end, this field
13661 ;; does not determine the width of the column.
13662 (if noalign (setq org-table-may-need-update c)))
13663 (delete-char N))
13664 (delete-char N)
13665 (org-fix-tags-on-the-fly)))
13667 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13668 (put 'org-self-insert-command 'delete-selection t)
13669 (put 'orgtbl-self-insert-command 'delete-selection t)
13670 (put 'org-delete-char 'delete-selection 'supersede)
13671 (put 'org-delete-backward-char 'delete-selection 'supersede)
13672 (put 'org-yank 'delete-selection 'yank)
13674 ;; Make `flyspell-mode' delay after some commands
13675 (put 'org-self-insert-command 'flyspell-delayed t)
13676 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13677 (put 'org-delete-char 'flyspell-delayed t)
13678 (put 'org-delete-backward-char 'flyspell-delayed t)
13680 ;; Make pabbrev-mode expand after org-mode commands
13681 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13682 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13684 ;; How to do this: Measure non-white length of current string
13685 ;; If equal to column width, we should realign.
13687 (defun org-remap (map &rest commands)
13688 "In MAP, remap the functions given in COMMANDS.
13689 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13690 (let (new old)
13691 (while commands
13692 (setq old (pop commands) new (pop commands))
13693 (if (fboundp 'command-remapping)
13694 (org-defkey map (vector 'remap old) new)
13695 (substitute-key-definition old new map global-map)))))
13697 (when (eq org-enable-table-editor 'optimized)
13698 ;; If the user wants maximum table support, we need to hijack
13699 ;; some standard editing functions
13700 (org-remap org-mode-map
13701 'self-insert-command 'org-self-insert-command
13702 'delete-char 'org-delete-char
13703 'delete-backward-char 'org-delete-backward-char)
13704 (org-defkey org-mode-map "|" 'org-force-self-insert))
13706 (defvar org-ctrl-c-ctrl-c-hook nil
13707 "Hook for functions attaching themselves to `C-c C-c'.
13708 This can be used to add additional functionality to the C-c C-c key which
13709 executes context-dependent commands.
13710 Each function will be called with no arguments. The function must check
13711 if the context is appropriate for it to act. If yes, it should do its
13712 thing and then return a non-nil value. If the context is wrong,
13713 just do nothing.")
13715 (defvar org-metaleft-hook nil
13716 "Hook for functions attaching themselves to `M-left'.
13717 See `org-ctrl-c-ctrl-c-hook' for more information.")
13718 (defvar org-metaright-hook nil
13719 "Hook for functions attaching themselves to `M-right'.
13720 See `org-ctrl-c-ctrl-c-hook' for more information.")
13721 (defvar org-metaup-hook nil
13722 "Hook for functions attaching themselves to `M-up'.
13723 See `org-ctrl-c-ctrl-c-hook' for more information.")
13724 (defvar org-metadown-hook nil
13725 "Hook for functions attaching themselves to `M-down'.
13726 See `org-ctrl-c-ctrl-c-hook' for more information.")
13727 (defvar org-shiftmetaleft-hook nil
13728 "Hook for functions attaching themselves to `M-S-left'.
13729 See `org-ctrl-c-ctrl-c-hook' for more information.")
13730 (defvar org-shiftmetaright-hook nil
13731 "Hook for functions attaching themselves to `M-S-right'.
13732 See `org-ctrl-c-ctrl-c-hook' for more information.")
13733 (defvar org-shiftmetaup-hook nil
13734 "Hook for functions attaching themselves to `M-S-up'.
13735 See `org-ctrl-c-ctrl-c-hook' for more information.")
13736 (defvar org-shiftmetadown-hook nil
13737 "Hook for functions attaching themselves to `M-S-down'.
13738 See `org-ctrl-c-ctrl-c-hook' for more information.")
13739 (defvar org-metareturn-hook nil
13740 "Hook for functions attaching themselves to `M-RET'.
13741 See `org-ctrl-c-ctrl-c-hook' for more information.")
13743 (defun org-modifier-cursor-error ()
13744 "Throw an error, a modified cursor command was applied in wrong context."
13745 (error "This command is active in special context like tables, headlines or items"))
13747 (defun org-shiftselect-error ()
13748 "Throw an error because Shift-Cursor command was applied in wrong context."
13749 (if (and (boundp 'shift-select-mode) shift-select-mode)
13750 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13751 (error "This command works only in special context like headlines or timestamps.")))
13753 (defun org-call-for-shift-select (cmd)
13754 (let ((this-command-keys-shift-translated t))
13755 (call-interactively cmd)))
13757 (defun org-shifttab (&optional arg)
13758 "Global visibility cycling or move to previous table field.
13759 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13760 on context.
13761 See the individual commands for more information."
13762 (interactive "P")
13763 (cond
13764 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13765 ((integerp arg)
13766 (message "Content view to level: %d" arg)
13767 (org-content (prefix-numeric-value arg))
13768 (setq org-cycle-global-status 'overview))
13769 (t (call-interactively 'org-global-cycle))))
13771 (defun org-shiftmetaleft ()
13772 "Promote subtree or delete table column.
13773 Calls `org-promote-subtree', `org-outdent-item',
13774 or `org-table-delete-column', depending on context.
13775 See the individual commands for more information."
13776 (interactive)
13777 (cond
13778 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
13779 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13780 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13781 ((org-at-item-p) (call-interactively 'org-outdent-item))
13782 (t (org-modifier-cursor-error))))
13784 (defun org-shiftmetaright ()
13785 "Demote subtree or insert table column.
13786 Calls `org-demote-subtree', `org-indent-item',
13787 or `org-table-insert-column', depending on context.
13788 See the individual commands for more information."
13789 (interactive)
13790 (cond
13791 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
13792 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13793 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13794 ((org-at-item-p) (call-interactively 'org-indent-item))
13795 (t (org-modifier-cursor-error))))
13797 (defun org-shiftmetaup (&optional arg)
13798 "Move subtree up or kill table row.
13799 Calls `org-move-subtree-up' or `org-table-kill-row' or
13800 `org-move-item-up' depending on context. See the individual commands
13801 for more information."
13802 (interactive "P")
13803 (cond
13804 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
13805 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13806 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13807 ((org-at-item-p) (call-interactively 'org-move-item-up))
13808 (t (org-modifier-cursor-error))))
13810 (defun org-shiftmetadown (&optional arg)
13811 "Move subtree down or insert table row.
13812 Calls `org-move-subtree-down' or `org-table-insert-row' or
13813 `org-move-item-down', depending on context. See the individual
13814 commands for more information."
13815 (interactive "P")
13816 (cond
13817 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
13818 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13819 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13820 ((org-at-item-p) (call-interactively 'org-move-item-down))
13821 (t (org-modifier-cursor-error))))
13823 (defun org-metaleft (&optional arg)
13824 "Promote heading or move table column to left.
13825 Calls `org-do-promote' or `org-table-move-column', depending on context.
13826 With no specific context, calls the Emacs default `backward-word'.
13827 See the individual commands for more information."
13828 (interactive "P")
13829 (cond
13830 ((run-hook-with-args-until-success 'org-metaleft-hook))
13831 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13832 ((or (org-on-heading-p)
13833 (and (org-region-active-p)
13834 (save-excursion
13835 (goto-char (region-beginning))
13836 (org-on-heading-p))))
13837 (call-interactively 'org-do-promote))
13838 ((or (org-at-item-p)
13839 (and (org-region-active-p)
13840 (save-excursion
13841 (goto-char (region-beginning))
13842 (org-at-item-p))))
13843 (call-interactively 'org-outdent-item))
13844 (t (call-interactively 'backward-word))))
13846 (defun org-metaright (&optional arg)
13847 "Demote subtree or move table column to right.
13848 Calls `org-do-demote' or `org-table-move-column', depending on context.
13849 With no specific context, calls the Emacs default `forward-word'.
13850 See the individual commands for more information."
13851 (interactive "P")
13852 (cond
13853 ((run-hook-with-args-until-success 'org-metaright-hook))
13854 ((org-at-table-p) (call-interactively 'org-table-move-column))
13855 ((or (org-on-heading-p)
13856 (and (org-region-active-p)
13857 (save-excursion
13858 (goto-char (region-beginning))
13859 (org-on-heading-p))))
13860 (call-interactively 'org-do-demote))
13861 ((or (org-at-item-p)
13862 (and (org-region-active-p)
13863 (save-excursion
13864 (goto-char (region-beginning))
13865 (org-at-item-p))))
13866 (call-interactively 'org-indent-item))
13867 (t (call-interactively 'forward-word))))
13869 (defun org-metaup (&optional arg)
13870 "Move subtree up or move table row up.
13871 Calls `org-move-subtree-up' or `org-table-move-row' or
13872 `org-move-item-up', depending on context. See the individual commands
13873 for more information."
13874 (interactive "P")
13875 (cond
13876 ((run-hook-with-args-until-success 'org-metaup-hook))
13877 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13878 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13879 ((org-at-item-p) (call-interactively 'org-move-item-up))
13880 (t (transpose-lines 1) (beginning-of-line -1))))
13882 (defun org-metadown (&optional arg)
13883 "Move subtree down or move table row down.
13884 Calls `org-move-subtree-down' or `org-table-move-row' or
13885 `org-move-item-down', depending on context. See the individual
13886 commands for more information."
13887 (interactive "P")
13888 (cond
13889 ((run-hook-with-args-until-success 'org-metadown-hook))
13890 ((org-at-table-p) (call-interactively 'org-table-move-row))
13891 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13892 ((org-at-item-p) (call-interactively 'org-move-item-down))
13893 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13895 (defun org-shiftup (&optional arg)
13896 "Increase item in timestamp or increase priority of current headline.
13897 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13898 depending on context. See the individual commands for more information."
13899 (interactive "P")
13900 (cond
13901 ((and org-support-shift-select (org-region-active-p))
13902 (org-call-for-shift-select 'previous-line))
13903 ((org-at-timestamp-p t)
13904 (call-interactively (if org-edit-timestamp-down-means-later
13905 'org-timestamp-down 'org-timestamp-up)))
13906 ((and (not (eq org-support-shift-select 'always))
13907 (org-on-heading-p))
13908 (call-interactively 'org-priority-up))
13909 ((and (not org-support-shift-select) (org-at-item-p))
13910 (call-interactively 'org-previous-item))
13911 ((org-clocktable-try-shift 'up arg))
13912 (org-support-shift-select
13913 (org-call-for-shift-select 'previous-line))
13914 (t (org-shiftselect-error))))
13916 (defun org-shiftdown (&optional arg)
13917 "Decrease item in timestamp or decrease priority of current headline.
13918 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13919 depending on context. See the individual commands for more information."
13920 (interactive "P")
13921 (cond
13922 ((and org-support-shift-select (org-region-active-p))
13923 (org-call-for-shift-select 'next-line))
13924 ((org-at-timestamp-p t)
13925 (call-interactively (if org-edit-timestamp-down-means-later
13926 'org-timestamp-up 'org-timestamp-down)))
13927 ((and (not (eq org-support-shift-select 'always))
13928 (org-on-heading-p))
13929 (call-interactively 'org-priority-down))
13930 ((and (not org-support-shift-select) (org-at-item-p))
13931 (call-interactively 'org-next-item))
13932 ((org-clocktable-try-shift 'down arg))
13933 (org-support-shift-select
13934 (org-call-for-shift-select 'next-line))
13935 (t (org-shiftselect-error))))
13937 (defun org-shiftright (&optional arg)
13938 "Cycle the thing at point or in the current line, depending on context.
13939 Depending on context, this does one of the following:
13941 - switch a timestamp at point one day into the future
13942 - on a headline, switch to the next TODO keyword.
13943 - on an item, switch entire list to the next bullet type
13944 - on a property line, switch to the next allowed value
13945 - on a clocktable definition line, move time block into the future"
13946 (interactive "P")
13947 (cond
13948 ((and org-support-shift-select (org-region-active-p))
13949 (org-call-for-shift-select 'forward-char))
13950 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13951 ((and (not (eq org-support-shift-select 'always))
13952 (org-on-heading-p))
13953 (org-call-with-arg 'org-todo 'right))
13954 ((or (and org-support-shift-select
13955 (not (eq org-support-shift-select 'always))
13956 (org-at-item-bullet-p))
13957 (and (not org-support-shift-select) (org-at-item-p)))
13958 (org-call-with-arg 'org-cycle-list-bullet nil))
13959 ((and (not (eq org-support-shift-select 'always))
13960 (org-at-property-p))
13961 (call-interactively 'org-property-next-allowed-value))
13962 ((org-clocktable-try-shift 'right arg))
13963 (org-support-shift-select
13964 (org-call-for-shift-select 'forward-char))
13965 (t (org-shiftselect-error))))
13967 (defun org-shiftleft (&optional arg)
13968 "Cycle the thing at point or in the current line, depending on context.
13969 Depending on context, this does one of the following:
13971 - switch a timestamp at point one day into the past
13972 - on a headline, switch to the previous TODO keyword.
13973 - on an item, switch entire list to the previous bullet type
13974 - on a property line, switch to the previous allowed value
13975 - on a clocktable definition line, move time block into the past"
13976 (interactive "P")
13977 (cond
13978 ((and org-support-shift-select (org-region-active-p))
13979 (org-call-for-shift-select 'backward-char))
13980 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13981 ((and (not (eq org-support-shift-select 'always))
13982 (org-on-heading-p))
13983 (org-call-with-arg 'org-todo 'left))
13984 ((or (and org-support-shift-select
13985 (not (eq org-support-shift-select 'always))
13986 (org-at-item-bullet-p))
13987 (and (not org-support-shift-select) (org-at-item-p)))
13988 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13989 ((and (not (eq org-support-shift-select 'always))
13990 (org-at-property-p))
13991 (call-interactively 'org-property-previous-allowed-value))
13992 ((org-clocktable-try-shift 'left arg))
13993 (org-support-shift-select
13994 (org-call-for-shift-select 'backward-char))
13995 (t (org-shiftselect-error))))
13997 (defun org-shiftcontrolright ()
13998 "Switch to next TODO set."
13999 (interactive)
14000 (cond
14001 ((and org-support-shift-select (org-region-active-p))
14002 (org-call-for-shift-select 'forward-word))
14003 ((and (not (eq org-support-shift-select 'always))
14004 (org-on-heading-p))
14005 (org-call-with-arg 'org-todo 'nextset))
14006 (org-support-shift-select
14007 (org-call-for-shift-select 'forward-word))
14008 (t (org-shiftselect-error))))
14010 (defun org-shiftcontrolleft ()
14011 "Switch to previous TODO set."
14012 (interactive)
14013 (cond
14014 ((and org-support-shift-select (org-region-active-p))
14015 (org-call-for-shift-select 'backward-word))
14016 ((and (not (eq org-support-shift-select 'always))
14017 (org-on-heading-p))
14018 (org-call-with-arg 'org-todo 'previousset))
14019 (org-support-shift-select
14020 (org-call-for-shift-select 'backward-word))
14021 (t (org-shiftselect-error))))
14023 (defun org-ctrl-c-ret ()
14024 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14025 (interactive)
14026 (cond
14027 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14028 (t (call-interactively 'org-insert-heading))))
14030 (defun org-copy-special ()
14031 "Copy region in table or copy current subtree.
14032 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14033 See the individual commands for more information."
14034 (interactive)
14035 (call-interactively
14036 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14038 (defun org-cut-special ()
14039 "Cut region in table or cut current subtree.
14040 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14041 See the individual commands for more information."
14042 (interactive)
14043 (call-interactively
14044 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14046 (defun org-paste-special (arg)
14047 "Paste rectangular region into table, or past subtree relative to level.
14048 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14049 See the individual commands for more information."
14050 (interactive "P")
14051 (if (org-at-table-p)
14052 (org-table-paste-rectangle)
14053 (org-paste-subtree arg)))
14055 (defun org-edit-special ()
14056 "Call a special editor for the stuff at point.
14057 When at a table, call the formula editor with `org-table-edit-formulas'.
14058 When at the first line of an src example, call `org-edit-src-code'.
14059 When in an #+include line, visit the include file. Otherwise call
14060 `ffap' to visit the file at point."
14061 (interactive)
14062 (cond
14063 ((org-at-table-p)
14064 (call-interactively 'org-table-edit-formulas))
14065 ((save-excursion
14066 (beginning-of-line 1)
14067 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14068 (find-file (org-trim (match-string 1))))
14069 ((org-edit-src-code))
14070 ((org-edit-fixed-width-region))
14071 (t (call-interactively 'ffap))))
14074 (defun org-ctrl-c-ctrl-c (&optional arg)
14075 "Set tags in headline, or update according to changed information at point.
14077 This command does many different things, depending on context:
14079 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14080 this is what we do.
14082 - If the cursor is in a headline, prompt for tags and insert them
14083 into the current line, aligned to `org-tags-column'. When called
14084 with prefix arg, realign all tags in the current buffer.
14086 - If the cursor is in one of the special #+KEYWORD lines, this
14087 triggers scanning the buffer for these lines and updating the
14088 information.
14090 - If the cursor is inside a table, realign the table. This command
14091 works even if the automatic table editor has been turned off.
14093 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14094 the entire table.
14096 - If the cursor is at a footnote reference or definition, jump to
14097 the corresponding definition or references, respectively.
14099 - If the cursor is a the beginning of a dynamic block, update it.
14101 - If the cursor is inside a table created by the table.el package,
14102 activate that table.
14104 - If the current buffer is a remember buffer, close note and file
14105 it. A prefix argument of 1 files to the default location
14106 without further interaction. A prefix argument of 2 files to
14107 the currently clocking task.
14109 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14110 links in this buffer.
14112 - If the cursor is on a numbered item in a plain list, renumber the
14113 ordered list.
14115 - If the cursor is on a checkbox, toggle it."
14116 (interactive "P")
14117 (let ((org-enable-table-editor t))
14118 (cond
14119 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14120 org-occur-highlights
14121 org-latex-fragment-image-overlays)
14122 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14123 (org-remove-occur-highlights)
14124 (org-remove-latex-fragment-image-overlays)
14125 (message "Temporary highlights/overlays removed from current buffer"))
14126 ((and (local-variable-p 'org-finish-function (current-buffer))
14127 (fboundp org-finish-function))
14128 (funcall org-finish-function))
14129 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14130 ((org-at-property-p)
14131 (call-interactively 'org-property-action))
14132 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14133 ((org-on-heading-p) (call-interactively 'org-set-tags))
14134 ((org-at-table.el-p)
14135 (require 'table)
14136 (beginning-of-line 1)
14137 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14138 (call-interactively 'table-recognize-table))
14139 ((org-at-table-p)
14140 (org-table-maybe-eval-formula)
14141 (if arg
14142 (call-interactively 'org-table-recalculate)
14143 (org-table-maybe-recalculate-line))
14144 (call-interactively 'org-table-align))
14145 ((or (org-footnote-at-reference-p)
14146 (org-footnote-at-definition-p))
14147 (call-interactively 'org-footnote-action))
14148 ((org-at-item-checkbox-p)
14149 (call-interactively 'org-toggle-checkbox))
14150 ((org-at-item-p)
14151 (if arg
14152 (call-interactively 'org-toggle-checkbox)
14153 (call-interactively 'org-maybe-renumber-ordered-list)))
14154 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14155 ;; Dynamic block
14156 (beginning-of-line 1)
14157 (save-excursion (org-update-dblock)))
14158 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14159 (cond
14160 ((equal (match-string 1) "TBLFM")
14161 ;; Recalculate the table before this line
14162 (save-excursion
14163 (beginning-of-line 1)
14164 (skip-chars-backward " \r\n\t")
14165 (if (org-at-table-p)
14166 (org-call-with-arg 'org-table-recalculate t))))
14168 ; (org-set-regexps-and-options)
14169 ; (org-restart-font-lock)
14170 (let ((org-inhibit-startup t)) (org-mode-restart))
14171 (message "Local setup has been refreshed"))))
14172 (t (error "C-c C-c can do nothing useful at this location.")))))
14174 (defun org-mode-restart ()
14175 "Restart Org-mode, to scan again for special lines.
14176 Also updates the keyword regular expressions."
14177 (interactive)
14178 (org-mode)
14179 (message "Org-mode restarted"))
14181 (defun org-kill-note-or-show-branches ()
14182 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14183 (interactive)
14184 (if (not org-finish-function)
14185 (call-interactively 'show-branches)
14186 (let ((org-note-abort t))
14187 (funcall org-finish-function))))
14189 (defun org-return (&optional indent)
14190 "Goto next table row or insert a newline.
14191 Calls `org-table-next-row' or `newline', depending on context.
14192 See the individual commands for more information."
14193 (interactive)
14194 (cond
14195 ((bobp) (if indent (newline-and-indent) (newline)))
14196 ((org-at-table-p)
14197 (org-table-justify-field-maybe)
14198 (call-interactively 'org-table-next-row))
14199 ((and org-return-follows-link
14200 (eq (get-text-property (point) 'face) 'org-link))
14201 (call-interactively 'org-open-at-point))
14202 ((and (org-at-heading-p)
14203 (looking-at
14204 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14205 (org-show-entry)
14206 (end-of-line 1)
14207 (newline))
14208 (t (if indent (newline-and-indent) (newline)))))
14210 (defun org-return-indent ()
14211 "Goto next table row or insert a newline and indent.
14212 Calls `org-table-next-row' or `newline-and-indent', depending on
14213 context. See the individual commands for more information."
14214 (interactive)
14215 (org-return t))
14217 (defun org-ctrl-c-star ()
14218 "Compute table, or change heading status of lines.
14219 Calls `org-table-recalculate' or `org-toggle-heading',
14220 depending on context."
14221 (interactive)
14222 (cond
14223 ((org-at-table-p)
14224 (call-interactively 'org-table-recalculate))
14226 ;; Convert all lines in region to list items
14227 (call-interactively 'org-toggle-heading))))
14229 (defun org-ctrl-c-minus ()
14230 "Insert separator line in table or modify bullet status of line.
14231 Also turns a plain line or a region of lines into list items.
14232 Calls `org-table-insert-hline', `org-toggle-item', or
14233 `org-cycle-list-bullet', depending on context."
14234 (interactive)
14235 (cond
14236 ((org-at-table-p)
14237 (call-interactively 'org-table-insert-hline))
14238 ((org-region-active-p)
14239 (call-interactively 'org-toggle-item))
14240 ((org-in-item-p)
14241 (call-interactively 'org-cycle-list-bullet))
14243 (call-interactively 'org-toggle-item))))
14245 (defun org-toggle-item ()
14246 "Convert headings or normal lines to items, items to normal lines.
14247 If there is no active region, only the current line is considered.
14249 If the first line in the region is a headline, convert all headlines to items.
14251 If the first line in the region is an item, convert all items to normal lines.
14253 If the first line is normal text, add an item bullet to each line."
14254 (interactive)
14255 (let (l2 l beg end)
14256 (if (org-region-active-p)
14257 (setq beg (region-beginning) end (region-end))
14258 (setq beg (point-at-bol)
14259 end (min (1+ (point-at-eol)) (point-max))))
14260 (save-excursion
14261 (goto-char end)
14262 (setq l2 (org-current-line))
14263 (goto-char beg)
14264 (beginning-of-line 1)
14265 (setq l (1- (org-current-line)))
14266 (if (org-at-item-p)
14267 ;; We already have items, de-itemize
14268 (while (< (setq l (1+ l)) l2)
14269 (when (org-at-item-p)
14270 (goto-char (match-beginning 2))
14271 (delete-region (match-beginning 2) (match-end 2))
14272 (and (looking-at "[ \t]+") (replace-match "")))
14273 (beginning-of-line 2))
14274 (if (org-on-heading-p)
14275 ;; Headings, convert to items
14276 (while (< (setq l (1+ l)) l2)
14277 (if (looking-at org-outline-regexp)
14278 (replace-match "- " t t))
14279 (beginning-of-line 2))
14280 ;; normal lines, turn them into items
14281 (while (< (setq l (1+ l)) l2)
14282 (unless (org-at-item-p)
14283 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14284 (replace-match "\\1- \\2")))
14285 (beginning-of-line 2)))))))
14287 (defun org-toggle-heading (&optional nstars)
14288 "Convert headings to normal text, or items or text to headings.
14289 If there is no active region, only the current line is considered.
14291 If the first line is a heading, remove the stars from all headlines
14292 in the region.
14294 If the first line is a plain list item, turn all plain list items into
14295 headings.
14297 If the first line is a normal line, turn each and every line in the region
14298 into a heading.
14300 When converting a line into a heading, the number of stars is chosen
14301 such that the lines become children of the current entry. However, when
14302 a prefix argument is given, its value determines the number of stars to add."
14303 (interactive "P")
14304 (let (l2 l itemp beg end)
14305 (if (org-region-active-p)
14306 (setq beg (region-beginning) end (region-end))
14307 (setq beg (point-at-bol)
14308 end (min (1+ (point-at-eol)) (point-max))))
14309 (save-excursion
14310 (goto-char end)
14311 (setq l2 (org-current-line))
14312 (goto-char beg)
14313 (beginning-of-line 1)
14314 (setq l (1- (org-current-line)))
14315 (if (org-on-heading-p)
14316 ;; We already have headlines, de-star them
14317 (while (< (setq l (1+ l)) l2)
14318 (when (org-on-heading-p t)
14319 (and (looking-at outline-regexp) (replace-match "")))
14320 (beginning-of-line 2))
14321 (setq itemp (org-at-item-p))
14322 (let* ((stars
14323 (if nstars
14324 (make-string (prefix-numeric-value current-prefix-arg)
14326 (save-excursion
14327 (re-search-backward org-complex-heading-regexp nil t)
14328 (or (match-string 1) ""))))
14329 (add-stars (cond (nstars "")
14330 ((equal stars "") "*")
14331 (org-odd-levels-only "**")
14332 (t "*")))
14333 (rpl (concat stars add-stars " ")))
14334 (while (< (setq l (1+ l)) l2)
14335 (if itemp
14336 (and (org-at-item-p) (replace-match rpl t t))
14337 (unless (org-on-heading-p)
14338 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14339 (replace-match (concat rpl (match-string 2))))))
14340 (beginning-of-line 2)))))))
14342 (defun org-meta-return (&optional arg)
14343 "Insert a new heading or wrap a region in a table.
14344 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14345 See the individual commands for more information."
14346 (interactive "P")
14347 (cond
14348 ((run-hook-with-args-until-success 'org-metareturn-hook))
14349 ((org-at-table-p)
14350 (call-interactively 'org-table-wrap-region))
14351 (t (call-interactively 'org-insert-heading))))
14353 ;;; Menu entries
14355 ;; Define the Org-mode menus
14356 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14357 '("Tbl"
14358 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14359 ["Next Field" org-cycle (org-at-table-p)]
14360 ["Previous Field" org-shifttab (org-at-table-p)]
14361 ["Next Row" org-return (org-at-table-p)]
14362 "--"
14363 ["Blank Field" org-table-blank-field (org-at-table-p)]
14364 ["Edit Field" org-table-edit-field (org-at-table-p)]
14365 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14366 "--"
14367 ("Column"
14368 ["Move Column Left" org-metaleft (org-at-table-p)]
14369 ["Move Column Right" org-metaright (org-at-table-p)]
14370 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14371 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14372 ("Row"
14373 ["Move Row Up" org-metaup (org-at-table-p)]
14374 ["Move Row Down" org-metadown (org-at-table-p)]
14375 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14376 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14377 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14378 "--"
14379 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14380 ("Rectangle"
14381 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14382 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14383 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14384 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14385 "--"
14386 ("Calculate"
14387 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14388 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14389 ["Edit Formulas" org-edit-special (org-at-table-p)]
14390 "--"
14391 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14392 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14393 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14394 "--"
14395 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14396 "--"
14397 ["Sum Column/Rectangle" org-table-sum
14398 (or (org-at-table-p) (org-region-active-p))]
14399 ["Which Column?" org-table-current-column (org-at-table-p)])
14400 ["Debug Formulas"
14401 org-table-toggle-formula-debugger
14402 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14403 ["Show Col/Row Numbers"
14404 org-table-toggle-coordinate-overlays
14405 :style toggle
14406 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14407 "--"
14408 ["Create" org-table-create (and (not (org-at-table-p))
14409 org-enable-table-editor)]
14410 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14411 ["Import from File" org-table-import (not (org-at-table-p))]
14412 ["Export to File" org-table-export (org-at-table-p)]
14413 "--"
14414 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14416 (easy-menu-define org-org-menu org-mode-map "Org menu"
14417 '("Org"
14418 ("Show/Hide"
14419 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14420 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14421 ["Sparse Tree..." org-sparse-tree t]
14422 ["Reveal Context" org-reveal t]
14423 ["Show All" show-all t]
14424 "--"
14425 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14426 "--"
14427 ["New Heading" org-insert-heading t]
14428 ("Navigate Headings"
14429 ["Up" outline-up-heading t]
14430 ["Next" outline-next-visible-heading t]
14431 ["Previous" outline-previous-visible-heading t]
14432 ["Next Same Level" outline-forward-same-level t]
14433 ["Previous Same Level" outline-backward-same-level t]
14434 "--"
14435 ["Jump" org-goto t])
14436 ("Edit Structure"
14437 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14438 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14439 "--"
14440 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14441 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14442 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14443 "--"
14444 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14445 "--"
14446 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14447 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14448 ["Demote Heading" org-metaright (not (org-at-table-p))]
14449 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14450 "--"
14451 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14452 "--"
14453 ["Convert to odd levels" org-convert-to-odd-levels t]
14454 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14455 ("Editing"
14456 ["Emphasis..." org-emphasize t]
14457 ["Edit Source Example" org-edit-special t]
14458 "--"
14459 ["Footnote new/jump" org-footnote-action t]
14460 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14461 ("Archive"
14462 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14463 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14464 ; :active t :keys "C-u C-c C-x C-a"]
14465 ["Sparse trees open ARCHIVE trees"
14466 (setq org-sparse-tree-open-archived-trees
14467 (not org-sparse-tree-open-archived-trees))
14468 :style toggle :selected org-sparse-tree-open-archived-trees]
14469 ["Cycling opens ARCHIVE trees"
14470 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14471 :style toggle :selected org-cycle-open-archived-trees]
14472 "--"
14473 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14474 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14475 ; ["Check and Move Children" (org-archive-subtree '(4))
14476 ; :active t :keys "C-u C-c C-x C-s"]
14478 "--"
14479 ("Hyperlinks"
14480 ["Store Link (Global)" org-store-link t]
14481 ["Insert Link" org-insert-link t]
14482 ["Follow Link" org-open-at-point t]
14483 "--"
14484 ["Next link" org-next-link t]
14485 ["Previous link" org-previous-link t]
14486 "--"
14487 ["Descriptive Links"
14488 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14489 :style radio
14490 :selected (member '(org-link) buffer-invisibility-spec)]
14491 ["Literal Links"
14492 (progn
14493 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14494 :style radio
14495 :selected (not (member '(org-link) buffer-invisibility-spec))])
14496 "--"
14497 ("TODO Lists"
14498 ["TODO/DONE/-" org-todo t]
14499 ("Select keyword"
14500 ["Next keyword" org-shiftright (org-on-heading-p)]
14501 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14502 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14503 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14504 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14505 ["Show TODO Tree" org-show-todo-tree t]
14506 ["Global TODO list" org-todo-list t]
14507 "--"
14508 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14509 :selected org-enforce-todo-dependencies :style toggle :active t]
14510 "Settings for tree at point"
14511 ["Do Children sequentially" org-toggle-ordered-property :style radio
14512 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14513 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14514 ["Do Children parallel" org-toggle-ordered-property :style radio
14515 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14516 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14517 "--"
14518 ["Set Priority" org-priority t]
14519 ["Priority Up" org-shiftup t]
14520 ["Priority Down" org-shiftdown t]
14521 "--"
14522 ["Get news from all feeds" org-feed-update-all t]
14523 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
14524 ["Customize feeds" (customize-variable 'org-feed-alist) t])
14525 ("TAGS and Properties"
14526 ["Set Tags" org-set-tags-command t]
14527 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14528 "--"
14529 ["Set property" org-set-property t]
14530 ["Column view of properties" org-columns t]
14531 ["Insert Column View DBlock" org-insert-columns-dblock t])
14532 ("Dates and Scheduling"
14533 ["Timestamp" org-time-stamp t]
14534 ["Timestamp (inactive)" org-time-stamp-inactive t]
14535 ("Change Date"
14536 ["1 Day Later" org-shiftright t]
14537 ["1 Day Earlier" org-shiftleft t]
14538 ["1 ... Later" org-shiftup t]
14539 ["1 ... Earlier" org-shiftdown t])
14540 ["Compute Time Range" org-evaluate-time-range t]
14541 ["Schedule Item" org-schedule t]
14542 ["Deadline" org-deadline t]
14543 "--"
14544 ["Custom time format" org-toggle-time-stamp-overlays
14545 :style radio :selected org-display-custom-times]
14546 "--"
14547 ["Goto Calendar" org-goto-calendar t]
14548 ["Date from Calendar" org-date-from-calendar t]
14549 "--"
14550 ["Start/Restart Timer" org-timer-start t]
14551 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14552 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14553 ["Insert Timer String" org-timer t]
14554 ["Insert Timer Item" org-timer-item t])
14555 ("Logging work"
14556 ["Clock in" org-clock-in t]
14557 ["Clock out" org-clock-out t]
14558 ["Clock cancel" org-clock-cancel t]
14559 ["Goto running clock" org-clock-goto t]
14560 ["Display times" org-clock-display t]
14561 ["Create clock table" org-clock-report t]
14562 "--"
14563 ["Record DONE time"
14564 (progn (setq org-log-done (not org-log-done))
14565 (message "Switching to %s will %s record a timestamp"
14566 (car org-done-keywords)
14567 (if org-log-done "automatically" "not")))
14568 :style toggle :selected org-log-done])
14569 "--"
14570 ["Agenda Command..." org-agenda t]
14571 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14572 ("File List for Agenda")
14573 ("Special views current file"
14574 ["TODO Tree" org-show-todo-tree t]
14575 ["Check Deadlines" org-check-deadlines t]
14576 ["Timeline" org-timeline t]
14577 ["Tags/Property tree" org-match-sparse-tree t])
14578 "--"
14579 ["Export/Publish..." org-export t]
14580 ("LaTeX"
14581 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14582 :selected org-cdlatex-mode]
14583 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14584 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14585 ["Modify math symbol" org-cdlatex-math-modify
14586 (org-inside-LaTeX-fragment-p)]
14587 ["Insert citation" org-reftex-citation t]
14588 "--"
14589 ["Export LaTeX fragments as images"
14590 (if (featurep 'org-exp)
14591 (setq org-export-with-LaTeX-fragments
14592 (not org-export-with-LaTeX-fragments))
14593 (require 'org-exp))
14594 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14595 org-export-with-LaTeX-fragments)])
14596 "--"
14597 ("Documentation"
14598 ["Show Version" org-version t]
14599 ["Info Documentation" org-info t])
14600 ("Customize"
14601 ["Browse Org Group" org-customize t]
14602 "--"
14603 ["Expand This Menu" org-create-customize-menu
14604 (fboundp 'customize-menu-create)])
14605 "--"
14606 ("Refresh/Reload"
14607 ["Refresh setup current buffer" org-mode-restart t]
14608 ["Reload Org (after update)" org-reload t]
14609 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
14612 (defun org-info (&optional node)
14613 "Read documentation for Org-mode in the info system.
14614 With optional NODE, go directly to that node."
14615 (interactive)
14616 (info (format "(org)%s" (or node ""))))
14618 (defun org-install-agenda-files-menu ()
14619 (let ((bl (buffer-list)))
14620 (save-excursion
14621 (while bl
14622 (set-buffer (pop bl))
14623 (if (org-mode-p) (setq bl nil)))
14624 (when (org-mode-p)
14625 (easy-menu-change
14626 '("Org") "File List for Agenda"
14627 (append
14628 (list
14629 ["Edit File List" (org-edit-agenda-file-list) t]
14630 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14631 ["Remove Current File from List" org-remove-file t]
14632 ["Cycle through agenda files" org-cycle-agenda-files t]
14633 ["Occur in all agenda files" org-occur-in-agenda-files t]
14634 "--")
14635 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14637 ;;;; Documentation
14639 ;;;###autoload
14640 (defun org-require-autoloaded-modules ()
14641 (interactive)
14642 (mapc 'require
14643 '(org-agenda org-archive org-attach org-clock org-colview
14644 org-exp org-id org-export-latex org-docbook
14645 org-publish org-remember org-table org-timer)))
14647 ;;;###autoload
14648 (defun org-reload (&optional uncompiled)
14649 "Reload all org lisp files.
14650 With prefix arg UNCOMPILED, load the uncompiled versions."
14651 (interactive "P")
14652 (require 'find-func)
14653 (let* ((dir (file-name-directory (find-library-name "org")))
14654 (files (directory-files dir t "\\.el\\'"))
14655 (remove-re (concat (if (featurep 'xemacs)
14656 "org-colview" "org-colview-xemacs")
14657 "\\'")))
14658 (setq files (mapcar 'file-name-sans-extension files))
14659 (setq files (mapcar
14660 (lambda (x) (if (string-match remove-re x) nil x))
14661 files))
14662 (setq files (delq nil files))
14663 (mapc
14664 (lambda (f)
14665 (if (and (not uncompiled)
14666 (file-exists-p (concat f ".elc")))
14667 (load (concat f ".elc") nil nil t)
14668 (load (concat f ".el") nil nil t)))
14669 files)))
14671 ;;;###autoload
14672 (defun org-customize ()
14673 "Call the customize function with org as argument."
14674 (interactive)
14675 (org-load-modules-maybe)
14676 (org-require-autoloaded-modules)
14677 (customize-browse 'org))
14679 (defun org-create-customize-menu ()
14680 "Create a full customization menu for Org-mode, insert it into the menu."
14681 (interactive)
14682 (org-load-modules-maybe)
14683 (org-require-autoloaded-modules)
14684 (if (fboundp 'customize-menu-create)
14685 (progn
14686 (easy-menu-change
14687 '("Org") "Customize"
14688 `(["Browse Org group" org-customize t]
14689 "--"
14690 ,(customize-menu-create 'org)
14691 ["Set" Custom-set t]
14692 ["Save" Custom-save t]
14693 ["Reset to Current" Custom-reset-current t]
14694 ["Reset to Saved" Custom-reset-saved t]
14695 ["Reset to Standard Settings" Custom-reset-standard t]))
14696 (message "\"Org\"-menu now contains full customization menu"))
14697 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14699 ;;;; Miscellaneous stuff
14701 ;;; Generally useful functions
14703 (defun org-find-text-property-in-string (prop s)
14704 "Return the first non-nil value of property PROP in string S."
14705 (or (get-text-property 0 prop s)
14706 (get-text-property (or (next-single-property-change 0 prop s) 0)
14707 prop s)))
14709 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14710 "Display the given MESSAGE as a warning."
14711 (if (fboundp 'display-warning)
14712 (display-warning 'org message
14713 (if (featurep 'xemacs)
14714 'warning
14715 :warning))
14716 (let ((buf (get-buffer-create "*Org warnings*")))
14717 (with-current-buffer buf
14718 (goto-char (point-max))
14719 (insert "Warning (Org): " message)
14720 (unless (bolp)
14721 (newline)))
14722 (display-buffer buf)
14723 (sit-for 0))))
14725 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14726 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14727 (if (and marker (marker-buffer marker)
14728 (buffer-live-p (marker-buffer marker)))
14729 (progn
14730 (switch-to-buffer (marker-buffer marker))
14731 (if (or (> marker (point-max)) (< marker (point-min)))
14732 (widen))
14733 (goto-char marker)
14734 (org-show-context 'org-goto))
14735 (if bookmark
14736 (bookmark-jump bookmark)
14737 (error "Cannot find location"))))
14739 (defun org-quote-csv-field (s)
14740 "Quote field for inclusion in CSV material."
14741 (if (string-match "[\",]" s)
14742 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14745 (defun org-plist-delete (plist property)
14746 "Delete PROPERTY from PLIST.
14747 This is in contrast to merely setting it to 0."
14748 (let (p)
14749 (while plist
14750 (if (not (eq property (car plist)))
14751 (setq p (plist-put p (car plist) (nth 1 plist))))
14752 (setq plist (cddr plist)))
14755 (defun org-force-self-insert (N)
14756 "Needed to enforce self-insert under remapping."
14757 (interactive "p")
14758 (self-insert-command N))
14760 (defun org-string-width (s)
14761 "Compute width of string, ignoring invisible characters.
14762 This ignores character with invisibility property `org-link', and also
14763 characters with property `org-cwidth', because these will become invisible
14764 upon the next fontification round."
14765 (let (b l)
14766 (when (or (eq t buffer-invisibility-spec)
14767 (assq 'org-link buffer-invisibility-spec))
14768 (while (setq b (text-property-any 0 (length s)
14769 'invisible 'org-link s))
14770 (setq s (concat (substring s 0 b)
14771 (substring s (or (next-single-property-change
14772 b 'invisible s) (length s)))))))
14773 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14774 (setq s (concat (substring s 0 b)
14775 (substring s (or (next-single-property-change
14776 b 'org-cwidth s) (length s))))))
14777 (setq l (string-width s) b -1)
14778 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14779 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14782 (defun org-get-indentation (&optional line)
14783 "Get the indentation of the current line, interpreting tabs.
14784 When LINE is given, assume it represents a line and compute its indentation."
14785 (if line
14786 (if (string-match "^ *" (org-remove-tabs line))
14787 (match-end 0))
14788 (save-excursion
14789 (beginning-of-line 1)
14790 (skip-chars-forward " \t")
14791 (current-column))))
14793 (defun org-remove-tabs (s &optional width)
14794 "Replace tabulators in S with spaces.
14795 Assumes that s is a single line, starting in column 0."
14796 (setq width (or width tab-width))
14797 (while (string-match "\t" s)
14798 (setq s (replace-match
14799 (make-string
14800 (- (* width (/ (+ (match-beginning 0) width) width))
14801 (match-beginning 0)) ?\ )
14802 t t s)))
14805 (defun org-fix-indentation (line ind)
14806 "Fix indentation in LINE.
14807 IND is a cons cell with target and minimum indentation.
14808 If the current indentation in LINE is smaller than the minimum,
14809 leave it alone. If it is larger than ind, set it to the target."
14810 (let* ((l (org-remove-tabs line))
14811 (i (org-get-indentation l))
14812 (i1 (car ind)) (i2 (cdr ind)))
14813 (if (>= i i2) (setq l (substring line i2)))
14814 (if (> i1 0)
14815 (concat (make-string i1 ?\ ) l)
14816 l)))
14818 (defun org-base-buffer (buffer)
14819 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14820 (if (not buffer)
14821 buffer
14822 (or (buffer-base-buffer buffer)
14823 buffer)))
14825 (defun org-trim (s)
14826 "Remove whitespace at beginning and end of string."
14827 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14828 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14831 (defun org-wrap (string &optional width lines)
14832 "Wrap string to either a number of lines, or a width in characters.
14833 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14834 that costs. If there is a word longer than WIDTH, the text is actually
14835 wrapped to the length of that word.
14836 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14837 many lines, whatever width that takes.
14838 The return value is a list of lines, without newlines at the end."
14839 (let* ((words (org-split-string string "[ \t\n]+"))
14840 (maxword (apply 'max (mapcar 'org-string-width words)))
14841 w ll)
14842 (cond (width
14843 (org-do-wrap words (max maxword width)))
14844 (lines
14845 (setq w maxword)
14846 (setq ll (org-do-wrap words maxword))
14847 (if (<= (length ll) lines)
14849 (setq ll words)
14850 (while (> (length ll) lines)
14851 (setq w (1+ w))
14852 (setq ll (org-do-wrap words w)))
14853 ll))
14854 (t (error "Cannot wrap this")))))
14856 (defun org-do-wrap (words width)
14857 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14858 (let (lines line)
14859 (while words
14860 (setq line (pop words))
14861 (while (and words (< (+ (length line) (length (car words))) width))
14862 (setq line (concat line " " (pop words))))
14863 (setq lines (push line lines)))
14864 (nreverse lines)))
14866 (defun org-split-string (string &optional separators)
14867 "Splits STRING into substrings at SEPARATORS.
14868 No empty strings are returned if there are matches at the beginning
14869 and end of string."
14870 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14871 (start 0)
14872 notfirst
14873 (list nil))
14874 (while (and (string-match rexp string
14875 (if (and notfirst
14876 (= start (match-beginning 0))
14877 (< start (length string)))
14878 (1+ start) start))
14879 (< (match-beginning 0) (length string)))
14880 (setq notfirst t)
14881 (or (eq (match-beginning 0) 0)
14882 (and (eq (match-beginning 0) (match-end 0))
14883 (eq (match-beginning 0) start))
14884 (setq list
14885 (cons (substring string start (match-beginning 0))
14886 list)))
14887 (setq start (match-end 0)))
14888 (or (eq start (length string))
14889 (setq list
14890 (cons (substring string start)
14891 list)))
14892 (nreverse list)))
14894 (defun org-uuidgen-p (s)
14895 "Is S an ID created by UUIDGEN?"
14896 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
14898 (defun org-context ()
14899 "Return a list of contexts of the current cursor position.
14900 If several contexts apply, all are returned.
14901 Each context entry is a list with a symbol naming the context, and
14902 two positions indicating start and end of the context. Possible
14903 contexts are:
14905 :headline anywhere in a headline
14906 :headline-stars on the leading stars in a headline
14907 :todo-keyword on a TODO keyword (including DONE) in a headline
14908 :tags on the TAGS in a headline
14909 :priority on the priority cookie in a headline
14910 :item on the first line of a plain list item
14911 :item-bullet on the bullet/number of a plain list item
14912 :checkbox on the checkbox in a plain list item
14913 :table in an org-mode table
14914 :table-special on a special filed in a table
14915 :table-table in a table.el table
14916 :link on a hyperlink
14917 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14918 :target on a <<target>>
14919 :radio-target on a <<<radio-target>>>
14920 :latex-fragment on a LaTeX fragment
14921 :latex-preview on a LaTeX fragment with overlayed preview image
14923 This function expects the position to be visible because it uses font-lock
14924 faces as a help to recognize the following contexts: :table-special, :link,
14925 and :keyword."
14926 (let* ((f (get-text-property (point) 'face))
14927 (faces (if (listp f) f (list f)))
14928 (p (point)) clist o)
14929 ;; First the large context
14930 (cond
14931 ((org-on-heading-p t)
14932 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14933 (when (progn
14934 (beginning-of-line 1)
14935 (looking-at org-todo-line-tags-regexp))
14936 (push (org-point-in-group p 1 :headline-stars) clist)
14937 (push (org-point-in-group p 2 :todo-keyword) clist)
14938 (push (org-point-in-group p 4 :tags) clist))
14939 (goto-char p)
14940 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14941 (if (looking-at "\\[#[A-Z0-9]\\]")
14942 (push (org-point-in-group p 0 :priority) clist)))
14944 ((org-at-item-p)
14945 (push (org-point-in-group p 2 :item-bullet) clist)
14946 (push (list :item (point-at-bol)
14947 (save-excursion (org-end-of-item) (point)))
14948 clist)
14949 (and (org-at-item-checkbox-p)
14950 (push (org-point-in-group p 0 :checkbox) clist)))
14952 ((org-at-table-p)
14953 (push (list :table (org-table-begin) (org-table-end)) clist)
14954 (if (memq 'org-formula faces)
14955 (push (list :table-special
14956 (previous-single-property-change p 'face)
14957 (next-single-property-change p 'face)) clist)))
14958 ((org-at-table-p 'any)
14959 (push (list :table-table) clist)))
14960 (goto-char p)
14962 ;; Now the small context
14963 (cond
14964 ((org-at-timestamp-p)
14965 (push (org-point-in-group p 0 :timestamp) clist))
14966 ((memq 'org-link faces)
14967 (push (list :link
14968 (previous-single-property-change p 'face)
14969 (next-single-property-change p 'face)) clist))
14970 ((memq 'org-special-keyword faces)
14971 (push (list :keyword
14972 (previous-single-property-change p 'face)
14973 (next-single-property-change p 'face)) clist))
14974 ((org-on-target-p)
14975 (push (org-point-in-group p 0 :target) clist)
14976 (goto-char (1- (match-beginning 0)))
14977 (if (looking-at org-radio-target-regexp)
14978 (push (org-point-in-group p 0 :radio-target) clist))
14979 (goto-char p))
14980 ((setq o (car (delq nil
14981 (mapcar
14982 (lambda (x)
14983 (if (memq x org-latex-fragment-image-overlays) x))
14984 (org-overlays-at (point))))))
14985 (push (list :latex-fragment
14986 (org-overlay-start o) (org-overlay-end o)) clist)
14987 (push (list :latex-preview
14988 (org-overlay-start o) (org-overlay-end o)) clist))
14989 ((org-inside-LaTeX-fragment-p)
14990 ;; FIXME: positions wrong.
14991 (push (list :latex-fragment (point) (point)) clist)))
14993 (setq clist (nreverse (delq nil clist)))
14994 clist))
14996 ;; FIXME: Compare with at-regexp-p Do we need both?
14997 (defun org-in-regexp (re &optional nlines visually)
14998 "Check if point is inside a match of regexp.
14999 Normally only the current line is checked, but you can include NLINES extra
15000 lines both before and after point into the search.
15001 If VISUALLY is set, require that the cursor is not after the match but
15002 really on, so that the block visually is on the match."
15003 (catch 'exit
15004 (let ((pos (point))
15005 (eol (point-at-eol (+ 1 (or nlines 0))))
15006 (inc (if visually 1 0)))
15007 (save-excursion
15008 (beginning-of-line (- 1 (or nlines 0)))
15009 (while (re-search-forward re eol t)
15010 (if (and (<= (match-beginning 0) pos)
15011 (>= (+ inc (match-end 0)) pos))
15012 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15014 (defun org-at-regexp-p (regexp)
15015 "Is point inside a match of REGEXP in the current line?"
15016 (catch 'exit
15017 (save-excursion
15018 (let ((pos (point)) (end (point-at-eol)))
15019 (beginning-of-line 1)
15020 (while (re-search-forward regexp end t)
15021 (if (and (<= (match-beginning 0) pos)
15022 (>= (match-end 0) pos))
15023 (throw 'exit t)))
15024 nil))))
15026 (defun org-occur-in-agenda-files (regexp &optional nlines)
15027 "Call `multi-occur' with buffers for all agenda files."
15028 (interactive "sOrg-files matching: \np")
15029 (let* ((files (org-agenda-files))
15030 (tnames (mapcar 'file-truename files))
15031 (extra org-agenda-text-search-extra-files)
15033 (when (eq (car extra) 'agenda-archives)
15034 (setq extra (cdr extra))
15035 (setq files (org-add-archive-files files)))
15036 (while (setq f (pop extra))
15037 (unless (member (file-truename f) tnames)
15038 (add-to-list 'files f 'append)
15039 (add-to-list 'tnames (file-truename f) 'append)))
15040 (multi-occur
15041 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15042 regexp)))
15044 (if (boundp 'occur-mode-find-occurrence-hook)
15045 ;; Emacs 23
15046 (add-hook 'occur-mode-find-occurrence-hook
15047 (lambda ()
15048 (when (org-mode-p)
15049 (org-reveal))))
15050 ;; Emacs 22
15051 (defadvice occur-mode-goto-occurrence
15052 (after org-occur-reveal activate)
15053 (and (org-mode-p) (org-reveal)))
15054 (defadvice occur-mode-goto-occurrence-other-window
15055 (after org-occur-reveal activate)
15056 (and (org-mode-p) (org-reveal)))
15057 (defadvice occur-mode-display-occurrence
15058 (after org-occur-reveal activate)
15059 (when (org-mode-p)
15060 (let ((pos (occur-mode-find-occurrence)))
15061 (with-current-buffer (marker-buffer pos)
15062 (save-excursion
15063 (goto-char pos)
15064 (org-reveal)))))))
15066 (defun org-uniquify (list)
15067 "Remove duplicate elements from LIST."
15068 (let (res)
15069 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15070 res))
15072 (defun org-delete-all (elts list)
15073 "Remove all elements in ELTS from LIST."
15074 (while elts
15075 (setq list (delete (pop elts) list)))
15076 list)
15078 (defun org-back-over-empty-lines ()
15079 "Move backwards over whitespace, to the beginning of the first empty line.
15080 Returns the number of empty lines passed."
15081 (let ((pos (point)))
15082 (skip-chars-backward " \t\n\r")
15083 (beginning-of-line 2)
15084 (goto-char (min (point) pos))
15085 (count-lines (point) pos)))
15087 (defun org-skip-whitespace ()
15088 (skip-chars-forward " \t\n\r"))
15090 (defun org-point-in-group (point group &optional context)
15091 "Check if POINT is in match-group GROUP.
15092 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15093 match. If the match group does ot exist or point is not inside it,
15094 return nil."
15095 (and (match-beginning group)
15096 (>= point (match-beginning group))
15097 (<= point (match-end group))
15098 (if context
15099 (list context (match-beginning group) (match-end group))
15100 t)))
15102 (defun org-switch-to-buffer-other-window (&rest args)
15103 "Switch to buffer in a second window on the current frame.
15104 In particular, do not allow pop-up frames."
15105 (let (pop-up-frames special-display-buffer-names special-display-regexps
15106 special-display-function)
15107 (apply 'switch-to-buffer-other-window args)))
15109 (defun org-combine-plists (&rest plists)
15110 "Create a single property list from all plists in PLISTS.
15111 The process starts by copying the first list, and then setting properties
15112 from the other lists. Settings in the last list are the most significant
15113 ones and overrule settings in the other lists."
15114 (let ((rtn (copy-sequence (pop plists)))
15115 p v ls)
15116 (while plists
15117 (setq ls (pop plists))
15118 (while ls
15119 (setq p (pop ls) v (pop ls))
15120 (setq rtn (plist-put rtn p v))))
15121 rtn))
15123 (defun org-move-line-down (arg)
15124 "Move the current line down. With prefix argument, move it past ARG lines."
15125 (interactive "p")
15126 (let ((col (current-column))
15127 beg end pos)
15128 (beginning-of-line 1) (setq beg (point))
15129 (beginning-of-line 2) (setq end (point))
15130 (beginning-of-line (+ 1 arg))
15131 (setq pos (move-marker (make-marker) (point)))
15132 (insert (delete-and-extract-region beg end))
15133 (goto-char pos)
15134 (org-move-to-column col)))
15136 (defun org-move-line-up (arg)
15137 "Move the current line up. With prefix argument, move it past ARG lines."
15138 (interactive "p")
15139 (let ((col (current-column))
15140 beg end pos)
15141 (beginning-of-line 1) (setq beg (point))
15142 (beginning-of-line 2) (setq end (point))
15143 (beginning-of-line (- arg))
15144 (setq pos (move-marker (make-marker) (point)))
15145 (insert (delete-and-extract-region beg end))
15146 (goto-char pos)
15147 (org-move-to-column col)))
15149 (defun org-replace-escapes (string table)
15150 "Replace %-escapes in STRING with values in TABLE.
15151 TABLE is an association list with keys like \"%a\" and string values.
15152 The sequences in STRING may contain normal field width and padding information,
15153 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15154 so values can contain further %-escapes if they are define later in TABLE."
15155 (let ((case-fold-search nil)
15156 e re rpl)
15157 (while (setq e (pop table))
15158 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15159 (while (string-match re string)
15160 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15161 (cdr e)))
15162 (setq string (replace-match rpl t t string))))
15163 string))
15166 (defun org-sublist (list start end)
15167 "Return a section of LIST, from START to END.
15168 Counting starts at 1."
15169 (let (rtn (c start))
15170 (setq list (nthcdr (1- start) list))
15171 (while (and list (<= c end))
15172 (push (pop list) rtn)
15173 (setq c (1+ c)))
15174 (nreverse rtn)))
15176 (defun org-find-base-buffer-visiting (file)
15177 "Like `find-buffer-visiting' but alway return the base buffer and
15178 not an indirect buffer."
15179 (let ((buf (find-buffer-visiting file)))
15180 (if buf
15181 (or (buffer-base-buffer buf) buf)
15182 nil)))
15184 (defun org-image-file-name-regexp (&optional extensions)
15185 "Return regexp matching the file names of images.
15186 If EXTENSIONS is given, only match these."
15187 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15188 (image-file-name-regexp)
15189 (let ((image-file-name-extensions
15190 (or extensions
15191 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15192 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15193 (concat "\\."
15194 (regexp-opt (nconc (mapcar 'upcase
15195 image-file-name-extensions)
15196 image-file-name-extensions)
15198 "\\'"))))
15200 (defun org-file-image-p (file &optional extensions)
15201 "Return non-nil if FILE is an image."
15202 (save-match-data
15203 (string-match (org-image-file-name-regexp extensions) file)))
15205 (defun org-get-cursor-date ()
15206 "Return the date at cursor in as a time.
15207 This works in the calendar and in the agenda, anywhere else it just
15208 returns the current time."
15209 (let (date day defd)
15210 (cond
15211 ((eq major-mode 'calendar-mode)
15212 (setq date (calendar-cursor-to-date)
15213 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15214 ((eq major-mode 'org-agenda-mode)
15215 (setq day (get-text-property (point) 'day))
15216 (if day
15217 (setq date (calendar-gregorian-from-absolute day)
15218 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15219 (nth 2 date))))))
15220 (or defd (current-time))))
15222 (defvar org-agenda-action-marker (make-marker)
15223 "Marker pointing to the entry for the next agenda action.")
15225 (defun org-mark-entry-for-agenda-action ()
15226 "Mark the current entry as target of an agenda action.
15227 Agenda actions are actions executed from the agenda with the key `k',
15228 which make use of the date at the cursor."
15229 (interactive)
15230 (move-marker org-agenda-action-marker
15231 (save-excursion (org-back-to-heading t) (point))
15232 (current-buffer))
15233 (message
15234 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15236 ;;; Paragraph filling stuff.
15237 ;; We want this to be just right, so use the full arsenal.
15239 (defun org-indent-line-function ()
15240 "Indent line like previous, but further if previous was headline or item."
15241 (interactive)
15242 (let* ((pos (point))
15243 (itemp (org-at-item-p))
15244 (org-drawer-regexp (or org-drawer-regexp "\000"))
15245 column bpos bcol tpos tcol bullet btype bullet-type)
15246 ;; Find the previous relevant line
15247 (beginning-of-line 1)
15248 (cond
15249 ((looking-at "#") (setq column 0))
15250 ((looking-at "\\*+ ") (setq column 0))
15251 ((and (looking-at "[ \t]*:END:")
15252 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15253 (save-excursion
15254 (goto-char (1- (match-beginning 1)))
15255 (setq column (current-column))))
15257 (beginning-of-line 0)
15258 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15259 (not (looking-at "[ \t]*:END:"))
15260 (not (looking-at org-drawer-regexp)))
15261 (beginning-of-line 0))
15262 (cond
15263 ((looking-at "\\*+[ \t]+")
15264 (if (not org-adapt-indentation)
15265 (setq column 0)
15266 (goto-char (match-end 0))
15267 (setq column (current-column))))
15268 ((looking-at org-drawer-regexp)
15269 (goto-char (1- (match-beginning 1)))
15270 (setq column (current-column)))
15271 ((looking-at "\\([ \t]*\\):END:")
15272 (goto-char (match-end 1))
15273 (setq column (current-column)))
15274 ((org-in-item-p)
15275 (org-beginning-of-item)
15276 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15277 (setq bpos (match-beginning 1) tpos (match-end 0)
15278 bcol (progn (goto-char bpos) (current-column))
15279 tcol (progn (goto-char tpos) (current-column))
15280 bullet (match-string 1)
15281 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15282 (if (> tcol (+ bcol org-description-max-indent))
15283 (setq tcol (+ bcol 5)))
15284 (if (not itemp)
15285 (setq column tcol)
15286 (goto-char pos)
15287 (beginning-of-line 1)
15288 (if (looking-at "\\S-")
15289 (progn
15290 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15291 (setq bullet (match-string 1)
15292 btype (if (string-match "[0-9]" bullet) "n" bullet))
15293 (setq column (if (equal btype bullet-type) bcol tcol)))
15294 (setq column (org-get-indentation)))))
15295 (t (setq column (org-get-indentation))))))
15296 (goto-char pos)
15297 (if (<= (current-column) (current-indentation))
15298 (org-indent-line-to column)
15299 (save-excursion (org-indent-line-to column)))
15300 (setq column (current-column))
15301 (beginning-of-line 1)
15302 (if (looking-at
15303 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15304 (replace-match (concat "\\1" (format org-property-format
15305 (match-string 2) (match-string 3)))
15306 t nil))
15307 (org-move-to-column column)))
15309 (defun org-set-autofill-regexps ()
15310 (interactive)
15311 ;; In the paragraph separator we include headlines, because filling
15312 ;; text in a line directly attached to a headline would otherwise
15313 ;; fill the headline as well.
15314 (org-set-local 'comment-start-skip "^#+[ \t]*")
15315 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15316 ;; The paragraph starter includes hand-formatted lists.
15317 (org-set-local 'paragraph-start
15318 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15319 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15320 ;; But only if the user has not turned off tables or fixed-width regions
15321 (org-set-local
15322 'auto-fill-inhibit-regexp
15323 (concat "\\*+ \\|#\\+"
15324 "\\|[ \t]*" org-keyword-time-regexp
15325 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15326 (concat
15327 "\\|[ \t]*["
15328 (if org-enable-table-editor "|" "")
15329 (if org-enable-fixed-width-editor ":" "")
15330 "]"))))
15331 ;; We use our own fill-paragraph function, to make sure that tables
15332 ;; and fixed-width regions are not wrapped. That function will pass
15333 ;; through to `fill-paragraph' when appropriate.
15334 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15335 ; Adaptive filling: To get full control, first make sure that
15336 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15337 (org-set-local 'adaptive-fill-regexp "\000")
15338 (org-set-local 'adaptive-fill-function
15339 'org-adaptive-fill-function)
15340 (org-set-local
15341 'align-mode-rules-list
15342 '((org-in-buffer-settings
15343 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15344 (modes . '(org-mode))))))
15346 (defun org-fill-paragraph (&optional justify)
15347 "Re-align a table, pass through to fill-paragraph if no table."
15348 (let ((table-p (org-at-table-p))
15349 (table.el-p (org-at-table.el-p)))
15350 (cond ((and (equal (char-after (point-at-bol)) ?*)
15351 (save-excursion (goto-char (point-at-bol))
15352 (looking-at outline-regexp)))
15353 t) ; skip headlines
15354 (table.el-p t) ; skip table.el tables
15355 (table-p (org-table-align) t) ; align org-mode tables
15356 (t nil)))) ; call paragraph-fill
15358 ;; For reference, this is the default value of adaptive-fill-regexp
15359 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15361 (defun org-adaptive-fill-function ()
15362 "Return a fill prefix for org-mode files.
15363 In particular, this makes sure hanging paragraphs for hand-formatted lists
15364 work correctly."
15365 (cond ((looking-at "#[ \t]+")
15366 (match-string 0))
15367 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15368 (save-excursion
15369 (if (> (match-end 1) (+ (match-beginning 1)
15370 org-description-max-indent))
15371 (goto-char (+ (match-beginning 1) 5))
15372 (goto-char (match-end 0)))
15373 (make-string (current-column) ?\ )))
15374 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15375 (save-excursion
15376 (goto-char (match-end 0))
15377 (make-string (current-column) ?\ )))
15378 (t nil)))
15380 ;;; Other stuff.
15382 (defun org-toggle-fixed-width-section (arg)
15383 "Toggle the fixed-width export.
15384 If there is no active region, the QUOTE keyword at the current headline is
15385 inserted or removed. When present, it causes the text between this headline
15386 and the next to be exported as fixed-width text, and unmodified.
15387 If there is an active region, this command adds or removes a colon as the
15388 first character of this line. If the first character of a line is a colon,
15389 this line is also exported in fixed-width font."
15390 (interactive "P")
15391 (let* ((cc 0)
15392 (regionp (org-region-active-p))
15393 (beg (if regionp (region-beginning) (point)))
15394 (end (if regionp (region-end)))
15395 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15396 (case-fold-search nil)
15397 (re "[ \t]*\\(: \\)")
15398 off)
15399 (if regionp
15400 (save-excursion
15401 (goto-char beg)
15402 (setq cc (current-column))
15403 (beginning-of-line 1)
15404 (setq off (looking-at re))
15405 (while (> nlines 0)
15406 (setq nlines (1- nlines))
15407 (beginning-of-line 1)
15408 (cond
15409 (arg
15410 (org-move-to-column cc t)
15411 (insert ": \n")
15412 (forward-line -1))
15413 ((and off (looking-at re))
15414 (replace-match "" t t nil 1))
15415 ((not off) (org-move-to-column cc t) (insert ": ")))
15416 (forward-line 1)))
15417 (save-excursion
15418 (org-back-to-heading)
15419 (if (looking-at (concat outline-regexp
15420 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15421 (replace-match "" t t nil 1)
15422 (if (looking-at outline-regexp)
15423 (progn
15424 (goto-char (match-end 0))
15425 (insert org-quote-string " "))))))))
15427 (defun org-reftex-citation ()
15428 "Use reftex-citation to insert a citation into the buffer.
15429 This looks for a line like
15431 #+BIBLIOGRAPHY: foo plain option:-d
15433 and derives from it that foo.bib is the bbliography file relevant
15434 for this document. It then installs the necessary environment for RefTeX
15435 to work in this buffer and calls `reftex-citation' to insert a citation
15436 into the buffer.
15438 Export of such citations to both LaTeX and HTML is handled by the contributed
15439 package org-exp-bibtex by Taru Karttunen."
15440 (interactive)
15441 (let ((reftex-docstruct-symbol 'rds)
15442 (reftex-cite-format "\\cite{%l}")
15443 rds bib)
15444 (save-excursion
15445 (save-restriction
15446 (widen)
15447 (let ((case-fold-search t)
15448 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
15449 (if (not (save-excursion
15450 (or (re-search-forward re nil t)
15451 (re-search-backward re nil t))))
15452 (error "No bibliography defined in file")
15453 (setq bib (concat (match-string 1) ".bib")
15454 rds (list (list 'bib bib)))))))
15455 (call-interactively 'reftex-citation)))
15457 ;;;; Functions extending outline functionality
15459 (defun org-beginning-of-line (&optional arg)
15460 "Go to the beginning of the current line. If that is invisible, continue
15461 to a visible line beginning. This makes the function of C-a more intuitive.
15462 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15463 first attempt, and only move to after the tags when the cursor is already
15464 beyond the end of the headline."
15465 (interactive "P")
15466 (let ((pos (point))
15467 (special (if (consp org-special-ctrl-a/e)
15468 (car org-special-ctrl-a/e)
15469 org-special-ctrl-a/e))
15470 refpos)
15471 (beginning-of-line 1)
15472 (if (and arg (fboundp 'move-beginning-of-line))
15473 (call-interactively 'move-beginning-of-line)
15474 (if (bobp)
15476 (backward-char 1)
15477 (if (org-invisible-p)
15478 (while (and (not (bobp)) (org-invisible-p))
15479 (backward-char 1)
15480 (beginning-of-line 1))
15481 (forward-char 1))))
15482 (when special
15483 (cond
15484 ((and (looking-at org-complex-heading-regexp)
15485 (= (char-after (match-end 1)) ?\ ))
15486 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15487 (point-at-eol)))
15488 (goto-char
15489 (if (eq special t)
15490 (cond ((> pos refpos) refpos)
15491 ((= pos (point)) refpos)
15492 (t (point)))
15493 (cond ((> pos (point)) (point))
15494 ((not (eq last-command this-command)) (point))
15495 (t refpos)))))
15496 ((org-at-item-p)
15497 (goto-char
15498 (if (eq special t)
15499 (cond ((> pos (match-end 4)) (match-end 4))
15500 ((= pos (point)) (match-end 4))
15501 (t (point)))
15502 (cond ((> pos (point)) (point))
15503 ((not (eq last-command this-command)) (point))
15504 (t (match-end 4))))))))
15505 (org-no-warnings
15506 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15508 (defun org-end-of-line (&optional arg)
15509 "Go to the end of the line.
15510 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15511 first attempt, and only move to after the tags when the cursor is already
15512 beyond the end of the headline."
15513 (interactive "P")
15514 (let ((special (if (consp org-special-ctrl-a/e)
15515 (cdr org-special-ctrl-a/e)
15516 org-special-ctrl-a/e)))
15517 (if (or (not special)
15518 (not (org-on-heading-p))
15519 arg)
15520 (call-interactively (if (fboundp 'move-end-of-line)
15521 'move-end-of-line
15522 'end-of-line))
15523 (let ((pos (point)))
15524 (beginning-of-line 1)
15525 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15526 (if (eq special t)
15527 (if (or (< pos (match-beginning 1))
15528 (= pos (match-end 0)))
15529 (goto-char (match-beginning 1))
15530 (goto-char (match-end 0)))
15531 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15532 (goto-char (match-end 0))
15533 (goto-char (match-beginning 1))))
15534 (call-interactively (if (fboundp 'move-end-of-line)
15535 'move-end-of-line
15536 'end-of-line)))))
15537 (org-no-warnings
15538 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15540 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15541 (define-key org-mode-map "\C-e" 'org-end-of-line)
15543 (defun org-backward-sentence (&optional arg)
15544 "Go to beginning of sentence, or beginning of table field.
15545 This will call `backward-sentence' or `org-table-beginning-of-field',
15546 depending on context."
15547 (interactive "P")
15548 (cond
15549 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
15550 (t (call-interactively 'backward-sentence))))
15552 (defun org-forward-sentence (&optional arg)
15553 "Go to end of sentence, or end of table field.
15554 This will call `forward-sentence' or `org-table-end-of-field',
15555 depending on context."
15556 (interactive "P")
15557 (cond
15558 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
15559 (t (call-interactively 'forward-sentence))))
15561 (define-key org-mode-map "\M-a" 'org-backward-sentence)
15562 (define-key org-mode-map "\M-e" 'org-forward-sentence)
15564 (defun org-kill-line (&optional arg)
15565 "Kill line, to tags or end of line."
15566 (interactive "P")
15567 (cond
15568 ((or (not org-special-ctrl-k)
15569 (bolp)
15570 (not (org-on-heading-p)))
15571 (call-interactively 'kill-line))
15572 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15573 (kill-region (point) (match-beginning 1))
15574 (org-set-tags nil t))
15575 (t (kill-region (point) (point-at-eol)))))
15577 (define-key org-mode-map "\C-k" 'org-kill-line)
15579 (defun org-yank (&optional arg)
15580 "Yank. If the kill is a subtree, treat it specially.
15581 This command will look at the current kill and check if is a single
15582 subtree, or a series of subtrees[1]. If it passes the test, and if the
15583 cursor is at the beginning of a line or after the stars of a currently
15584 empty headline, then the yank is handled specially. How exactly depends
15585 on the value of the following variables, both set by default.
15587 org-yank-folded-subtrees
15588 When set, the subtree(s) will be folded after insertion, but only
15589 if doing so would now swallow text after the yanked text.
15591 org-yank-adjusted-subtrees
15592 When set, the subtree will be promoted or demoted in order to
15593 fit into the local outline tree structure, which means that the level
15594 will be adjusted so that it becomes the smaller one of the two
15595 *visible* surrounding headings.
15597 Any prefix to this command will cause `yank' to be called directly with
15598 no special treatment. In particular, a simple `C-u' prefix will just
15599 plainly yank the text as it is.
15601 \[1] Basically, the test checks if the first non-white line is a heading
15602 and if there are no other headings with fewer stars."
15603 (interactive "P")
15604 (setq this-command 'yank)
15605 (if arg
15606 (call-interactively 'yank)
15607 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15608 (and (org-kill-is-subtree-p)
15609 (or (bolp)
15610 (and (looking-at "[ \t]*$")
15611 (string-match
15612 "\\`\\*+\\'"
15613 (buffer-substring (point-at-bol) (point)))))))
15614 swallowp)
15615 (cond
15616 ((and subtreep org-yank-folded-subtrees)
15617 (let ((beg (point))
15618 end)
15619 (if (and subtreep org-yank-adjusted-subtrees)
15620 (org-paste-subtree nil nil 'for-yank)
15621 (call-interactively 'yank))
15622 (setq end (point))
15623 (goto-char beg)
15624 (when (and (bolp) subtreep
15625 (not (setq swallowp
15626 (org-yank-folding-would-swallow-text beg end))))
15627 (or (looking-at outline-regexp)
15628 (re-search-forward (concat "^" outline-regexp) end t))
15629 (while (and (< (point) end) (looking-at outline-regexp))
15630 (hide-subtree)
15631 (org-cycle-show-empty-lines 'folded)
15632 (condition-case nil
15633 (outline-forward-same-level 1)
15634 (error (goto-char end)))))
15635 (when swallowp
15636 (message
15637 "Yanked text not folded because that would swallow text"))
15638 (goto-char end)
15639 (skip-chars-forward " \t\n\r")
15640 (beginning-of-line 1)
15641 (push-mark beg 'nomsg)))
15642 ((and subtreep org-yank-adjusted-subtrees)
15643 (let ((beg (point-at-bol)))
15644 (org-paste-subtree nil nil 'for-yank)
15645 (push-mark beg 'nomsg)))
15647 (call-interactively 'yank))))))
15649 (defun org-yank-folding-would-swallow-text (beg end)
15650 "Would hide-subtree at BEG swallow any text after END?"
15651 (let (level)
15652 (save-excursion
15653 (goto-char beg)
15654 (when (or (looking-at outline-regexp)
15655 (re-search-forward (concat "^" outline-regexp) end t))
15656 (setq level (org-outline-level)))
15657 (goto-char end)
15658 (skip-chars-forward " \t\r\n\v\f")
15659 (if (or (eobp)
15660 (and (bolp) (looking-at org-outline-regexp)
15661 (<= (org-outline-level) level)))
15662 nil ; Nothing would be swallowed
15663 t)))) ; something would swallow
15665 (define-key org-mode-map "\C-y" 'org-yank)
15667 (defun org-invisible-p ()
15668 "Check if point is at a character currently not visible."
15669 ;; Early versions of noutline don't have `outline-invisible-p'.
15670 (if (fboundp 'outline-invisible-p)
15671 (outline-invisible-p)
15672 (get-char-property (point) 'invisible)))
15674 (defun org-invisible-p2 ()
15675 "Check if point is at a character currently not visible."
15676 (save-excursion
15677 (if (and (eolp) (not (bobp))) (backward-char 1))
15678 ;; Early versions of noutline don't have `outline-invisible-p'.
15679 (if (fboundp 'outline-invisible-p)
15680 (outline-invisible-p)
15681 (get-char-property (point) 'invisible))))
15683 (defun org-back-to-heading (&optional invisible-ok)
15684 "Call `outline-back-to-heading', but provide a better error message."
15685 (condition-case nil
15686 (outline-back-to-heading invisible-ok)
15687 (error (error "Before first headline at position %d in buffer %s"
15688 (point) (current-buffer)))))
15690 (defun org-before-first-heading-p ()
15691 "Before first heading?"
15692 (save-excursion
15693 (null (re-search-backward "^\\*+ " nil t))))
15695 (defalias 'org-on-heading-p 'outline-on-heading-p)
15696 (defalias 'org-at-heading-p 'outline-on-heading-p)
15697 (defun org-at-heading-or-item-p ()
15698 (or (org-on-heading-p) (org-at-item-p)))
15700 (defun org-on-target-p ()
15701 (or (org-in-regexp org-radio-target-regexp)
15702 (org-in-regexp org-target-regexp)))
15704 (defun org-up-heading-all (arg)
15705 "Move to the heading line of which the present line is a subheading.
15706 This function considers both visible and invisible heading lines.
15707 With argument, move up ARG levels."
15708 (if (fboundp 'outline-up-heading-all)
15709 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15710 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15712 (defun org-up-heading-safe ()
15713 "Move to the heading line of which the present line is a subheading.
15714 This version will not throw an error. It will return the level of the
15715 headline found, or nil if no higher level is found."
15716 (let (start-level re)
15717 (org-back-to-heading t)
15718 (setq start-level (funcall outline-level))
15719 (if (equal start-level 1)
15721 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
15722 (if (re-search-backward re nil t)
15723 (funcall outline-level)))))
15725 (defun org-first-sibling-p ()
15726 "Is this heading the first child of its parents?"
15727 (interactive)
15728 (let ((re (concat "^" outline-regexp))
15729 level l)
15730 (unless (org-at-heading-p t)
15731 (error "Not at a heading"))
15732 (setq level (funcall outline-level))
15733 (save-excursion
15734 (if (not (re-search-backward re nil t))
15736 (setq l (funcall outline-level))
15737 (< l level)))))
15739 (defun org-goto-sibling (&optional previous)
15740 "Goto the next sibling, even if it is invisible.
15741 When PREVIOUS is set, go to the previous sibling instead. Returns t
15742 when a sibling was found. When none is found, return nil and don't
15743 move point."
15744 (let ((fun (if previous 're-search-backward 're-search-forward))
15745 (pos (point))
15746 (re (concat "^" outline-regexp))
15747 level l)
15748 (when (condition-case nil (org-back-to-heading t) (error nil))
15749 (setq level (funcall outline-level))
15750 (catch 'exit
15751 (or previous (forward-char 1))
15752 (while (funcall fun re nil t)
15753 (setq l (funcall outline-level))
15754 (when (< l level) (goto-char pos) (throw 'exit nil))
15755 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15756 (goto-char pos)
15757 nil))))
15759 (defun org-show-siblings ()
15760 "Show all siblings of the current headline."
15761 (save-excursion
15762 (while (org-goto-sibling) (org-flag-heading nil)))
15763 (save-excursion
15764 (while (org-goto-sibling 'previous)
15765 (org-flag-heading nil))))
15767 (defun org-show-hidden-entry ()
15768 "Show an entry where even the heading is hidden."
15769 (save-excursion
15770 (org-show-entry)))
15772 (defun org-flag-heading (flag &optional entry)
15773 "Flag the current heading. FLAG non-nil means make invisible.
15774 When ENTRY is non-nil, show the entire entry."
15775 (save-excursion
15776 (org-back-to-heading t)
15777 ;; Check if we should show the entire entry
15778 (if entry
15779 (progn
15780 (org-show-entry)
15781 (save-excursion
15782 (and (outline-next-heading)
15783 (org-flag-heading nil))))
15784 (outline-flag-region (max (point-min) (1- (point)))
15785 (save-excursion (outline-end-of-heading) (point))
15786 flag))))
15788 (defun org-forward-same-level (arg)
15789 "Move forward to the ARG'th subheading at same level as this one.
15790 Stop at the first and last subheadings of a superior heading.
15791 This is like outline-forward-same-level, but invisible headings are ok."
15792 (interactive "p")
15793 (org-back-to-heading t)
15794 (while (> arg 0)
15795 (let ((point-to-move-to (save-excursion
15796 (org-get-next-sibling))))
15797 (if point-to-move-to
15798 (progn
15799 (goto-char point-to-move-to)
15800 (setq arg (1- arg)))
15801 (progn
15802 (setq arg 0)
15803 (error "No following same-level heading"))))))
15805 (defun org-get-next-sibling ()
15806 "Move to next heading of the same level, and return point.
15807 If there is no such heading, return nil.
15808 This is like outline-next-sibling, but invisible headings are ok."
15809 (let ((level (funcall outline-level)))
15810 (outline-next-heading)
15811 (while (and (not (eobp)) (> (funcall outline-level) level))
15812 (outline-next-heading))
15813 (if (or (eobp) (< (funcall outline-level) level))
15815 (point))))
15817 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15818 ;; This is an exact copy of the original function, but it uses
15819 ;; `org-back-to-heading', to make it work also in invisible
15820 ;; trees. And is uses an invisible-OK argument.
15821 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15822 (org-back-to-heading invisible-OK)
15823 (let ((first t)
15824 (level (funcall outline-level)))
15825 (while (and (not (eobp))
15826 (or first (> (funcall outline-level) level)))
15827 (setq first nil)
15828 (outline-next-heading))
15829 (unless to-heading
15830 (if (memq (preceding-char) '(?\n ?\^M))
15831 (progn
15832 ;; Go to end of line before heading
15833 (forward-char -1)
15834 (if (memq (preceding-char) '(?\n ?\^M))
15835 ;; leave blank line before heading
15836 (forward-char -1))))))
15837 (point))
15839 (defun org-show-subtree ()
15840 "Show everything after this heading at deeper levels."
15841 (outline-flag-region
15842 (point)
15843 (save-excursion
15844 (outline-end-of-subtree) (outline-next-heading) (point))
15845 nil))
15847 (defun org-show-entry ()
15848 "Show the body directly following this heading.
15849 Show the heading too, if it is currently invisible."
15850 (interactive)
15851 (save-excursion
15852 (condition-case nil
15853 (progn
15854 (org-back-to-heading t)
15855 (outline-flag-region
15856 (max (point-min) (1- (point)))
15857 (save-excursion
15858 (if (re-search-forward
15859 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
15860 (match-beginning 1)
15861 (point-max)))
15862 nil))
15863 (error nil))))
15865 (defun org-make-options-regexp (kwds &optional extra)
15866 "Make a regular expression for keyword lines."
15867 (concat
15869 "#?[ \t]*\\+\\("
15870 (mapconcat 'regexp-quote kwds "\\|")
15871 (if extra (concat "\\|" extra))
15872 "\\):[ \t]*"
15873 "\\(.+\\)"))
15875 ;; Make isearch reveal the necessary context
15876 (defun org-isearch-end ()
15877 "Reveal context after isearch exits."
15878 (when isearch-success ; only if search was successful
15879 (if (featurep 'xemacs)
15880 ;; Under XEmacs, the hook is run in the correct place,
15881 ;; we directly show the context.
15882 (org-show-context 'isearch)
15883 ;; In Emacs the hook runs *before* restoring the overlays.
15884 ;; So we have to use a one-time post-command-hook to do this.
15885 ;; (Emacs 22 has a special variable, see function `org-mode')
15886 (unless (and (boundp 'isearch-mode-end-hook-quit)
15887 isearch-mode-end-hook-quit)
15888 ;; Only when the isearch was not quitted.
15889 (org-add-hook 'post-command-hook 'org-isearch-post-command
15890 'append 'local)))))
15892 (defun org-isearch-post-command ()
15893 "Remove self from hook, and show context."
15894 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15895 (org-show-context 'isearch))
15898 ;;;; Integration with and fixes for other packages
15900 ;;; Imenu support
15902 (defvar org-imenu-markers nil
15903 "All markers currently used by Imenu.")
15904 (make-variable-buffer-local 'org-imenu-markers)
15906 (defun org-imenu-new-marker (&optional pos)
15907 "Return a new marker for use by Imenu, and remember the marker."
15908 (let ((m (make-marker)))
15909 (move-marker m (or pos (point)))
15910 (push m org-imenu-markers)
15913 (defun org-imenu-get-tree ()
15914 "Produce the index for Imenu."
15915 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15916 (setq org-imenu-markers nil)
15917 (let* ((n org-imenu-depth)
15918 (re (concat "^" outline-regexp))
15919 (subs (make-vector (1+ n) nil))
15920 (last-level 0)
15921 m level head)
15922 (save-excursion
15923 (save-restriction
15924 (widen)
15925 (goto-char (point-max))
15926 (while (re-search-backward re nil t)
15927 (setq level (org-reduced-level (funcall outline-level)))
15928 (when (<= level n)
15929 (looking-at org-complex-heading-regexp)
15930 (setq head (org-link-display-format
15931 (org-match-string-no-properties 4))
15932 m (org-imenu-new-marker))
15933 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15934 (if (>= level last-level)
15935 (push (cons head m) (aref subs level))
15936 (push (cons head (aref subs (1+ level))) (aref subs level))
15937 (loop for i from (1+ level) to n do (aset subs i nil)))
15938 (setq last-level level)))))
15939 (aref subs 1)))
15941 (eval-after-load "imenu"
15942 '(progn
15943 (add-hook 'imenu-after-jump-hook
15944 (lambda ()
15945 (if (eq major-mode 'org-mode)
15946 (org-show-context 'org-goto))))))
15948 (defun org-link-display-format (link)
15949 "Replace a link with either the description, or the link target
15950 if no description is present"
15951 (save-match-data
15952 (if (string-match org-bracket-link-analytic-regexp link)
15953 (replace-match (or (match-string 5 link)
15954 (concat (match-string 1 link)
15955 (match-string 3 link)))
15956 nil nil link)
15957 link)))
15959 ;; Speedbar support
15961 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15962 "Overlay marking the agenda restriction line in speedbar.")
15963 (org-overlay-put org-speedbar-restriction-lock-overlay
15964 'face 'org-agenda-restriction-lock)
15965 (org-overlay-put org-speedbar-restriction-lock-overlay
15966 'help-echo "Agendas are currently limited to this item.")
15967 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15969 (defun org-speedbar-set-agenda-restriction ()
15970 "Restrict future agenda commands to the location at point in speedbar.
15971 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15972 (interactive)
15973 (require 'org-agenda)
15974 (let (p m tp np dir txt)
15975 (cond
15976 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15977 'org-imenu t))
15978 (setq m (get-text-property p 'org-imenu-marker))
15979 (save-excursion
15980 (save-restriction
15981 (set-buffer (marker-buffer m))
15982 (goto-char m)
15983 (org-agenda-set-restriction-lock 'subtree))))
15984 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15985 'speedbar-function 'speedbar-find-file))
15986 (setq tp (previous-single-property-change
15987 (1+ p) 'speedbar-function)
15988 np (next-single-property-change
15989 tp 'speedbar-function)
15990 dir (speedbar-line-directory)
15991 txt (buffer-substring-no-properties (or tp (point-min))
15992 (or np (point-max))))
15993 (save-excursion
15994 (save-restriction
15995 (set-buffer (find-file-noselect
15996 (let ((default-directory dir))
15997 (expand-file-name txt))))
15998 (unless (org-mode-p)
15999 (error "Cannot restrict to non-Org-mode file"))
16000 (org-agenda-set-restriction-lock 'file))))
16001 (t (error "Don't know how to restrict Org-mode's agenda")))
16002 (org-move-overlay org-speedbar-restriction-lock-overlay
16003 (point-at-bol) (point-at-eol))
16004 (setq current-prefix-arg nil)
16005 (org-agenda-maybe-redo)))
16007 (eval-after-load "speedbar"
16008 '(progn
16009 (speedbar-add-supported-extension ".org")
16010 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16011 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16012 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16013 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16014 (add-hook 'speedbar-visiting-tag-hook
16015 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16018 ;;; Fixes and Hacks for problems with other packages
16020 ;; Make flyspell not check words in links, to not mess up our keymap
16021 (defun org-mode-flyspell-verify ()
16022 "Don't let flyspell put overlays at active buttons."
16023 (not (get-text-property (point) 'keymap)))
16025 ;; Make `bookmark-jump' show the jump location if it was hidden.
16026 (eval-after-load "bookmark"
16027 '(if (boundp 'bookmark-after-jump-hook)
16028 ;; We can use the hook
16029 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16030 ;; Hook not available, use advice
16031 (defadvice bookmark-jump (after org-make-visible activate)
16032 "Make the position visible."
16033 (org-bookmark-jump-unhide))))
16035 ;; Make sure saveplace show the location if it was hidden
16036 (eval-after-load "saveplace"
16037 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16038 "Make the position visible."
16039 (org-bookmark-jump-unhide)))
16041 (defun org-bookmark-jump-unhide ()
16042 "Unhide the current position, to show the bookmark location."
16043 (and (org-mode-p)
16044 (or (org-invisible-p)
16045 (save-excursion (goto-char (max (point-min) (1- (point))))
16046 (org-invisible-p)))
16047 (org-show-context 'bookmark-jump)))
16049 ;; Make session.el ignore our circular variable
16050 (eval-after-load "session"
16051 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16053 ;;;; Experimental code
16055 (defun org-closed-in-range ()
16056 "Sparse tree of items closed in a certain time range.
16057 Still experimental, may disappear in the future."
16058 (interactive)
16059 ;; Get the time interval from the user.
16060 (let* ((time1 (time-to-seconds
16061 (org-read-date nil 'to-time nil "Starting date: ")))
16062 (time2 (time-to-seconds
16063 (org-read-date nil 'to-time nil "End date:")))
16064 ;; callback function
16065 (callback (lambda ()
16066 (let ((time
16067 (time-to-seconds
16068 (apply 'encode-time
16069 (org-parse-time-string
16070 (match-string 1))))))
16071 ;; check if time in interval
16072 (and (>= time time1) (<= time time2))))))
16073 ;; make tree, check each match with the callback
16074 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16076 ;;;; Finish up
16078 (provide 'org)
16080 (run-hooks 'org-load-hook)
16082 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16084 ;;; org.el ends here