Release 6.25b
[org-mode.git] / lisp / org.el
blob32f6991105fb8ed310204edc7d769a271d6b51b3
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.25b
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.25b"
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 Finally, if the parent is blocked because of ordered siblings of its own,
1722 the child will also be blocked.
1723 This variable needs to be set before org.el is loaded, and you need to
1724 restart Emacs after a change to make the change effective. The only way
1725 to change is while Emacs is running is through the customize interface."
1726 :set (lambda (var val)
1727 (set var val)
1728 (if val
1729 (add-hook 'org-blocker-hook
1730 'org-block-todo-from-children-or-siblings-or-parent)
1731 (remove-hook 'org-blocker-hook
1732 'org-block-todo-from-children-or-siblings-or-parent)))
1733 :group 'org-todo
1734 :type 'boolean)
1736 (defcustom org-enforce-todo-checkbox-dependencies nil
1737 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1738 When this is nil, checkboxes have no influence on switching TODO states.
1739 When non-nil, you first need to check off all check boxes before the TODO
1740 entry can be switched to DONE.
1741 This variable needs to be set before org.el is loaded, and you need to
1742 restart Emacs after a change to make the change effective. The only way
1743 to change is while Emacs is running is through the customize interface."
1744 :set (lambda (var val)
1745 (set var val)
1746 (if val
1747 (add-hook 'org-blocker-hook
1748 'org-block-todo-from-checkboxes)
1749 (remove-hook 'org-blocker-hook
1750 'org-block-todo-from-checkboxes)))
1751 :group 'org-todo
1752 :type 'boolean)
1754 (defcustom org-todo-state-tags-triggers nil
1755 "Tag changes that should be triggered by TODO state changes.
1756 This is a list. Each entry is
1758 (state-change (tag . flag) .......)
1760 State-change can be a string with a state, and empty string to indicate the
1761 state that has no TODO keyword, or it can be one of the symbols `todo'
1762 or `done', meaning any not-done or done state, respectively."
1763 :group 'org-todo
1764 :group 'org-tags
1765 :type '(repeat
1766 (cons (choice :tag "When changing to"
1767 (const :tag "Not-done state" todo)
1768 (const :tag "Done state" done)
1769 (string :tag "State"))
1770 (repeat
1771 (cons :tag "Tag action"
1772 (string :tag "Tag")
1773 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1775 (defcustom org-log-done nil
1776 "Information to record when a task moves to the DONE state.
1778 Possible values are:
1780 nil Don't add anything, just change the keyword
1781 time Add a time stamp to the task
1782 note Prompt a closing note and add it with template `org-log-note-headings'
1784 This option can also be set with on a per-file-basis with
1786 #+STARTUP: nologdone
1787 #+STARTUP: logdone
1788 #+STARTUP: lognotedone
1790 You can have local logging settings for a subtree by setting the LOGGING
1791 property to one or more of these keywords."
1792 :group 'org-todo
1793 :group 'org-progress
1794 :type '(choice
1795 (const :tag "No logging" nil)
1796 (const :tag "Record CLOSED timestamp" time)
1797 (const :tag "Record CLOSED timestamp with closing note." note)))
1799 ;; Normalize old uses of org-log-done.
1800 (cond
1801 ((eq org-log-done t) (setq org-log-done 'time))
1802 ((and (listp org-log-done) (memq 'done org-log-done))
1803 (setq org-log-done 'note)))
1805 (defcustom org-log-note-clock-out nil
1806 "Non-nil means, record a note when clocking out of an item.
1807 This can also be configured on a per-file basis by adding one of
1808 the following lines anywhere in the buffer:
1810 #+STARTUP: lognoteclock-out
1811 #+STARTUP: nolognoteclock-out"
1812 :group 'org-todo
1813 :group 'org-progress
1814 :type 'boolean)
1816 (defcustom org-log-done-with-time t
1817 "Non-nil means, the CLOSED time stamp will contain date and time.
1818 When nil, only the date will be recorded."
1819 :group 'org-progress
1820 :type 'boolean)
1822 (defcustom org-log-note-headings
1823 '((done . "CLOSING NOTE %t")
1824 (state . "State %-12s from %-12S %t")
1825 (note . "Note taken on %t")
1826 (clock-out . ""))
1827 "Headings for notes added to entries.
1828 The value is an alist, with the car being a symbol indicating the note
1829 context, and the cdr is the heading to be used. The heading may also be the
1830 empty string.
1831 %t in the heading will be replaced by a time stamp.
1832 %s will be replaced by the new TODO state, in double quotes.
1833 %S will be replaced by the old TODO state, in double quotes.
1834 %u will be replaced by the user name.
1835 %U will be replaced by the full user name."
1836 :group 'org-todo
1837 :group 'org-progress
1838 :type '(list :greedy t
1839 (cons (const :tag "Heading when closing an item" done) string)
1840 (cons (const :tag
1841 "Heading when changing todo state (todo sequence only)"
1842 state) string)
1843 (cons (const :tag "Heading when just taking a note" note) string)
1844 (cons (const :tag "Heading when clocking out" clock-out) string)))
1846 (unless (assq 'note org-log-note-headings)
1847 (push '(note . "%t") org-log-note-headings))
1849 (defcustom org-log-into-drawer nil
1850 "Non-nil means, insert state change notes and time stamps into a drawer.
1851 When nil, state changes notes will be inserted after the headline and
1852 any scheduling and clock lines, but not inside a drawer.
1854 The value of this variable should be the name of the drawer to use.
1855 LOGBOOK is proposed at the default drawer for this purpose, you can
1856 also set this to a string to define the drawer of your choice.
1858 A value of t is also allowed, representing \"LOGBOOK\".
1860 If this variable is set, `org-log-state-notes-insert-after-drawers'
1861 will be ignored."
1862 :group 'org-todo
1863 :group 'org-progress
1864 :type '(choice
1865 (const :tag "Not into a drawer" nil)
1866 (const :tag "LOGBOOK" t)
1867 (string :tag "Other")))
1869 (if (fboundp 'defvaralias)
1870 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1872 (defcustom org-log-state-notes-insert-after-drawers nil
1873 "Non-nil means, insert state change notes after any drawers in entry.
1874 Only the drawers that *immediately* follow the headline and the
1875 deadline/scheduled line are skipped.
1876 When nil, insert notes right after the heading and perhaps the line
1877 with deadline/scheduling if present.
1879 This variable will have no effect if `org-log-into-drawer' is
1880 set."
1881 :group 'org-todo
1882 :group 'org-progress
1883 :type 'boolean)
1885 (defcustom org-log-states-order-reversed t
1886 "Non-nil means, the latest state change note will be directly after heading.
1887 When nil, the notes will be orderer according to time."
1888 :group 'org-todo
1889 :group 'org-progress
1890 :type 'boolean)
1892 (defcustom org-log-repeat 'time
1893 "Non-nil means, record moving through the DONE state when triggering repeat.
1894 An auto-repeating tasks is immediately switched back to TODO when marked
1895 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1896 the TODO keyword definition, or recording a closing note by setting
1897 `org-log-done', there will be no record of the task moving through DONE.
1898 This variable forces taking a note anyway. Possible values are:
1900 nil Don't force a record
1901 time Record a time stamp
1902 note Record a note
1904 This option can also be set with on a per-file-basis with
1906 #+STARTUP: logrepeat
1907 #+STARTUP: lognoterepeat
1908 #+STARTUP: nologrepeat
1910 You can have local logging settings for a subtree by setting the LOGGING
1911 property to one or more of these keywords."
1912 :group 'org-todo
1913 :group 'org-progress
1914 :type '(choice
1915 (const :tag "Don't force a record" nil)
1916 (const :tag "Force recording the DONE state" time)
1917 (const :tag "Force recording a note with the DONE state" note)))
1920 (defgroup org-priorities nil
1921 "Priorities in Org-mode."
1922 :tag "Org Priorities"
1923 :group 'org-todo)
1925 (defcustom org-highest-priority ?A
1926 "The highest priority of TODO items. A character like ?A, ?B etc.
1927 Must have a smaller ASCII number than `org-lowest-priority'."
1928 :group 'org-priorities
1929 :type 'character)
1931 (defcustom org-lowest-priority ?C
1932 "The lowest priority of TODO items. A character like ?A, ?B etc.
1933 Must have a larger ASCII number than `org-highest-priority'."
1934 :group 'org-priorities
1935 :type 'character)
1937 (defcustom org-default-priority ?B
1938 "The default priority of TODO items.
1939 This is the priority an item get if no explicit priority is given."
1940 :group 'org-priorities
1941 :type 'character)
1943 (defcustom org-priority-start-cycle-with-default t
1944 "Non-nil means, start with default priority when starting to cycle.
1945 When this is nil, the first step in the cycle will be (depending on the
1946 command used) one higher or lower that the default priority."
1947 :group 'org-priorities
1948 :type 'boolean)
1950 (defgroup org-time nil
1951 "Options concerning time stamps and deadlines in Org-mode."
1952 :tag "Org Time"
1953 :group 'org)
1955 (defcustom org-insert-labeled-timestamps-at-point nil
1956 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1957 When nil, these labeled time stamps are forces into the second line of an
1958 entry, just after the headline. When scheduling from the global TODO list,
1959 the time stamp will always be forced into the second line."
1960 :group 'org-time
1961 :type 'boolean)
1963 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1964 "Formats for `format-time-string' which are used for time stamps.
1965 It is not recommended to change this constant.")
1967 (defcustom org-time-stamp-rounding-minutes '(0 5)
1968 "Number of minutes to round time stamps to.
1969 These are two values, the first applies when first creating a time stamp.
1970 The second applies when changing it with the commands `S-up' and `S-down'.
1971 When changing the time stamp, this means that it will change in steps
1972 of N minutes, as given by the second value.
1974 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1975 numbers should be factors of 60, so for example 5, 10, 15.
1977 When this is larger than 1, you can still force an exact time-stamp by using
1978 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1979 and by using a prefix arg to `S-up/down' to specify the exact number
1980 of minutes to shift."
1981 :group 'org-time
1982 :get '(lambda (var) ; Make sure all entries have 5 elements
1983 (if (integerp (default-value var))
1984 (list (default-value var) 5)
1985 (default-value var)))
1986 :type '(list
1987 (integer :tag "when inserting times")
1988 (integer :tag "when modifying times")))
1990 ;; Normalize old customizations of this variable.
1991 (when (integerp org-time-stamp-rounding-minutes)
1992 (setq org-time-stamp-rounding-minutes
1993 (list org-time-stamp-rounding-minutes
1994 org-time-stamp-rounding-minutes)))
1996 (defcustom org-display-custom-times nil
1997 "Non-nil means, overlay custom formats over all time stamps.
1998 The formats are defined through the variable `org-time-stamp-custom-formats'.
1999 To turn this on on a per-file basis, insert anywhere in the file:
2000 #+STARTUP: customtime"
2001 :group 'org-time
2002 :set 'set-default
2003 :type 'sexp)
2004 (make-variable-buffer-local 'org-display-custom-times)
2006 (defcustom org-time-stamp-custom-formats
2007 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2008 "Custom formats for time stamps. See `format-time-string' for the syntax.
2009 These are overlayed over the default ISO format if the variable
2010 `org-display-custom-times' is set. Time like %H:%M should be at the
2011 end of the second format."
2012 :group 'org-time
2013 :type 'sexp)
2015 (defun org-time-stamp-format (&optional long inactive)
2016 "Get the right format for a time string."
2017 (let ((f (if long (cdr org-time-stamp-formats)
2018 (car org-time-stamp-formats))))
2019 (if inactive
2020 (concat "[" (substring f 1 -1) "]")
2021 f)))
2023 (defcustom org-time-clocksum-format "%d:%02d"
2024 "The format string used when creating CLOCKSUM lines, or when
2025 org-mode generates a time duration."
2026 :group 'org-time
2027 :type 'string)
2029 (defcustom org-deadline-warning-days 14
2030 "No. of days before expiration during which a deadline becomes active.
2031 This variable governs the display in sparse trees and in the agenda.
2032 When 0 or negative, it means use this number (the absolute value of it)
2033 even if a deadline has a different individual lead time specified.
2035 Custom commands can set this variable in the options section."
2036 :group 'org-time
2037 :group 'org-agenda-daily/weekly
2038 :type 'integer)
2040 (defcustom org-read-date-prefer-future t
2041 "Non-nil means, assume future for incomplete date input from user.
2042 This affects the following situations:
2043 1. The user gives a day, but no month.
2044 For example, if today is the 15th, and you enter \"3\", Org-mode will
2045 read this as the third of *next* month. However, if you enter \"17\",
2046 it will be considered as *this* month.
2047 2. The user gives a month but not a year.
2048 For example, if it is april and you enter \"feb 2\", this will be read
2049 as feb 2, *next* year. \"May 5\", however, will be this year.
2051 Currently this does not work for ISO week specifications.
2053 When this option is nil, the current month and year will always be used
2054 as defaults."
2055 :group 'org-time
2056 :type 'boolean)
2058 (defcustom org-read-date-display-live t
2059 "Non-nil means, display current interpretation of date prompt live.
2060 This display will be in an overlay, in the minibuffer."
2061 :group 'org-time
2062 :type 'boolean)
2064 (defcustom org-read-date-popup-calendar t
2065 "Non-nil means, pop up a calendar when prompting for a date.
2066 In the calendar, the date can be selected with mouse-1. However, the
2067 minibuffer will also be active, and you can simply enter the date as well.
2068 When nil, only the minibuffer will be available."
2069 :group 'org-time
2070 :type 'boolean)
2071 (if (fboundp 'defvaralias)
2072 (defvaralias 'org-popup-calendar-for-date-prompt
2073 'org-read-date-popup-calendar))
2075 (defcustom org-read-date-minibuffer-setup-hook nil
2076 "Hook to be used to set up keys for the date/time interface.
2077 Add key definitions to `minibuffer-local-map', which will be a temporary
2078 copy."
2079 :group 'org-time
2080 :type 'hook)
2082 (defcustom org-extend-today-until 0
2083 "The hour when your day really ends. Must be an integer.
2084 This has influence for the following applications:
2085 - When switching the agenda to \"today\". It it is still earlier than
2086 the time given here, the day recognized as TODAY is actually yesterday.
2087 - When a date is read from the user and it is still before the time given
2088 here, the current date and time will be assumed to be yesterday, 23:59.
2089 Also, timestamps inserted in remember templates follow this rule.
2091 IMPORTANT: This is a feature whose implementation is and likely will
2092 remain incomplete. Really, it is only here because past midnight seems to
2093 be the favorite working time of John Wiegley :-)"
2094 :group 'org-time
2095 :type 'integer)
2097 (defcustom org-edit-timestamp-down-means-later nil
2098 "Non-nil means, S-down will increase the time in a time stamp.
2099 When nil, S-up will increase."
2100 :group 'org-time
2101 :type 'boolean)
2103 (defcustom org-calendar-follow-timestamp-change t
2104 "Non-nil means, make the calendar window follow timestamp changes.
2105 When a timestamp is modified and the calendar window is visible, it will be
2106 moved to the new date."
2107 :group 'org-time
2108 :type 'boolean)
2110 (defgroup org-tags nil
2111 "Options concerning tags in Org-mode."
2112 :tag "Org Tags"
2113 :group 'org)
2115 (defcustom org-tag-alist nil
2116 "List of tags allowed in Org-mode files.
2117 When this list is nil, Org-mode will base TAG input on what is already in the
2118 buffer.
2119 The value of this variable is an alist, the car of each entry must be a
2120 keyword as a string, the cdr may be a character that is used to select
2121 that tag through the fast-tag-selection interface.
2122 See the manual for details."
2123 :group 'org-tags
2124 :type '(repeat
2125 (choice
2126 (cons (string :tag "Tag name")
2127 (character :tag "Access char"))
2128 (const :tag "Start radio group" (:startgroup))
2129 (const :tag "End radio group" (:endgroup))
2130 (const :tag "New line" (:newline)))))
2132 (defcustom org-tag-persistent-alist nil
2133 "List of tags that will always appear in all Org-mode files.
2134 This is in addition to any in buffer settings or customizations
2135 of `org-tag-alist'.
2136 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2137 The value of this variable is an alist, the car of each entry must be a
2138 keyword as a string, the cdr may be a character that is used to select
2139 that tag through the fast-tag-selection interface.
2140 See the manual for details.
2141 To disable these tags on a per-file basis, insert anywhere in the file:
2142 #+STARTUP: noptag"
2143 :group 'org-tags
2144 :type '(repeat
2145 (choice
2146 (cons (string :tag "Tag name")
2147 (character :tag "Access char"))
2148 (const :tag "Start radio group" (:startgroup))
2149 (const :tag "End radio group" (:endgroup))
2150 (const :tag "New line" (:newline)))))
2152 (defvar org-file-tags nil
2153 "List of tags that can be inherited by all entries in the file.
2154 The tags will be inherited if the variable `org-use-tag-inheritance'
2155 says they should be.
2156 This variable is populated from #+TAG lines.")
2158 (defcustom org-use-fast-tag-selection 'auto
2159 "Non-nil means, use fast tag selection scheme.
2160 This is a special interface to select and deselect tags with single keys.
2161 When nil, fast selection is never used.
2162 When the symbol `auto', fast selection is used if and only if selection
2163 characters for tags have been configured, either through the variable
2164 `org-tag-alist' or through a #+TAGS line in the buffer.
2165 When t, fast selection is always used and selection keys are assigned
2166 automatically if necessary."
2167 :group 'org-tags
2168 :type '(choice
2169 (const :tag "Always" t)
2170 (const :tag "Never" nil)
2171 (const :tag "When selection characters are configured" 'auto)))
2173 (defcustom org-fast-tag-selection-single-key nil
2174 "Non-nil means, fast tag selection exits after first change.
2175 When nil, you have to press RET to exit it.
2176 During fast tag selection, you can toggle this flag with `C-c'.
2177 This variable can also have the value `expert'. In this case, the window
2178 displaying the tags menu is not even shown, until you press C-c again."
2179 :group 'org-tags
2180 :type '(choice
2181 (const :tag "No" nil)
2182 (const :tag "Yes" t)
2183 (const :tag "Expert" expert)))
2185 (defvar org-fast-tag-selection-include-todo nil
2186 "Non-nil means, fast tags selection interface will also offer TODO states.
2187 This is an undocumented feature, you should not rely on it.")
2189 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2190 "The column to which tags should be indented in a headline.
2191 If this number is positive, it specifies the column. If it is negative,
2192 it means that the tags should be flushright to that column. For example,
2193 -80 works well for a normal 80 character screen."
2194 :group 'org-tags
2195 :type 'integer)
2197 (defcustom org-auto-align-tags t
2198 "Non-nil means, realign tags after pro/demotion of TODO state change.
2199 These operations change the length of a headline and therefore shift
2200 the tags around. With this options turned on, after each such operation
2201 the tags are again aligned to `org-tags-column'."
2202 :group 'org-tags
2203 :type 'boolean)
2205 (defcustom org-use-tag-inheritance t
2206 "Non-nil means, tags in levels apply also for sublevels.
2207 When nil, only the tags directly given in a specific line apply there.
2208 This may also be a list of tags that should be inherited, or a regexp that
2209 matches tags that should be inherited. Additional control is possible
2210 with the variable `org-tags-exclude-from-inheritance' which gives an
2211 explicit list of tags to be excluded from inheritance., even if the value of
2212 `org-use-tag-inheritance' would select it for inheritance.
2214 If this option is t, a match early-on in a tree can lead to a large
2215 number of matches in the subtree when constructing the agenda or creating
2216 a sparse tree. If you only want to see the first match in a tree during
2217 a search, check out the variable `org-tags-match-list-sublevels'."
2218 :group 'org-tags
2219 :type '(choice
2220 (const :tag "Not" nil)
2221 (const :tag "Always" t)
2222 (repeat :tag "Specific tags" (string :tag "Tag"))
2223 (regexp :tag "Tags matched by regexp")))
2225 (defcustom org-tags-exclude-from-inheritance nil
2226 "List of tags that should never be inherited.
2227 This is a way to exclude a few tags from inheritance. For way to do
2228 the opposite, to actively allow inheritance for selected tags,
2229 see the variable `org-use-tag-inheritance'."
2230 :group 'org-tags
2231 :type '(repeat (string :tag "Tag")))
2233 (defun org-tag-inherit-p (tag)
2234 "Check if TAG is one that should be inherited."
2235 (cond
2236 ((member tag org-tags-exclude-from-inheritance) nil)
2237 ((eq org-use-tag-inheritance t) t)
2238 ((not org-use-tag-inheritance) nil)
2239 ((stringp org-use-tag-inheritance)
2240 (string-match org-use-tag-inheritance tag))
2241 ((listp org-use-tag-inheritance)
2242 (member tag org-use-tag-inheritance))
2243 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2245 (defcustom org-tags-match-list-sublevels t
2246 "Non-nil means list also sublevels of headlines matching a search.
2247 This variable applies to tags/property searches, and also to stuck
2248 projects because this search is based on a tags match as well.
2250 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2251 the sublevels of a headline matching a tag search often also match
2252 the same search. Listing all of them can create very long lists.
2253 Setting this variable to nil causes subtrees of a match to be skipped.
2255 As a special case, if the tag search is restricted to TODO items, the
2256 value of this variable is ignored and sublevels are always checked, to
2257 make sure all corresponding TODO items find their way into the list.
2259 This variable is semi-obsolete and probably should always be true. It
2260 is better to limit inheritance to certain tags using the variables
2261 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2262 :group 'org-tags
2263 :type '(choice
2264 (const :tag "No, don't list them" nil)
2265 (const :tag "Yes, do list them" t)
2266 (const :tag "List them, indented with leading dots" indented)))
2268 (defvar org-tags-history nil
2269 "History of minibuffer reads for tags.")
2270 (defvar org-last-tags-completion-table nil
2271 "The last used completion table for tags.")
2272 (defvar org-after-tags-change-hook nil
2273 "Hook that is run after the tags in a line have changed.")
2275 (defgroup org-properties nil
2276 "Options concerning properties in Org-mode."
2277 :tag "Org Properties"
2278 :group 'org)
2280 (defcustom org-property-format "%-10s %s"
2281 "How property key/value pairs should be formatted by `indent-line'.
2282 When `indent-line' hits a property definition, it will format the line
2283 according to this format, mainly to make sure that the values are
2284 lined-up with respect to each other."
2285 :group 'org-properties
2286 :type 'string)
2288 (defcustom org-use-property-inheritance nil
2289 "Non-nil means, properties apply also for sublevels.
2291 This setting is chiefly used during property searches. Turning it on can
2292 cause significant overhead when doing a search, which is why it is not
2293 on by default.
2295 When nil, only the properties directly given in the current entry count.
2296 When t, every property is inherited. The value may also be a list of
2297 properties that should have inheritance, or a regular expression matching
2298 properties that should be inherited.
2300 However, note that some special properties use inheritance under special
2301 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2302 and the properties ending in \"_ALL\" when they are used as descriptor
2303 for valid values of a property.
2305 Note for programmers:
2306 When querying an entry with `org-entry-get', you can control if inheritance
2307 should be used. By default, `org-entry-get' looks only at the local
2308 properties. You can request inheritance by setting the inherit argument
2309 to t (to force inheritance) or to `selective' (to respect the setting
2310 in this variable)."
2311 :group 'org-properties
2312 :type '(choice
2313 (const :tag "Not" nil)
2314 (const :tag "Always" t)
2315 (repeat :tag "Specific properties" (string :tag "Property"))
2316 (regexp :tag "Properties matched by regexp")))
2318 (defun org-property-inherit-p (property)
2319 "Check if PROPERTY is one that should be inherited."
2320 (cond
2321 ((eq org-use-property-inheritance t) t)
2322 ((not org-use-property-inheritance) nil)
2323 ((stringp org-use-property-inheritance)
2324 (string-match org-use-property-inheritance property))
2325 ((listp org-use-property-inheritance)
2326 (member property org-use-property-inheritance))
2327 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2329 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2330 "The default column format, if no other format has been defined.
2331 This variable can be set on the per-file basis by inserting a line
2333 #+COLUMNS: %25ITEM ....."
2334 :group 'org-properties
2335 :type 'string)
2337 (defcustom org-columns-ellipses ".."
2338 "The ellipses to be used when a field in column view is truncated.
2339 When this is the empty string, as many characters as possible are shown,
2340 but then there will be no visual indication that the field has been truncated.
2341 When this is a string of length N, the last N characters of a truncated
2342 field are replaced by this string. If the column is narrower than the
2343 ellipses string, only part of the ellipses string will be shown."
2344 :group 'org-properties
2345 :type 'string)
2347 (defcustom org-columns-modify-value-for-display-function nil
2348 "Function that modifies values for display in column view.
2349 For example, it can be used to cut out a certain part from a time stamp.
2350 The function must take 2 arguments:
2352 column-title The title of the column (*not* the property name)
2353 value The value that should be modified.
2355 The function should return the value that should be displayed,
2356 or nil if the normal value should be used."
2357 :group 'org-properties
2358 :type 'function)
2360 (defcustom org-effort-property "Effort"
2361 "The property that is being used to keep track of effort estimates.
2362 Effort estimates given in this property need to have the format H:MM."
2363 :group 'org-properties
2364 :group 'org-progress
2365 :type '(string :tag "Property"))
2367 (defconst org-global-properties-fixed
2368 '(("VISIBILITY_ALL" . "folded children content all"))
2369 "List of property/value pairs that can be inherited by any entry.
2371 These are fixed values, for the preset properties. The user variable
2372 that can be used to add to this list is `org-global-properties'.
2374 The entries in this list are cons cells where the car is a property
2375 name and cdr is a string with the value. If the value represents
2376 multiple items like an \"_ALL\" property, separate the items by
2377 spaces.")
2379 (defcustom org-global-properties nil
2380 "List of property/value pairs that can be inherited by any entry.
2382 This list will be combined with the constant `org-global-properties-fixed'.
2384 The entries in this list are cons cells where the car is a property
2385 name and cdr is a string with the value.
2387 You can set buffer-local values for the same purpose in the variable
2388 `org-file-properties' this by adding lines like
2390 #+PROPERTY: NAME VALUE"
2391 :group 'org-properties
2392 :type '(repeat
2393 (cons (string :tag "Property")
2394 (string :tag "Value"))))
2396 (defvar org-file-properties nil
2397 "List of property/value pairs that can be inherited by any entry.
2398 Valid for the current buffer.
2399 This variable is populated from #+PROPERTY lines.")
2400 (make-variable-buffer-local 'org-file-properties)
2402 (defgroup org-agenda nil
2403 "Options concerning agenda views in Org-mode."
2404 :tag "Org Agenda"
2405 :group 'org)
2407 (defvar org-category nil
2408 "Variable used by org files to set a category for agenda display.
2409 Such files should use a file variable to set it, for example
2411 # -*- mode: org; org-category: \"ELisp\"
2413 or contain a special line
2415 #+CATEGORY: ELisp
2417 If the file does not specify a category, then file's base name
2418 is used instead.")
2419 (make-variable-buffer-local 'org-category)
2420 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2422 (defcustom org-agenda-files nil
2423 "The files to be used for agenda display.
2424 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2425 \\[org-remove-file]. You can also use customize to edit the list.
2427 If an entry is a directory, all files in that directory that are matched by
2428 `org-agenda-file-regexp' will be part of the file list.
2430 If the value of the variable is not a list but a single file name, then
2431 the list of agenda files is actually stored and maintained in that file, one
2432 agenda file per line."
2433 :group 'org-agenda
2434 :type '(choice
2435 (repeat :tag "List of files and directories" file)
2436 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2438 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2439 "Regular expression to match files for `org-agenda-files'.
2440 If any element in the list in that variable contains a directory instead
2441 of a normal file, all files in that directory that are matched by this
2442 regular expression will be included."
2443 :group 'org-agenda
2444 :type 'regexp)
2446 (defcustom org-agenda-text-search-extra-files nil
2447 "List of extra files to be searched by text search commands.
2448 These files will be search in addition to the agenda files by the
2449 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2450 Note that these files will only be searched for text search commands,
2451 not for the other agenda views like todo lists, tag searches or the weekly
2452 agenda. This variable is intended to list notes and possibly archive files
2453 that should also be searched by these two commands.
2454 In fact, if the first element in the list is the symbol `agenda-archives',
2455 than all archive files of all agenda files will be added to the search
2456 scope."
2457 :group 'org-agenda
2458 :type '(set :greedy t
2459 (const :tag "Agenda Archives" agenda-archives)
2460 (repeat :inline t (file))))
2462 (if (fboundp 'defvaralias)
2463 (defvaralias 'org-agenda-multi-occur-extra-files
2464 'org-agenda-text-search-extra-files))
2466 (defcustom org-agenda-skip-unavailable-files nil
2467 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2468 A nil value means to remove them, after a query, from the list."
2469 :group 'org-agenda
2470 :type 'boolean)
2472 (defcustom org-calendar-to-agenda-key [?c]
2473 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2474 The command `org-calendar-goto-agenda' will be bound to this key. The
2475 default is the character `c' because then `c' can be used to switch back and
2476 forth between agenda and calendar."
2477 :group 'org-agenda
2478 :type 'sexp)
2480 (defcustom org-calendar-agenda-action-key [?k]
2481 "The key to be installed in `calendar-mode-map' for agenda-action.
2482 The command `org-agenda-action' will be bound to this key. The
2483 default is the character `k' because we use the same key in the agenda."
2484 :group 'org-agenda
2485 :type 'sexp)
2487 (eval-after-load "calendar"
2488 '(progn
2489 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2490 'org-calendar-goto-agenda)
2491 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2492 'org-agenda-action)))
2494 (defgroup org-latex nil
2495 "Options for embedding LaTeX code into Org-mode."
2496 :tag "Org LaTeX"
2497 :group 'org)
2499 (defcustom org-format-latex-options
2500 '(:foreground default :background default :scale 1.0
2501 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2502 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2503 "Options for creating images from LaTeX fragments.
2504 This is a property list with the following properties:
2505 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2506 `default' means use the foreground of the default face.
2507 :background the background color, or \"Transparent\".
2508 `default' means use the background of the default face.
2509 :scale a scaling factor for the size of the images.
2510 :html-foreground, :html-background, :html-scale
2511 the same numbers for HTML export.
2512 :matchers a list indicating which matchers should be used to
2513 find LaTeX fragments. Valid members of this list are:
2514 \"begin\" find environments
2515 \"$1\" find single characters surrounded by $.$
2516 \"$\" find math expressions surrounded by $...$
2517 \"$$\" find math expressions surrounded by $$....$$
2518 \"\\(\" find math expressions surrounded by \\(...\\)
2519 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2520 :group 'org-latex
2521 :type 'plist)
2523 (defcustom org-format-latex-header "\\documentclass{article}
2524 \\usepackage{fullpage} % do not remove
2525 \\usepackage{amssymb}
2526 \\usepackage[usenames]{color}
2527 \\usepackage{amsmath}
2528 \\usepackage{latexsym}
2529 \\usepackage[mathscr]{eucal}
2530 \\pagestyle{empty} % do not remove"
2531 "The document header used for processing LaTeX fragments."
2532 :group 'org-latex
2533 :type 'string)
2536 (defgroup org-font-lock nil
2537 "Font-lock settings for highlighting in Org-mode."
2538 :tag "Org Font Lock"
2539 :group 'org)
2541 (defcustom org-level-color-stars-only nil
2542 "Non-nil means fontify only the stars in each headline.
2543 When nil, the entire headline is fontified.
2544 Changing it requires restart of `font-lock-mode' to become effective
2545 also in regions already fontified."
2546 :group 'org-font-lock
2547 :type 'boolean)
2549 (defcustom org-hide-leading-stars nil
2550 "Non-nil means, hide the first N-1 stars in a headline.
2551 This works by using the face `org-hide' for these stars. This
2552 face is white for a light background, and black for a dark
2553 background. You may have to customize the face `org-hide' to
2554 make this work.
2555 Changing it requires restart of `font-lock-mode' to become effective
2556 also in regions already fontified.
2557 You may also set this on a per-file basis by adding one of the following
2558 lines to the buffer:
2560 #+STARTUP: hidestars
2561 #+STARTUP: showstars"
2562 :group 'org-font-lock
2563 :type 'boolean)
2565 (defcustom org-fontify-done-headline nil
2566 "Non-nil means, change the face of a headline if it is marked DONE.
2567 Normally, only the TODO/DONE keyword indicates the state of a headline.
2568 When this is non-nil, the headline after the keyword is set to the
2569 `org-headline-done' as an additional indication."
2570 :group 'org-font-lock
2571 :type 'boolean)
2573 (defcustom org-fontify-emphasized-text t
2574 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2575 Changing this variable requires a restart of Emacs to take effect."
2576 :group 'org-font-lock
2577 :type 'boolean)
2579 (defcustom org-highlight-latex-fragments-and-specials nil
2580 "Non-nil means, fontify what is treated specially by the exporters."
2581 :group 'org-font-lock
2582 :type 'boolean)
2584 (defcustom org-hide-emphasis-markers nil
2585 "Non-nil mean font-lock should hide the emphasis marker characters."
2586 :group 'org-font-lock
2587 :type 'boolean)
2589 (defvar org-emph-re nil
2590 "Regular expression for matching emphasis.")
2591 (defvar org-verbatim-re nil
2592 "Regular expression for matching verbatim text.")
2593 (defvar org-emphasis-regexp-components) ; defined just below
2594 (defvar org-emphasis-alist) ; defined just below
2595 (defun org-set-emph-re (var val)
2596 "Set variable and compute the emphasis regular expression."
2597 (set var val)
2598 (when (and (boundp 'org-emphasis-alist)
2599 (boundp 'org-emphasis-regexp-components)
2600 org-emphasis-alist org-emphasis-regexp-components)
2601 (let* ((e org-emphasis-regexp-components)
2602 (pre (car e))
2603 (post (nth 1 e))
2604 (border (nth 2 e))
2605 (body (nth 3 e))
2606 (nl (nth 4 e))
2607 (body1 (concat body "*?"))
2608 (markers (mapconcat 'car org-emphasis-alist ""))
2609 (vmarkers (mapconcat
2610 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2611 org-emphasis-alist "")))
2612 ;; make sure special characters appear at the right position in the class
2613 (if (string-match "\\^" markers)
2614 (setq markers (concat (replace-match "" t t markers) "^")))
2615 (if (string-match "-" markers)
2616 (setq markers (concat (replace-match "" t t markers) "-")))
2617 (if (string-match "\\^" vmarkers)
2618 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2619 (if (string-match "-" vmarkers)
2620 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2621 (if (> nl 0)
2622 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2623 (int-to-string nl) "\\}")))
2624 ;; Make the regexp
2625 (setq org-emph-re
2626 (concat "\\([" pre "]\\|^\\)"
2627 "\\("
2628 "\\([" markers "]\\)"
2629 "\\("
2630 "[^" border "]\\|"
2631 "[^" border "]"
2632 body1
2633 "[^" border "]"
2634 "\\)"
2635 "\\3\\)"
2636 "\\([" post "]\\|$\\)"))
2637 (setq org-verbatim-re
2638 (concat "\\([" pre "]\\|^\\)"
2639 "\\("
2640 "\\([" vmarkers "]\\)"
2641 "\\("
2642 "[^" border "]\\|"
2643 "[^" border "]"
2644 body1
2645 "[^" border "]"
2646 "\\)"
2647 "\\3\\)"
2648 "\\([" post "]\\|$\\)")))))
2650 (defcustom org-emphasis-regexp-components
2651 '(" \t('\"{" "- \t.,:!?;'\")}" " \t\r\n,\"'" "." 1)
2652 "Components used to build the regular expression for emphasis.
2653 This is a list with 6 entries. Terminology: In an emphasis string
2654 like \" *strong word* \", we call the initial space PREMATCH, the final
2655 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2656 and \"trong wor\" is the body. The different components in this variable
2657 specify what is allowed/forbidden in each part:
2659 pre Chars allowed as prematch. Beginning of line will be allowed too.
2660 post Chars allowed as postmatch. End of line will be allowed too.
2661 border The chars *forbidden* as border characters.
2662 body-regexp A regexp like \".\" to match a body character. Don't use
2663 non-shy groups here, and don't allow newline here.
2664 newline The maximum number of newlines allowed in an emphasis exp.
2666 Use customize to modify this, or restart Emacs after changing it."
2667 :group 'org-font-lock
2668 :set 'org-set-emph-re
2669 :type '(list
2670 (sexp :tag "Allowed chars in pre ")
2671 (sexp :tag "Allowed chars in post ")
2672 (sexp :tag "Forbidden chars in border ")
2673 (sexp :tag "Regexp for body ")
2674 (integer :tag "number of newlines allowed")
2675 (option (boolean :tag "Please ignore this button"))))
2677 (defcustom org-emphasis-alist
2678 `(("*" bold "<b>" "</b>")
2679 ("/" italic "<i>" "</i>")
2680 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2681 ("=" org-code "<code>" "</code>" verbatim)
2682 ("~" org-verbatim "<code>" "</code>" verbatim)
2683 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2684 "<del>" "</del>")
2686 "Special syntax for emphasized text.
2687 Text starting and ending with a special character will be emphasized, for
2688 example *bold*, _underlined_ and /italic/. This variable sets the marker
2689 characters, the face to be used by font-lock for highlighting in Org-mode
2690 Emacs buffers, and the HTML tags to be used for this.
2691 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2692 Use customize to modify this, or restart Emacs after changing it."
2693 :group 'org-font-lock
2694 :set 'org-set-emph-re
2695 :type '(repeat
2696 (list
2697 (string :tag "Marker character")
2698 (choice
2699 (face :tag "Font-lock-face")
2700 (plist :tag "Face property list"))
2701 (string :tag "HTML start tag")
2702 (string :tag "HTML end tag")
2703 (option (const verbatim)))))
2705 ;;; Miscellaneous options
2707 (defgroup org-completion nil
2708 "Completion in Org-mode."
2709 :tag "Org Completion"
2710 :group 'org)
2712 (defcustom org-completion-use-ido nil
2713 "Non-nil means, use ido completion wherever possible.
2714 Note that `ido-mode' must be active for this variable to be relevant.
2715 If you decide to turn this variable on, you might well want to turn off
2716 `org-outline-path-complete-in-steps'."
2717 :group 'org-completion
2718 :type 'boolean)
2720 (defcustom org-completion-fallback-command 'hippie-expand
2721 "The expansion command called by \\[org-complete] in normal context.
2722 Normal means, no org-mode-specific context."
2723 :group 'org-completion
2724 :type 'function)
2726 ;;; Functions and variables from ther packages
2727 ;; Declared here to avoid compiler warnings
2729 ;; XEmacs only
2730 (defvar outline-mode-menu-heading)
2731 (defvar outline-mode-menu-show)
2732 (defvar outline-mode-menu-hide)
2733 (defvar zmacs-regions) ; XEmacs regions
2735 ;; Emacs only
2736 (defvar mark-active)
2738 ;; Various packages
2739 (declare-function find-library-name "find-func" (library))
2740 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2741 (declare-function calendar-forward-day "cal-move" (arg))
2742 (declare-function calendar-goto-date "cal-move" (date))
2743 (declare-function calendar-goto-today "cal-move" ())
2744 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2745 (defvar calc-embedded-close-formula)
2746 (defvar calc-embedded-open-formula)
2747 (declare-function cdlatex-tab "ext:cdlatex" ())
2748 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2749 (defvar font-lock-unfontify-region-function)
2750 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2751 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2752 (defvar iswitchb-temp-buflist)
2753 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2754 (defvar org-agenda-tags-todo-honor-ignore-options)
2755 (declare-function org-agenda-skip "org-agenda" ())
2756 (declare-function org-format-agenda-item "org-agenda"
2757 (extra txt &optional category tags dotime noprefix remove-re))
2758 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2759 (declare-function org-agenda-change-all-lines "org-agenda"
2760 (newhead hdmarker &optional fixface just-this))
2761 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2762 (declare-function org-agenda-maybe-redo "org-agenda" ())
2763 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2764 (beg end))
2765 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2766 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2767 "org-agenda" (&optional end))
2769 (declare-function parse-time-string "parse-time" (string))
2770 (declare-function remember "remember" (&optional initial))
2771 (declare-function remember-buffer-desc "remember" ())
2772 (declare-function remember-finalize "remember" ())
2773 (defvar remember-save-after-remembering)
2774 (defvar remember-data-file)
2775 (defvar remember-register)
2776 (defvar remember-buffer)
2777 (defvar remember-handler-functions)
2778 (defvar remember-annotation-functions)
2779 (defvar texmathp-why)
2780 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2781 (declare-function table--at-cell-p "table" (position &optional object at-column))
2783 (defvar w3m-current-url)
2784 (defvar w3m-current-title)
2786 (defvar org-latex-regexps)
2788 ;;; Autoload and prepare some org modules
2790 ;; Some table stuff that needs to be defined here, because it is used
2791 ;; by the functions setting up org-mode or checking for table context.
2793 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2794 "Detects an org-type or table-type table.")
2795 (defconst org-table-line-regexp "^[ \t]*|"
2796 "Detects an org-type table line.")
2797 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2798 "Detects an org-type table line.")
2799 (defconst org-table-hline-regexp "^[ \t]*|-"
2800 "Detects an org-type table hline.")
2801 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2802 "Detects a table-type table hline.")
2803 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2804 "Searching from within a table (any type) this finds the first line
2805 outside the table.")
2807 ;; Autoload the functions in org-table.el that are needed by functions here.
2809 (eval-and-compile
2810 (org-autoload "org-table"
2811 '(org-table-align org-table-begin org-table-blank-field
2812 org-table-convert org-table-convert-region org-table-copy-down
2813 org-table-copy-region org-table-create
2814 org-table-create-or-convert-from-region
2815 org-table-create-with-table.el org-table-current-dline
2816 org-table-cut-region org-table-delete-column org-table-edit-field
2817 org-table-edit-formulas org-table-end org-table-eval-formula
2818 org-table-export org-table-field-info
2819 org-table-get-stored-formulas org-table-goto-column
2820 org-table-hline-and-move org-table-import org-table-insert-column
2821 org-table-insert-hline org-table-insert-row org-table-iterate
2822 org-table-justify-field-maybe org-table-kill-row
2823 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2824 org-table-move-column org-table-move-column-left
2825 org-table-move-column-right org-table-move-row
2826 org-table-move-row-down org-table-move-row-up
2827 org-table-next-field org-table-next-row org-table-paste-rectangle
2828 org-table-previous-field org-table-recalculate
2829 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2830 org-table-toggle-coordinate-overlays
2831 org-table-toggle-formula-debugger org-table-wrap-region
2832 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2834 (defun org-at-table-p (&optional table-type)
2835 "Return t if the cursor is inside an org-type table.
2836 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2837 (if org-enable-table-editor
2838 (save-excursion
2839 (beginning-of-line 1)
2840 (looking-at (if table-type org-table-any-line-regexp
2841 org-table-line-regexp)))
2842 nil))
2843 (defsubst org-table-p () (org-at-table-p))
2845 (defun org-at-table.el-p ()
2846 "Return t if and only if we are at a table.el table."
2847 (and (org-at-table-p 'any)
2848 (save-excursion
2849 (goto-char (org-table-begin 'any))
2850 (looking-at org-table1-hline-regexp))))
2851 (defun org-table-recognize-table.el ()
2852 "If there is a table.el table nearby, recognize it and move into it."
2853 (if org-table-tab-recognizes-table.el
2854 (if (org-at-table.el-p)
2855 (progn
2856 (beginning-of-line 1)
2857 (if (looking-at org-table-dataline-regexp)
2859 (if (looking-at org-table1-hline-regexp)
2860 (progn
2861 (beginning-of-line 2)
2862 (if (looking-at org-table-any-border-regexp)
2863 (beginning-of-line -1)))))
2864 (if (re-search-forward "|" (org-table-end t) t)
2865 (progn
2866 (require 'table)
2867 (if (table--at-cell-p (point))
2869 (message "recognizing table.el table...")
2870 (table-recognize-table)
2871 (message "recognizing table.el table...done")))
2872 (error "This should not happen..."))
2874 nil)
2875 nil))
2877 (defun org-at-table-hline-p ()
2878 "Return t if the cursor is inside a hline in a table."
2879 (if org-enable-table-editor
2880 (save-excursion
2881 (beginning-of-line 1)
2882 (looking-at org-table-hline-regexp))
2883 nil))
2885 (defvar org-table-clean-did-remove-column nil)
2887 (defun org-table-map-tables (function)
2888 "Apply FUNCTION to the start of all tables in the buffer."
2889 (save-excursion
2890 (save-restriction
2891 (widen)
2892 (goto-char (point-min))
2893 (while (re-search-forward org-table-any-line-regexp nil t)
2894 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2895 (beginning-of-line 1)
2896 (if (looking-at org-table-line-regexp)
2897 (save-excursion (funcall function)))
2898 (re-search-forward org-table-any-border-regexp nil 1))))
2899 (message "Mapping tables: done"))
2901 ;; Declare and autoload functions from org-exp.el
2903 (declare-function org-default-export-plist "org-exp")
2904 (declare-function org-infile-export-plist "org-exp")
2905 (declare-function org-get-current-options "org-exp")
2906 (eval-and-compile
2907 (org-autoload "org-exp"
2908 '(org-export org-export-as-ascii org-export-visible
2909 org-insert-export-options-template org-export-as-html-and-open
2910 org-export-as-html-batch org-export-as-html-to-buffer
2911 org-replace-region-by-html org-export-region-as-html
2912 org-export-as-html org-export-icalendar-this-file
2913 org-export-icalendar-all-agenda-files
2914 org-table-clean-before-export
2915 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2917 ;; Declare and autoload functions from org-agenda.el
2919 (eval-and-compile
2920 (org-autoload "org-agenda"
2921 '(org-agenda org-agenda-list org-search-view
2922 org-todo-list org-tags-view org-agenda-list-stuck-projects
2923 org-diary org-agenda-to-appt
2924 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2926 ;; Autoload org-remember
2928 (eval-and-compile
2929 (org-autoload "org-remember"
2930 '(org-remember-insinuate org-remember-annotation
2931 org-remember-apply-template org-remember org-remember-handler)))
2933 ;; Autoload org-clock.el
2936 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2937 (beg end))
2938 (declare-function org-clock-update-mode-line "org-clock" ())
2939 (defvar org-clock-start-time)
2940 (defvar org-clock-marker (make-marker)
2941 "Marker recording the last clock-in.")
2943 (eval-and-compile
2944 (org-autoload
2945 "org-clock"
2946 '(org-clock-in org-clock-out org-clock-cancel
2947 org-clock-goto org-clock-sum org-clock-display
2948 org-clock-remove-overlays org-clock-report
2949 org-clocktable-shift org-dblock-write:clocktable
2950 org-get-clocktable)))
2952 (defun org-clock-update-time-maybe ()
2953 "If this is a CLOCK line, update it and return t.
2954 Otherwise, return nil."
2955 (interactive)
2956 (save-excursion
2957 (beginning-of-line 1)
2958 (skip-chars-forward " \t")
2959 (when (looking-at org-clock-string)
2960 (let ((re (concat "[ \t]*" org-clock-string
2961 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2962 "\\([ \t]*=>.*\\)?\\)?"))
2963 ts te h m s neg)
2964 (cond
2965 ((not (looking-at re))
2966 nil)
2967 ((not (match-end 2))
2968 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2969 (> org-clock-marker (point))
2970 (<= org-clock-marker (point-at-eol)))
2971 ;; The clock is running here
2972 (setq org-clock-start-time
2973 (apply 'encode-time
2974 (org-parse-time-string (match-string 1))))
2975 (org-clock-update-mode-line)))
2977 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2978 (end-of-line 1)
2979 (setq ts (match-string 1)
2980 te (match-string 3))
2981 (setq s (- (time-to-seconds
2982 (apply 'encode-time (org-parse-time-string te)))
2983 (time-to-seconds
2984 (apply 'encode-time (org-parse-time-string ts))))
2985 neg (< s 0)
2986 s (abs s)
2987 h (floor (/ s 3600))
2988 s (- s (* 3600 h))
2989 m (floor (/ s 60))
2990 s (- s (* 60 s)))
2991 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2992 t))))))
2994 (defun org-check-running-clock ()
2995 "Check if the current buffer contains the running clock.
2996 If yes, offer to stop it and to save the buffer with the changes."
2997 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2998 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2999 (buffer-name))))
3000 (org-clock-out)
3001 (when (y-or-n-p "Save changed buffer?")
3002 (save-buffer))))
3004 (defun org-clocktable-try-shift (dir n)
3005 "Check if this line starts a clock table, if yes, shift the time block."
3006 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3007 (org-clocktable-shift dir n)))
3009 ;; Autoload org-timer.el
3011 (eval-and-compile
3012 (org-autoload
3013 "org-timer"
3014 '(org-timer-start org-timer org-timer-item
3015 org-timer-change-times-in-region)))
3017 ;; Autoload org-feed.el
3019 (eval-and-compile
3020 (org-autoload
3021 "org-feed"
3022 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3025 ;; Autoload archiving code
3026 ;; The stuff that is needed for cycling and tags has to be defined here.
3028 (defgroup org-archive nil
3029 "Options concerning archiving in Org-mode."
3030 :tag "Org Archive"
3031 :group 'org-structure)
3033 (defcustom org-archive-location "%s_archive::"
3034 "The location where subtrees should be archived.
3036 The value of this variable is a string, consisting of two parts,
3037 separated by a double-colon. The first part is a filename and
3038 the second part is a headline.
3040 When the filename is omitted, archiving happens in the same file.
3041 %s in the filename will be replaced by the current file
3042 name (without the directory part). Archiving to a different file
3043 is useful to keep archived entries from contributing to the
3044 Org-mode Agenda.
3046 The archived entries will be filed as subtrees of the specified
3047 headline. When the headline is omitted, the subtrees are simply
3048 filed away at the end of the file, as top-level entries. Also in
3049 the heading you can use %s to represent the file name, this can be
3050 useful when using the same archive for a number of different files.
3052 Here are a few examples:
3053 \"%s_archive::\"
3054 If the current file is Projects.org, archive in file
3055 Projects.org_archive, as top-level trees. This is the default.
3057 \"::* Archived Tasks\"
3058 Archive in the current file, under the top-level headline
3059 \"* Archived Tasks\".
3061 \"~/org/archive.org::\"
3062 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3064 \"~/org/archive.org::From %s\"
3065 Archive in file ~/org/archive.org (absolute path), und headlines
3066 \"From FILENAME\" where file name is the current file name.
3068 \"basement::** Finished Tasks\"
3069 Archive in file ./basement (relative path), as level 3 trees
3070 below the level 2 heading \"** Finished Tasks\".
3072 You may set this option on a per-file basis by adding to the buffer a
3073 line like
3075 #+ARCHIVE: basement::** Finished Tasks
3077 You may also define it locally for a subtree by setting an ARCHIVE property
3078 in the entry. If such a property is found in an entry, or anywhere up
3079 the hierarchy, it will be used."
3080 :group 'org-archive
3081 :type 'string)
3083 (defcustom org-archive-tag "ARCHIVE"
3084 "The tag that marks a subtree as archived.
3085 An archived subtree does not open during visibility cycling, and does
3086 not contribute to the agenda listings.
3087 After changing this, font-lock must be restarted in the relevant buffers to
3088 get the proper fontification."
3089 :group 'org-archive
3090 :group 'org-keywords
3091 :type 'string)
3093 (defcustom org-agenda-skip-archived-trees t
3094 "Non-nil means, the agenda will skip any items located in archived trees.
3095 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3096 variable is no longer recommended, you should leave it at the value t.
3097 Instead, use the key `v' to cycle the archives-mode in the agenda."
3098 :group 'org-archive
3099 :group 'org-agenda-skip
3100 :type 'boolean)
3102 (defcustom org-columns-skip-arrchived-trees t
3103 "Non-nil means, irgnore archived trees when creating column view."
3104 :group 'org-archive
3105 :group 'org-properties
3106 :type 'boolean)
3108 (defcustom org-cycle-open-archived-trees nil
3109 "Non-nil means, `org-cycle' will open archived trees.
3110 An archived tree is a tree marked with the tag ARCHIVE.
3111 When nil, archived trees will stay folded. You can still open them with
3112 normal outline commands like `show-all', but not with the cycling commands."
3113 :group 'org-archive
3114 :group 'org-cycle
3115 :type 'boolean)
3117 (defcustom org-sparse-tree-open-archived-trees nil
3118 "Non-nil means sparse tree construction shows matches in archived trees.
3119 When nil, matches in these trees are highlighted, but the trees are kept in
3120 collapsed state."
3121 :group 'org-archive
3122 :group 'org-sparse-trees
3123 :type 'boolean)
3125 (defun org-cycle-hide-archived-subtrees (state)
3126 "Re-hide all archived subtrees after a visibility state change."
3127 (when (and (not org-cycle-open-archived-trees)
3128 (not (memq state '(overview folded))))
3129 (save-excursion
3130 (let* ((globalp (memq state '(contents all)))
3131 (beg (if globalp (point-min) (point)))
3132 (end (if globalp (point-max) (org-end-of-subtree t))))
3133 (org-hide-archived-subtrees beg end)
3134 (goto-char beg)
3135 (if (looking-at (concat ".*:" org-archive-tag ":"))
3136 (message "%s" (substitute-command-keys
3137 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3139 (defun org-force-cycle-archived ()
3140 "Cycle subtree even if it is archived."
3141 (interactive)
3142 (setq this-command 'org-cycle)
3143 (let ((org-cycle-open-archived-trees t))
3144 (call-interactively 'org-cycle)))
3146 (defun org-hide-archived-subtrees (beg end)
3147 "Re-hide all archived subtrees after a visibility state change."
3148 (save-excursion
3149 (let* ((re (concat ":" org-archive-tag ":")))
3150 (goto-char beg)
3151 (while (re-search-forward re end t)
3152 (and (org-on-heading-p) (hide-subtree))
3153 (org-end-of-subtree t)))))
3155 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3157 (eval-and-compile
3158 (org-autoload "org-archive"
3159 '(org-add-archive-files org-archive-subtree
3160 org-archive-to-archive-sibling org-toggle-archive-tag)))
3162 ;; Autoload Column View Code
3164 (declare-function org-columns-number-to-string "org-colview")
3165 (declare-function org-columns-get-format-and-top-level "org-colview")
3166 (declare-function org-columns-compute "org-colview")
3168 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3169 '(org-columns-number-to-string org-columns-get-format-and-top-level
3170 org-columns-compute org-agenda-columns org-columns-remove-overlays
3171 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3173 ;; Autoload ID code
3175 (declare-function org-id-store-link "org-id")
3176 (declare-function org-id-locations-load "org-id")
3177 (declare-function org-id-locations-save "org-id")
3178 (defvar org-id-track-globally)
3179 (org-autoload "org-id"
3180 '(org-id-get-create org-id-new org-id-copy org-id-get
3181 org-id-get-with-outline-path-completion
3182 org-id-get-with-outline-drilling
3183 org-id-goto org-id-find org-id-store-link))
3185 ;; Autoload Plotting Code
3187 (org-autoload "org-plot"
3188 '(org-plot/gnuplot))
3190 ;;; Variables for pre-computed regular expressions, all buffer local
3192 (defvar org-drawer-regexp nil
3193 "Matches first line of a hidden block.")
3194 (make-variable-buffer-local 'org-drawer-regexp)
3195 (defvar org-todo-regexp nil
3196 "Matches any of the TODO state keywords.")
3197 (make-variable-buffer-local 'org-todo-regexp)
3198 (defvar org-not-done-regexp nil
3199 "Matches any of the TODO state keywords except the last one.")
3200 (make-variable-buffer-local 'org-not-done-regexp)
3201 (defvar org-not-done-heading-regexp nil
3202 "Matches a TODO headline that is not done.")
3203 (make-variable-buffer-local 'org-not-done-regexp)
3204 (defvar org-todo-line-regexp nil
3205 "Matches a headline and puts TODO state into group 2 if present.")
3206 (make-variable-buffer-local 'org-todo-line-regexp)
3207 (defvar org-complex-heading-regexp nil
3208 "Matches a headline and puts everything into groups:
3209 group 1: the stars
3210 group 2: The todo keyword, maybe
3211 group 3: Priority cookie
3212 group 4: True headline
3213 group 5: Tags")
3214 (make-variable-buffer-local 'org-complex-heading-regexp)
3215 (defvar org-todo-line-tags-regexp nil
3216 "Matches a headline and puts TODO state into group 2 if present.
3217 Also put tags into group 4 if tags are present.")
3218 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3219 (defvar org-nl-done-regexp nil
3220 "Matches newline followed by a headline with the DONE keyword.")
3221 (make-variable-buffer-local 'org-nl-done-regexp)
3222 (defvar org-looking-at-done-regexp nil
3223 "Matches the DONE keyword a point.")
3224 (make-variable-buffer-local 'org-looking-at-done-regexp)
3225 (defvar org-ds-keyword-length 12
3226 "Maximum length of the Deadline and SCHEDULED keywords.")
3227 (make-variable-buffer-local 'org-ds-keyword-length)
3228 (defvar org-deadline-regexp nil
3229 "Matches the DEADLINE keyword.")
3230 (make-variable-buffer-local 'org-deadline-regexp)
3231 (defvar org-deadline-time-regexp nil
3232 "Matches the DEADLINE keyword together with a time stamp.")
3233 (make-variable-buffer-local 'org-deadline-time-regexp)
3234 (defvar org-deadline-line-regexp nil
3235 "Matches the DEADLINE keyword and the rest of the line.")
3236 (make-variable-buffer-local 'org-deadline-line-regexp)
3237 (defvar org-scheduled-regexp nil
3238 "Matches the SCHEDULED keyword.")
3239 (make-variable-buffer-local 'org-scheduled-regexp)
3240 (defvar org-scheduled-time-regexp nil
3241 "Matches the SCHEDULED keyword together with a time stamp.")
3242 (make-variable-buffer-local 'org-scheduled-time-regexp)
3243 (defvar org-closed-time-regexp nil
3244 "Matches the CLOSED keyword together with a time stamp.")
3245 (make-variable-buffer-local 'org-closed-time-regexp)
3247 (defvar org-keyword-time-regexp nil
3248 "Matches any of the 4 keywords, together with the time stamp.")
3249 (make-variable-buffer-local 'org-keyword-time-regexp)
3250 (defvar org-keyword-time-not-clock-regexp nil
3251 "Matches any of the 3 keywords, together with the time stamp.")
3252 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3253 (defvar org-maybe-keyword-time-regexp nil
3254 "Matches a timestamp, possibly preceeded by a keyword.")
3255 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3256 (defvar org-planning-or-clock-line-re nil
3257 "Matches a line with planning or clock info.")
3258 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3260 (defconst org-plain-time-of-day-regexp
3261 (concat
3262 "\\(\\<[012]?[0-9]"
3263 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3264 "\\(--?"
3265 "\\(\\<[012]?[0-9]"
3266 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3267 "\\)?")
3268 "Regular expression to match a plain time or time range.
3269 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3270 groups carry important information:
3271 0 the full match
3272 1 the first time, range or not
3273 8 the second time, if it is a range.")
3275 (defconst org-plain-time-extension-regexp
3276 (concat
3277 "\\(\\<[012]?[0-9]"
3278 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3279 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3280 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3281 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3282 groups carry important information:
3283 0 the full match
3284 7 hours of duration
3285 9 minutes of duration")
3287 (defconst org-stamp-time-of-day-regexp
3288 (concat
3289 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3290 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3291 "\\(--?"
3292 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3293 "Regular expression to match a timestamp time or time range.
3294 After a match, the following groups carry important information:
3295 0 the full match
3296 1 date plus weekday, for backreferencing to make sure both times on same day
3297 2 the first time, range or not
3298 4 the second time, if it is a range.")
3300 (defconst org-startup-options
3301 '(("fold" org-startup-folded t)
3302 ("overview" org-startup-folded t)
3303 ("nofold" org-startup-folded nil)
3304 ("showall" org-startup-folded nil)
3305 ("content" org-startup-folded content)
3306 ("hidestars" org-hide-leading-stars t)
3307 ("showstars" org-hide-leading-stars nil)
3308 ("odd" org-odd-levels-only t)
3309 ("oddeven" org-odd-levels-only nil)
3310 ("align" org-startup-align-all-tables t)
3311 ("noalign" org-startup-align-all-tables nil)
3312 ("customtime" org-display-custom-times t)
3313 ("logdone" org-log-done time)
3314 ("lognotedone" org-log-done note)
3315 ("nologdone" org-log-done nil)
3316 ("lognoteclock-out" org-log-note-clock-out t)
3317 ("nolognoteclock-out" org-log-note-clock-out nil)
3318 ("logrepeat" org-log-repeat state)
3319 ("lognoterepeat" org-log-repeat note)
3320 ("nologrepeat" org-log-repeat nil)
3321 ("fninline" org-footnote-define-inline t)
3322 ("nofninline" org-footnote-define-inline nil)
3323 ("fnlocal" org-footnote-section nil)
3324 ("fnauto" org-footnote-auto-label t)
3325 ("fnprompt" org-footnote-auto-label nil)
3326 ("fnconfirm" org-footnote-auto-label confirm)
3327 ("fnplain" org-footnote-auto-label plain)
3328 ("constcgs" constants-unit-system cgs)
3329 ("constSI" constants-unit-system SI)
3330 ("noptag" org-tag-persistent-alist nil))
3331 "Variable associated with STARTUP options for org-mode.
3332 Each element is a list of three items: The startup options as written
3333 in the #+STARTUP line, the corresponding variable, and the value to
3334 set this variable to if the option is found. An optional forth element PUSH
3335 means to push this value onto the list in the variable.")
3337 (defun org-set-regexps-and-options ()
3338 "Precompute regular expressions for current buffer."
3339 (when (org-mode-p)
3340 (org-set-local 'org-todo-kwd-alist nil)
3341 (org-set-local 'org-todo-key-alist nil)
3342 (org-set-local 'org-todo-key-trigger nil)
3343 (org-set-local 'org-todo-keywords-1 nil)
3344 (org-set-local 'org-done-keywords nil)
3345 (org-set-local 'org-todo-heads nil)
3346 (org-set-local 'org-todo-sets nil)
3347 (org-set-local 'org-todo-log-states nil)
3348 (org-set-local 'org-file-properties nil)
3349 (org-set-local 'org-file-tags nil)
3350 (let ((re (org-make-options-regexp
3351 '("CATEGORY" "TODO" "COLUMNS"
3352 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3353 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3354 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3355 (splitre "[ \t]+")
3356 kwds kws0 kwsa key log value cat arch tags const links hw dws
3357 tail sep kws1 prio props ftags drawers
3358 ext-setup-or-nil setup-contents (start 0))
3359 (save-excursion
3360 (save-restriction
3361 (widen)
3362 (goto-char (point-min))
3363 (while (or (and ext-setup-or-nil
3364 (string-match re ext-setup-or-nil start)
3365 (setq start (match-end 0)))
3366 (and (setq ext-setup-or-nil nil start 0)
3367 (re-search-forward re nil t)))
3368 (setq key (upcase (match-string 1 ext-setup-or-nil))
3369 value (org-match-string-no-properties 2 ext-setup-or-nil))
3370 (cond
3371 ((equal key "CATEGORY")
3372 (if (string-match "[ \t]+$" value)
3373 (setq value (replace-match "" t t value)))
3374 (setq cat value))
3375 ((member key '("SEQ_TODO" "TODO"))
3376 (push (cons 'sequence (org-split-string value splitre)) kwds))
3377 ((equal key "TYP_TODO")
3378 (push (cons 'type (org-split-string value splitre)) kwds))
3379 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3380 ;; general TODO-like setup
3381 (push (cons (intern (downcase (match-string 1 key)))
3382 (org-split-string value splitre)) kwds))
3383 ((equal key "TAGS")
3384 (setq tags (append tags (if tags '("\\n") nil)
3385 (org-split-string value splitre))))
3386 ((equal key "COLUMNS")
3387 (org-set-local 'org-columns-default-format value))
3388 ((equal key "LINK")
3389 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3390 (push (cons (match-string 1 value)
3391 (org-trim (match-string 2 value)))
3392 links)))
3393 ((equal key "PRIORITIES")
3394 (setq prio (org-split-string value " +")))
3395 ((equal key "PROPERTY")
3396 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3397 (push (cons (match-string 1 value) (match-string 2 value))
3398 props)))
3399 ((equal key "FILETAGS")
3400 (when (string-match "\\S-" value)
3401 (setq ftags
3402 (append
3403 ftags
3404 (apply 'append
3405 (mapcar (lambda (x) (org-split-string x ":"))
3406 (org-split-string value)))))))
3407 ((equal key "DRAWERS")
3408 (setq drawers (org-split-string value splitre)))
3409 ((equal key "CONSTANTS")
3410 (setq const (append const (org-split-string value splitre))))
3411 ((equal key "STARTUP")
3412 (let ((opts (org-split-string value splitre))
3413 l var val)
3414 (while (setq l (pop opts))
3415 (when (setq l (assoc l org-startup-options))
3416 (setq var (nth 1 l) val (nth 2 l))
3417 (if (not (nth 3 l))
3418 (set (make-local-variable var) val)
3419 (if (not (listp (symbol-value var)))
3420 (set (make-local-variable var) nil))
3421 (set (make-local-variable var) (symbol-value var))
3422 (add-to-list var val))))))
3423 ((equal key "ARCHIVE")
3424 (string-match " *$" value)
3425 (setq arch (replace-match "" t t value))
3426 (remove-text-properties 0 (length arch)
3427 '(face t fontified t) arch))
3428 ((equal key "SETUPFILE")
3429 (setq setup-contents (org-file-contents
3430 (expand-file-name
3431 (org-remove-double-quotes value))
3432 'noerror))
3433 (if (not ext-setup-or-nil)
3434 (setq ext-setup-or-nil setup-contents start 0)
3435 (setq ext-setup-or-nil
3436 (concat (substring ext-setup-or-nil 0 start)
3437 "\n" setup-contents "\n"
3438 (substring ext-setup-or-nil start)))))
3439 ))))
3440 (when cat
3441 (org-set-local 'org-category (intern cat))
3442 (push (cons "CATEGORY" cat) props))
3443 (when prio
3444 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3445 (setq prio (mapcar 'string-to-char prio))
3446 (org-set-local 'org-highest-priority (nth 0 prio))
3447 (org-set-local 'org-lowest-priority (nth 1 prio))
3448 (org-set-local 'org-default-priority (nth 2 prio)))
3449 (and props (org-set-local 'org-file-properties (nreverse props)))
3450 (and ftags (org-set-local 'org-file-tags
3451 (mapcar 'org-add-prop-inherited ftags)))
3452 (and drawers (org-set-local 'org-drawers drawers))
3453 (and arch (org-set-local 'org-archive-location arch))
3454 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3455 ;; Process the TODO keywords
3456 (unless kwds
3457 ;; Use the global values as if they had been given locally.
3458 (setq kwds (default-value 'org-todo-keywords))
3459 (if (stringp (car kwds))
3460 (setq kwds (list (cons org-todo-interpretation
3461 (default-value 'org-todo-keywords)))))
3462 (setq kwds (reverse kwds)))
3463 (setq kwds (nreverse kwds))
3464 (let (inter kws kw)
3465 (while (setq kws (pop kwds))
3466 (let ((kws (or
3467 (run-hook-with-args-until-success
3468 'org-todo-setup-filter-hook kws)
3469 kws)))
3470 (setq inter (pop kws) sep (member "|" kws)
3471 kws0 (delete "|" (copy-sequence kws))
3472 kwsa nil
3473 kws1 (mapcar
3474 (lambda (x)
3475 ;; 1 2
3476 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3477 (progn
3478 (setq kw (match-string 1 x)
3479 key (and (match-end 2) (match-string 2 x))
3480 log (org-extract-log-state-settings x))
3481 (push (cons kw (and key (string-to-char key))) kwsa)
3482 (and log (push log org-todo-log-states))
3484 (error "Invalid TODO keyword %s" x)))
3485 kws0)
3486 kwsa (if kwsa (append '((:startgroup))
3487 (nreverse kwsa)
3488 '((:endgroup))))
3489 hw (car kws1)
3490 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3491 tail (list inter hw (car dws) (org-last dws))))
3492 (add-to-list 'org-todo-heads hw 'append)
3493 (push kws1 org-todo-sets)
3494 (setq org-done-keywords (append org-done-keywords dws nil))
3495 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3496 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3497 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3498 (setq org-todo-sets (nreverse org-todo-sets)
3499 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3500 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3501 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3502 ;; Process the constants
3503 (when const
3504 (let (e cst)
3505 (while (setq e (pop const))
3506 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3507 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3508 (setq org-table-formula-constants-local cst)))
3510 ;; Process the tags.
3511 (when tags
3512 (let (e tgs)
3513 (while (setq e (pop tags))
3514 (cond
3515 ((equal e "{") (push '(:startgroup) tgs))
3516 ((equal e "}") (push '(:endgroup) tgs))
3517 ((equal e "\\n") (push '(:newline) tgs))
3518 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3519 (push (cons (match-string 1 e)
3520 (string-to-char (match-string 2 e)))
3521 tgs))
3522 (t (push (list e) tgs))))
3523 (org-set-local 'org-tag-alist nil)
3524 (while (setq e (pop tgs))
3525 (or (and (stringp (car e))
3526 (assoc (car e) org-tag-alist))
3527 (push e org-tag-alist)))))
3529 ;; Compute the regular expressions and other local variables
3530 (if (not org-done-keywords)
3531 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3532 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3533 (length org-scheduled-string)
3534 (length org-clock-string)
3535 (length org-closed-string)))
3536 org-drawer-regexp
3537 (concat "^[ \t]*:\\("
3538 (mapconcat 'regexp-quote org-drawers "\\|")
3539 "\\):[ \t]*$")
3540 org-not-done-keywords
3541 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3542 org-todo-regexp
3543 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3544 "\\|") "\\)\\>")
3545 org-not-done-regexp
3546 (concat "\\<\\("
3547 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3548 "\\)\\>")
3549 org-not-done-heading-regexp
3550 (concat "^\\(\\*+\\)[ \t]+\\("
3551 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3552 "\\)\\>")
3553 org-todo-line-regexp
3554 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3555 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3556 "\\)\\>\\)?[ \t]*\\(.*\\)")
3557 org-complex-heading-regexp
3558 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3559 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3560 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3561 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3562 org-nl-done-regexp
3563 (concat "\n\\*+[ \t]+"
3564 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3565 "\\)" "\\>")
3566 org-todo-line-tags-regexp
3567 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3568 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3569 (org-re
3570 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3571 org-looking-at-done-regexp
3572 (concat "^" "\\(?:"
3573 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3574 "\\>")
3575 org-deadline-regexp (concat "\\<" org-deadline-string)
3576 org-deadline-time-regexp
3577 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3578 org-deadline-line-regexp
3579 (concat "\\<\\(" org-deadline-string "\\).*")
3580 org-scheduled-regexp
3581 (concat "\\<" org-scheduled-string)
3582 org-scheduled-time-regexp
3583 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3584 org-closed-time-regexp
3585 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3586 org-keyword-time-regexp
3587 (concat "\\<\\(" org-scheduled-string
3588 "\\|" org-deadline-string
3589 "\\|" org-closed-string
3590 "\\|" org-clock-string "\\)"
3591 " *[[<]\\([^]>]+\\)[]>]")
3592 org-keyword-time-not-clock-regexp
3593 (concat "\\<\\(" org-scheduled-string
3594 "\\|" org-deadline-string
3595 "\\|" org-closed-string
3596 "\\)"
3597 " *[[<]\\([^]>]+\\)[]>]")
3598 org-maybe-keyword-time-regexp
3599 (concat "\\(\\<\\(" org-scheduled-string
3600 "\\|" org-deadline-string
3601 "\\|" org-closed-string
3602 "\\|" org-clock-string "\\)\\)?"
3603 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3604 org-planning-or-clock-line-re
3605 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3606 "\\|" org-deadline-string
3607 "\\|" org-closed-string "\\|" org-clock-string
3608 "\\)\\>\\)")
3610 (org-compute-latex-and-specials-regexp)
3611 (org-set-font-lock-defaults))))
3613 (defun org-file-contents (file &optional noerror)
3614 "Return the contents of FILE, as a string."
3615 (if (or (not file)
3616 (not (file-readable-p file)))
3617 (if noerror
3618 (progn
3619 (message "Cannot read file %s" file)
3620 (ding) (sit-for 2)
3622 (error "Cannot read file %s" file))
3623 (with-temp-buffer
3624 (insert-file-contents file)
3625 (buffer-string))))
3627 (defun org-extract-log-state-settings (x)
3628 "Extract the log state setting from a TODO keyword string.
3629 This will extract info from a string like \"WAIT(w@/!)\"."
3630 (let (kw key log1 log2)
3631 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3632 (setq kw (match-string 1 x)
3633 key (and (match-end 2) (match-string 2 x))
3634 log1 (and (match-end 3) (match-string 3 x))
3635 log2 (and (match-end 4) (match-string 4 x)))
3636 (and (or log1 log2)
3637 (list kw
3638 (and log1 (if (equal log1 "!") 'time 'note))
3639 (and log2 (if (equal log2 "!") 'time 'note)))))))
3641 (defun org-remove-keyword-keys (list)
3642 "Remove a pair of parenthesis at the end of each string in LIST."
3643 (mapcar (lambda (x)
3644 (if (string-match "(.*)$" x)
3645 (substring x 0 (match-beginning 0))
3647 list))
3649 ;; FIXME: this could be done much better, using second characters etc.
3650 (defun org-assign-fast-keys (alist)
3651 "Assign fast keys to a keyword-key alist.
3652 Respect keys that are already there."
3653 (let (new e k c c1 c2 (char ?a))
3654 (while (setq e (pop alist))
3655 (cond
3656 ((equal e '(:startgroup)) (push e new))
3657 ((equal e '(:endgroup)) (push e new))
3658 ((equal e '(:newline)) (push e new))
3660 (setq k (car e) c2 nil)
3661 (if (cdr e)
3662 (setq c (cdr e))
3663 ;; automatically assign a character.
3664 (setq c1 (string-to-char
3665 (downcase (substring
3666 k (if (= (string-to-char k) ?@) 1 0)))))
3667 (if (or (rassoc c1 new) (rassoc c1 alist))
3668 (while (or (rassoc char new) (rassoc char alist))
3669 (setq char (1+ char)))
3670 (setq c2 c1))
3671 (setq c (or c2 char)))
3672 (push (cons k c) new))))
3673 (nreverse new)))
3675 ;;; Some variables used in various places
3677 (defvar org-window-configuration nil
3678 "Used in various places to store a window configuration.")
3679 (defvar org-finish-function nil
3680 "Function to be called when `C-c C-c' is used.
3681 This is for getting out of special buffers like remember.")
3684 ;; FIXME: Occasionally check by commenting these, to make sure
3685 ;; no other functions uses these, forgetting to let-bind them.
3686 (defvar entry)
3687 (defvar state)
3688 (defvar last-state)
3689 (defvar date)
3690 (defvar description)
3692 ;; Defined somewhere in this file, but used before definition.
3693 (defvar org-html-entities)
3694 (defvar org-struct-menu)
3695 (defvar org-org-menu)
3696 (defvar org-tbl-menu)
3697 (defvar org-agenda-keymap)
3699 ;;;; Define the Org-mode
3701 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3702 (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."))
3705 ;; We use a before-change function to check if a table might need
3706 ;; an update.
3707 (defvar org-table-may-need-update t
3708 "Indicates that a table might need an update.
3709 This variable is set by `org-before-change-function'.
3710 `org-table-align' sets it back to nil.")
3711 (defun org-before-change-function (beg end)
3712 "Every change indicates that a table might need an update."
3713 (setq org-table-may-need-update t))
3714 (defvar org-mode-map)
3715 (defvar org-mode-hook nil
3716 "Mode hook for Org-mode, run after the mode was turned on.")
3717 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3718 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3719 (defvar org-table-buffer-is-an nil)
3720 (defconst org-outline-regexp "\\*+ ")
3722 ;;;###autoload
3723 (define-derived-mode org-mode outline-mode "Org"
3724 "Outline-based notes management and organizer, alias
3725 \"Carsten's outline-mode for keeping track of everything.\"
3727 Org-mode develops organizational tasks around a NOTES file which
3728 contains information about projects as plain text. Org-mode is
3729 implemented on top of outline-mode, which is ideal to keep the content
3730 of large files well structured. It supports ToDo items, deadlines and
3731 time stamps, which magically appear in the diary listing of the Emacs
3732 calendar. Tables are easily created with a built-in table editor.
3733 Plain text URL-like links connect to websites, emails (VM), Usenet
3734 messages (Gnus), BBDB entries, and any files related to the project.
3735 For printing and sharing of notes, an Org-mode file (or a part of it)
3736 can be exported as a structured ASCII or HTML file.
3738 The following commands are available:
3740 \\{org-mode-map}"
3742 ;; Get rid of Outline menus, they are not needed
3743 ;; Need to do this here because define-derived-mode sets up
3744 ;; the keymap so late. Still, it is a waste to call this each time
3745 ;; we switch another buffer into org-mode.
3746 (if (featurep 'xemacs)
3747 (when (boundp 'outline-mode-menu-heading)
3748 ;; Assume this is Greg's port, it used easymenu
3749 (easy-menu-remove outline-mode-menu-heading)
3750 (easy-menu-remove outline-mode-menu-show)
3751 (easy-menu-remove outline-mode-menu-hide))
3752 (define-key org-mode-map [menu-bar headings] 'undefined)
3753 (define-key org-mode-map [menu-bar hide] 'undefined)
3754 (define-key org-mode-map [menu-bar show] 'undefined))
3756 (org-load-modules-maybe)
3757 (easy-menu-add org-org-menu)
3758 (easy-menu-add org-tbl-menu)
3759 (org-install-agenda-files-menu)
3760 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3761 (org-add-to-invisibility-spec '(org-cwidth))
3762 (when (featurep 'xemacs)
3763 (org-set-local 'line-move-ignore-invisible t))
3764 (org-set-local 'outline-regexp org-outline-regexp)
3765 (org-set-local 'outline-level 'org-outline-level)
3766 (when (and org-ellipsis
3767 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3768 (fboundp 'make-glyph-code))
3769 (unless org-display-table
3770 (setq org-display-table (make-display-table)))
3771 (set-display-table-slot
3772 org-display-table 4
3773 (vconcat (mapcar
3774 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3775 org-ellipsis)))
3776 (if (stringp org-ellipsis) org-ellipsis "..."))))
3777 (setq buffer-display-table org-display-table))
3778 (org-set-regexps-and-options)
3779 (when (and org-tag-faces (not org-tags-special-faces-re))
3780 ;; tag faces set outside customize.... force initialization.
3781 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3782 ;; Calc embedded
3783 (org-set-local 'calc-embedded-open-mode "# ")
3784 (modify-syntax-entry ?# "<")
3785 (modify-syntax-entry ?@ "w")
3786 (if org-startup-truncated (setq truncate-lines t))
3787 (org-set-local 'font-lock-unfontify-region-function
3788 'org-unfontify-region)
3789 ;; Activate before-change-function
3790 (org-set-local 'org-table-may-need-update t)
3791 (org-add-hook 'before-change-functions 'org-before-change-function nil
3792 'local)
3793 ;; Check for running clock before killing a buffer
3794 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3795 ;; Paragraphs and auto-filling
3796 (org-set-autofill-regexps)
3797 (setq indent-line-function 'org-indent-line-function)
3798 (org-update-radio-target-regexp)
3799 ;; Make sure dependence stuff works reliably, even for users who set it
3800 ;; too late :-(
3801 (if org-enforce-todo-dependencies
3802 (add-hook 'org-blocker-hook
3803 'org-block-todo-from-children-or-siblings-or-parent)
3804 (remove-hook 'org-blocker-hook
3805 'org-block-todo-from-children-or-siblings-or-parent))
3806 (if org-enforce-todo-checkbox-dependencies
3807 (add-hook 'org-blocker-hook
3808 'org-block-todo-from-checkboxes)
3809 (remove-hook 'org-blocker-hook
3810 'org-block-todo-from-checkboxes))
3812 ;; Comment characters
3813 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3814 (org-set-local 'comment-padding " ")
3816 ;; Align options lines
3817 (org-set-local
3818 'align-mode-rules-list
3819 '((org-in-buffer-settings
3820 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3821 (modes . '(org-mode)))))
3823 ;; Imenu
3824 (org-set-local 'imenu-create-index-function
3825 'org-imenu-get-tree)
3827 ;; Make isearch reveal context
3828 (if (or (featurep 'xemacs)
3829 (not (boundp 'outline-isearch-open-invisible-function)))
3830 ;; Emacs 21 and XEmacs make use of the hook
3831 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3832 ;; Emacs 22 deals with this through a special variable
3833 (org-set-local 'outline-isearch-open-invisible-function
3834 (lambda (&rest ignore) (org-show-context 'isearch))))
3836 ;; If empty file that did not turn on org-mode automatically, make it to.
3837 (if (and org-insert-mode-line-in-empty-file
3838 (interactive-p)
3839 (= (point-min) (point-max)))
3840 (insert "# -*- mode: org -*-\n\n"))
3842 (unless org-inhibit-startup
3843 (when org-startup-align-all-tables
3844 (let ((bmp (buffer-modified-p)))
3845 (org-table-map-tables 'org-table-align)
3846 (set-buffer-modified-p bmp)))
3847 (org-set-startup-visibility)))
3849 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3851 (defun org-current-time ()
3852 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3853 (if (> (car org-time-stamp-rounding-minutes) 1)
3854 (let ((r (car org-time-stamp-rounding-minutes))
3855 (time (decode-time)))
3856 (apply 'encode-time
3857 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3858 (nthcdr 2 time))))
3859 (current-time)))
3861 ;;;; Font-Lock stuff, including the activators
3863 (defvar org-mouse-map (make-sparse-keymap))
3864 (org-defkey org-mouse-map
3865 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3866 (org-defkey org-mouse-map
3867 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3868 (when org-mouse-1-follows-link
3869 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3870 (when org-tab-follows-link
3871 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3872 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3874 (require 'font-lock)
3876 (defconst org-non-link-chars "]\t\n\r<>")
3877 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3878 "shell" "elisp"))
3879 (defvar org-link-types-re nil
3880 "Matches a link that has a url-like prefix like \"http:\"")
3881 (defvar org-link-re-with-space nil
3882 "Matches a link with spaces, optional angular brackets around it.")
3883 (defvar org-link-re-with-space2 nil
3884 "Matches a link with spaces, optional angular brackets around it.")
3885 (defvar org-link-re-with-space3 nil
3886 "Matches a link with spaces, only for internal part in bracket links.")
3887 (defvar org-angle-link-re nil
3888 "Matches link with angular brackets, spaces are allowed.")
3889 (defvar org-plain-link-re nil
3890 "Matches plain link, without spaces.")
3891 (defvar org-bracket-link-regexp nil
3892 "Matches a link in double brackets.")
3893 (defvar org-bracket-link-analytic-regexp nil
3894 "Regular expression used to analyze links.
3895 Here is what the match groups contain after a match:
3896 1: http:
3897 2: http
3898 3: path
3899 4: [desc]
3900 5: desc")
3901 (defvar org-bracket-link-analytic-regexp++ nil
3902 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3903 (defvar org-any-link-re nil
3904 "Regular expression matching any link.")
3906 (defun org-make-link-regexps ()
3907 "Update the link regular expressions.
3908 This should be called after the variable `org-link-types' has changed."
3909 (setq org-link-types-re
3910 (concat
3911 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3912 org-link-re-with-space
3913 (concat
3914 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3915 "\\([^" org-non-link-chars " ]"
3916 "[^" org-non-link-chars "]*"
3917 "[^" org-non-link-chars " ]\\)>?")
3918 org-link-re-with-space2
3919 (concat
3920 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3921 "\\([^" org-non-link-chars " ]"
3922 "[^\t\n\r]*"
3923 "[^" org-non-link-chars " ]\\)>?")
3924 org-link-re-with-space3
3925 (concat
3926 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3927 "\\([^" org-non-link-chars " ]"
3928 "[^\t\n\r]*\\)")
3929 org-angle-link-re
3930 (concat
3931 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3932 "\\([^" org-non-link-chars " ]"
3933 "[^" org-non-link-chars "]*"
3934 "\\)>")
3935 org-plain-link-re
3936 (concat
3937 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3938 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3939 org-bracket-link-regexp
3940 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3941 org-bracket-link-analytic-regexp
3942 (concat
3943 "\\[\\["
3944 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3945 "\\([^]]+\\)"
3946 "\\]"
3947 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3948 "\\]")
3949 org-bracket-link-analytic-regexp++
3950 (concat
3951 "\\[\\["
3952 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3953 "\\([^]]+\\)"
3954 "\\]"
3955 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3956 "\\]")
3957 org-any-link-re
3958 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3959 org-angle-link-re "\\)\\|\\("
3960 org-plain-link-re "\\)")))
3962 (org-make-link-regexps)
3964 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3965 "Regular expression for fast time stamp matching.")
3966 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3967 "Regular expression for fast time stamp matching.")
3968 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3969 "Regular expression matching time strings for analysis.
3970 This one does not require the space after the date, so it can be used
3971 on a string that terminates immediately after the date.")
3972 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3973 "Regular expression matching time strings for analysis.")
3974 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3975 "Regular expression matching time stamps, with groups.")
3976 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3977 "Regular expression matching time stamps (also [..]), with groups.")
3978 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3979 "Regular expression matching a time stamp range.")
3980 (defconst org-tr-regexp-both
3981 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3982 "Regular expression matching a time stamp range.")
3983 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3984 org-ts-regexp "\\)?")
3985 "Regular expression matching a time stamp or time stamp range.")
3986 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3987 org-ts-regexp-both "\\)?")
3988 "Regular expression matching a time stamp or time stamp range.
3989 The time stamps may be either active or inactive.")
3991 (defvar org-emph-face nil)
3993 (defun org-do-emphasis-faces (limit)
3994 "Run through the buffer and add overlays to links."
3995 (let (rtn)
3996 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3997 (if (not (= (char-after (match-beginning 3))
3998 (char-after (match-beginning 4))))
3999 (progn
4000 (setq rtn t)
4001 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4002 'face
4003 (nth 1 (assoc (match-string 3)
4004 org-emphasis-alist)))
4005 (add-text-properties (match-beginning 2) (match-end 2)
4006 '(font-lock-multiline t))
4007 (when org-hide-emphasis-markers
4008 (add-text-properties (match-end 4) (match-beginning 5)
4009 '(invisible org-link))
4010 (add-text-properties (match-beginning 3) (match-end 3)
4011 '(invisible org-link)))))
4012 (backward-char 1))
4013 rtn))
4015 (defun org-emphasize (&optional char)
4016 "Insert or change an emphasis, i.e. a font like bold or italic.
4017 If there is an active region, change that region to a new emphasis.
4018 If there is no region, just insert the marker characters and position
4019 the cursor between them.
4020 CHAR should be either the marker character, or the first character of the
4021 HTML tag associated with that emphasis. If CHAR is a space, the means
4022 to remove the emphasis of the selected region.
4023 If char is not given (for example in an interactive call) it
4024 will be prompted for."
4025 (interactive)
4026 (let ((eal org-emphasis-alist) e det
4027 (erc org-emphasis-regexp-components)
4028 (prompt "")
4029 (string "") beg end move tag c s)
4030 (if (org-region-active-p)
4031 (setq beg (region-beginning) end (region-end)
4032 string (buffer-substring beg end))
4033 (setq move t))
4035 (while (setq e (pop eal))
4036 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4037 c (aref tag 0))
4038 (push (cons c (string-to-char (car e))) det)
4039 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4040 (substring tag 1)))))
4041 (setq det (nreverse det))
4042 (unless char
4043 (message "%s" (concat "Emphasis marker or tag:" prompt))
4044 (setq char (read-char-exclusive)))
4045 (setq char (or (cdr (assoc char det)) char))
4046 (if (equal char ?\ )
4047 (setq s "" move nil)
4048 (unless (assoc (char-to-string char) org-emphasis-alist)
4049 (error "No such emphasis marker: \"%c\"" char))
4050 (setq s (char-to-string char)))
4051 (while (and (> (length string) 1)
4052 (equal (substring string 0 1) (substring string -1))
4053 (assoc (substring string 0 1) org-emphasis-alist))
4054 (setq string (substring string 1 -1)))
4055 (setq string (concat s string s))
4056 (if beg (delete-region beg end))
4057 (unless (or (bolp)
4058 (string-match (concat "[" (nth 0 erc) "\n]")
4059 (char-to-string (char-before (point)))))
4060 (insert " "))
4061 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4062 (char-to-string (char-after (point))))
4063 (insert " ") (backward-char 1))
4064 (insert string)
4065 (and move (backward-char 1))))
4067 (defconst org-nonsticky-props
4068 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4071 (defun org-activate-plain-links (limit)
4072 "Run through the buffer and add overlays to links."
4073 (catch 'exit
4074 (let (f)
4075 (while (re-search-forward org-plain-link-re limit t)
4076 (setq f (get-text-property (match-beginning 0) 'face))
4077 (if (or (eq f 'org-tag)
4078 (and (listp f) (memq 'org-tag f)))
4080 (add-text-properties (match-beginning 0) (match-end 0)
4081 (list 'mouse-face 'highlight
4082 'rear-nonsticky org-nonsticky-props
4083 'keymap org-mouse-map
4085 (throw 'exit t))))))
4087 (defun org-activate-code (limit)
4088 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4089 (progn
4090 (remove-text-properties (match-beginning 0) (match-end 0)
4091 '(display t invisible t intangible t))
4092 t)))
4094 (defun org-activate-angle-links (limit)
4095 "Run through the buffer and add overlays to links."
4096 (if (re-search-forward org-angle-link-re limit t)
4097 (progn
4098 (add-text-properties (match-beginning 0) (match-end 0)
4099 (list 'mouse-face 'highlight
4100 'rear-nonsticky org-nonsticky-props
4101 'keymap org-mouse-map
4103 t)))
4105 (defun org-activate-footnote-links (limit)
4106 "Run through the buffer and add overlays to links."
4107 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4108 limit t)
4109 (progn
4110 (add-text-properties (match-beginning 2) (match-end 2)
4111 (list 'mouse-face 'highlight
4112 'rear-nonsticky org-nonsticky-props
4113 'keymap org-mouse-map
4114 'help-echo
4115 (if (= (point-at-bol) (match-beginning 2))
4116 "Footnote definition"
4117 "Footnote reference")
4119 t)))
4121 (defun org-activate-bracket-links (limit)
4122 "Run through the buffer and add overlays to bracketed links."
4123 (if (re-search-forward org-bracket-link-regexp limit t)
4124 (let* ((help (concat "LINK: "
4125 (org-match-string-no-properties 1)))
4126 ;; FIXME: above we should remove the escapes.
4127 ;; but that requires another match, protecting match data,
4128 ;; a lot of overhead for font-lock.
4129 (ip (org-maybe-intangible
4130 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4131 'keymap org-mouse-map 'mouse-face 'highlight
4132 'font-lock-multiline t 'help-echo help)))
4133 (vp (list 'rear-nonsticky org-nonsticky-props
4134 'keymap org-mouse-map 'mouse-face 'highlight
4135 'font-lock-multiline t 'help-echo help)))
4136 ;; We need to remove the invisible property here. Table narrowing
4137 ;; may have made some of this invisible.
4138 (remove-text-properties (match-beginning 0) (match-end 0)
4139 '(invisible nil))
4140 (if (match-end 3)
4141 (progn
4142 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4143 (add-text-properties (match-beginning 3) (match-end 3) vp)
4144 (add-text-properties (match-end 3) (match-end 0) ip))
4145 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4146 (add-text-properties (match-beginning 1) (match-end 1) vp)
4147 (add-text-properties (match-end 1) (match-end 0) ip))
4148 t)))
4150 (defun org-activate-dates (limit)
4151 "Run through the buffer and add overlays to dates."
4152 (if (re-search-forward org-tsr-regexp-both limit t)
4153 (progn
4154 (add-text-properties (match-beginning 0) (match-end 0)
4155 (list 'mouse-face 'highlight
4156 'rear-nonsticky org-nonsticky-props
4157 'keymap org-mouse-map))
4158 (when org-display-custom-times
4159 (if (match-end 3)
4160 (org-display-custom-time (match-beginning 3) (match-end 3)))
4161 (org-display-custom-time (match-beginning 1) (match-end 1)))
4162 t)))
4164 (defvar org-target-link-regexp nil
4165 "Regular expression matching radio targets in plain text.")
4166 (make-variable-buffer-local 'org-target-link-regexp)
4167 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4168 "Regular expression matching a link target.")
4169 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4170 "Regular expression matching a radio target.")
4171 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4172 "Regular expression matching any target.")
4174 (defun org-activate-target-links (limit)
4175 "Run through the buffer and add overlays to target matches."
4176 (when org-target-link-regexp
4177 (let ((case-fold-search t))
4178 (if (re-search-forward org-target-link-regexp limit t)
4179 (progn
4180 (add-text-properties (match-beginning 0) (match-end 0)
4181 (list 'mouse-face 'highlight
4182 'rear-nonsticky org-nonsticky-props
4183 'keymap org-mouse-map
4184 'help-echo "Radio target link"
4185 'org-linked-text t))
4186 t)))))
4188 (defun org-update-radio-target-regexp ()
4189 "Find all radio targets in this file and update the regular expression."
4190 (interactive)
4191 (when (memq 'radio org-activate-links)
4192 (setq org-target-link-regexp
4193 (org-make-target-link-regexp (org-all-targets 'radio)))
4194 (org-restart-font-lock)))
4196 (defun org-hide-wide-columns (limit)
4197 (let (s e)
4198 (setq s (text-property-any (point) (or limit (point-max))
4199 'org-cwidth t))
4200 (when s
4201 (setq e (next-single-property-change s 'org-cwidth))
4202 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4203 (goto-char e)
4204 t)))
4206 (defvar org-latex-and-specials-regexp nil
4207 "Regular expression for highlighting export special stuff.")
4208 (defvar org-match-substring-regexp)
4209 (defvar org-match-substring-with-braces-regexp)
4210 (defvar org-export-html-special-string-regexps)
4212 (defun org-compute-latex-and-specials-regexp ()
4213 "Compute regular expression for stuff treated specially by exporters."
4214 (if (not org-highlight-latex-fragments-and-specials)
4215 (org-set-local 'org-latex-and-specials-regexp nil)
4216 (require 'org-exp)
4217 (let*
4218 ((matchers (plist-get org-format-latex-options :matchers))
4219 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4220 org-latex-regexps)))
4221 (options (org-combine-plists (org-default-export-plist)
4222 (org-infile-export-plist)))
4223 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4224 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4225 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4226 (org-export-html-expand (plist-get options :expand-quoted-html))
4227 (org-export-with-special-strings (plist-get options :special-strings))
4228 (re-sub
4229 (cond
4230 ((equal org-export-with-sub-superscripts '{})
4231 (list org-match-substring-with-braces-regexp))
4232 (org-export-with-sub-superscripts
4233 (list org-match-substring-regexp))
4234 (t nil)))
4235 (re-latex
4236 (if org-export-with-LaTeX-fragments
4237 (mapcar (lambda (x) (nth 1 x)) latexs)))
4238 (re-macros
4239 (if org-export-with-TeX-macros
4240 (list (concat "\\\\"
4241 (regexp-opt
4242 (append (mapcar 'car org-html-entities)
4243 (if (boundp 'org-latex-entities)
4244 org-latex-entities nil))
4245 'words))) ; FIXME
4247 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4248 (re-special (if org-export-with-special-strings
4249 (mapcar (lambda (x) (car x))
4250 org-export-html-special-string-regexps)))
4251 (re-rest
4252 (delq nil
4253 (list
4254 (if org-export-html-expand "@<[^>\n]+>")
4255 ))))
4256 (org-set-local
4257 'org-latex-and-specials-regexp
4258 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4259 re-rest) "\\|")))))
4261 (defun org-do-latex-and-special-faces (limit)
4262 "Run through the buffer and add overlays to links."
4263 (when org-latex-and-specials-regexp
4264 (let (rtn d)
4265 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4266 limit t))
4267 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4268 'face))
4269 '(org-code org-verbatim underline)))
4270 (progn
4271 (setq rtn t
4272 d (cond ((member (char-after (1+ (match-beginning 0)))
4273 '(?_ ?^)) 1)
4274 (t 0)))
4275 (font-lock-prepend-text-property
4276 (+ d (match-beginning 0)) (match-end 0)
4277 'face 'org-latex-and-export-specials)
4278 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4279 '(font-lock-multiline t)))))
4280 rtn)))
4282 (defun org-restart-font-lock ()
4283 "Restart font-lock-mode, to force refontification."
4284 (when (and (boundp 'font-lock-mode) font-lock-mode)
4285 (font-lock-mode -1)
4286 (font-lock-mode 1)))
4288 (defun org-all-targets (&optional radio)
4289 "Return a list of all targets in this file.
4290 With optional argument RADIO, only find radio targets."
4291 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4292 rtn)
4293 (save-excursion
4294 (goto-char (point-min))
4295 (while (re-search-forward re nil t)
4296 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4297 rtn)))
4299 (defun org-make-target-link-regexp (targets)
4300 "Make regular expression matching all strings in TARGETS.
4301 The regular expression finds the targets also if there is a line break
4302 between words."
4303 (and targets
4304 (concat
4305 "\\<\\("
4306 (mapconcat
4307 (lambda (x)
4308 (while (string-match " +" x)
4309 (setq x (replace-match "\\s-+" t t x)))
4311 targets
4312 "\\|")
4313 "\\)\\>")))
4315 (defun org-activate-tags (limit)
4316 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4317 (progn
4318 (add-text-properties (match-beginning 1) (match-end 1)
4319 (list 'mouse-face 'highlight
4320 'rear-nonsticky org-nonsticky-props
4321 'keymap org-mouse-map))
4322 t)))
4324 (defun org-outline-level ()
4325 (save-excursion
4326 (looking-at outline-regexp)
4327 (if (match-beginning 1)
4328 (+ (org-get-string-indentation (match-string 1)) 1000)
4329 (1- (- (match-end 0) (match-beginning 0))))))
4331 (defvar org-font-lock-keywords nil)
4333 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4334 "Regular expression matching a property line.")
4336 (defvar org-font-lock-hook nil
4337 "Functions to be called for special font lock stuff.")
4339 (defun org-font-lock-hook (limit)
4340 (run-hook-with-args 'org-font-lock-hook limit))
4342 (defun org-set-font-lock-defaults ()
4343 (let* ((em org-fontify-emphasized-text)
4344 (lk org-activate-links)
4345 (org-font-lock-extra-keywords
4346 (list
4347 ;; Call the hook
4348 '(org-font-lock-hook)
4349 ;; Headlines
4350 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4351 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4352 ;; Table lines
4353 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4354 (1 'org-table t))
4355 ;; Table internals
4356 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4357 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4358 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4359 ;; Drawers
4360 (list org-drawer-regexp '(0 'org-special-keyword t))
4361 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4362 ;; Properties
4363 (list org-property-re
4364 '(1 'org-special-keyword t)
4365 '(3 'org-property-value t))
4366 (if org-format-transports-properties-p
4367 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4368 ;; Links
4369 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4370 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4371 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4372 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4373 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4374 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4375 (if (memq 'footnote lk) '(org-activate-footnote-links
4376 (2 'org-footnote t)))
4377 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4378 '(org-hide-wide-columns (0 nil append))
4379 ;; TODO lines
4380 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4381 '(1 (org-get-todo-face 1) t))
4382 ;; DONE
4383 (if org-fontify-done-headline
4384 (list (concat "^[*]+ +\\<\\("
4385 (mapconcat 'regexp-quote org-done-keywords "\\|")
4386 "\\)\\(.*\\)")
4387 '(2 'org-headline-done t))
4388 nil)
4389 ;; Priorities
4390 '(org-font-lock-add-priority-faces)
4391 ;; Tags
4392 '(org-font-lock-add-tag-faces)
4393 ;; Special keywords
4394 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4395 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4396 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4397 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4398 ;; Emphasis
4399 (if em
4400 (if (featurep 'xemacs)
4401 '(org-do-emphasis-faces (0 nil append))
4402 '(org-do-emphasis-faces)))
4403 ;; Checkboxes
4404 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4405 2 'org-checkbox prepend)
4406 (if org-provide-checkbox-statistics
4407 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4408 (0 (org-get-checkbox-statistics-face) t)))
4409 ;; Description list items
4410 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4411 2 'bold prepend)
4412 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4413 '(1 'org-archived prepend))
4414 ;; Specials
4415 '(org-do-latex-and-special-faces)
4416 ;; Code
4417 '(org-activate-code (1 'org-code t))
4418 ;; COMMENT
4419 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4420 "\\|" org-quote-string "\\)\\>")
4421 '(1 'org-special-keyword t))
4422 '("^#.*" (0 'font-lock-comment-face t))
4424 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4425 ;; Now set the full font-lock-keywords
4426 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4427 (org-set-local 'font-lock-defaults
4428 '(org-font-lock-keywords t nil nil backward-paragraph))
4429 (kill-local-variable 'font-lock-keywords) nil))
4431 (defvar org-m nil)
4432 (defvar org-l nil)
4433 (defvar org-f nil)
4434 (defun org-get-level-face (n)
4435 "Get the right face for match N in font-lock matching of headlines."
4436 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4437 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4438 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4439 (cond
4440 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4441 ((eq n 2) org-f)
4442 (t (if org-level-color-stars-only nil org-f))))
4444 (defun org-get-todo-face (kwd)
4445 "Get the right face for a TODO keyword KWD.
4446 If KWD is a number, get the corresponding match group."
4447 (if (numberp kwd) (setq kwd (match-string kwd)))
4448 (or (cdr (assoc kwd org-todo-keyword-faces))
4449 (and (member kwd org-done-keywords) 'org-done)
4450 'org-todo))
4452 (defun org-font-lock-add-tag-faces (limit)
4453 "Add the special tag faces."
4454 (when (and org-tag-faces org-tags-special-faces-re)
4455 (while (re-search-forward org-tags-special-faces-re limit t)
4456 (add-text-properties (match-beginning 1) (match-end 1)
4457 (list 'face (org-get-tag-face 1)
4458 'font-lock-fontified t))
4459 (backward-char 1))))
4461 (defun org-font-lock-add-priority-faces (limit)
4462 "Add the special priority faces."
4463 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4464 (add-text-properties
4465 (match-beginning 0) (match-end 0)
4466 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4467 org-priority-faces))
4468 'org-special-keyword)
4469 'font-lock-fontified t))))
4471 (defun org-get-tag-face (kwd)
4472 "Get the right face for a TODO keyword KWD.
4473 If KWD is a number, get the corresponding match group."
4474 (if (numberp kwd) (setq kwd (match-string kwd)))
4475 (or (cdr (assoc kwd org-tag-faces))
4476 'org-tag))
4478 (defun org-unfontify-region (beg end &optional maybe_loudly)
4479 "Remove fontification and activation overlays from links."
4480 (font-lock-default-unfontify-region beg end)
4481 (let* ((buffer-undo-list t)
4482 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4483 (inhibit-modification-hooks t)
4484 deactivate-mark buffer-file-name buffer-file-truename)
4485 (remove-text-properties beg end
4486 '(mouse-face t keymap t org-linked-text t
4487 invisible t intangible t))))
4489 ;;;; Visibility cycling, including org-goto and indirect buffer
4491 ;;; Cycling
4493 (defvar org-cycle-global-status nil)
4494 (make-variable-buffer-local 'org-cycle-global-status)
4495 (defvar org-cycle-subtree-status nil)
4496 (make-variable-buffer-local 'org-cycle-subtree-status)
4498 ;;;###autoload
4500 (defvar org-inlinetask-min-level)
4501 (defun org-cycle (&optional arg)
4502 "Visibility cycling for Org-mode.
4504 - When this function is called with a prefix argument, rotate the entire
4505 buffer through 3 states (global cycling)
4506 1. OVERVIEW: Show only top-level headlines.
4507 2. CONTENTS: Show all headlines of all levels, but no body text.
4508 3. SHOW ALL: Show everything.
4509 When called with two C-u C-u prefixes, switch to the startup visibility,
4510 determined by the variable `org-startup-folded', and by any VISIBILITY
4511 properties in the buffer.
4512 When called with three C-u C-u C-u prefixed, show the entire buffer,
4513 including drawers.
4515 - When point is at the beginning of a headline, rotate the subtree started
4516 by this line through 3 different states (local cycling)
4517 1. FOLDED: Only the main headline is shown.
4518 2. CHILDREN: The main headline and the direct children are shown.
4519 From this state, you can move to one of the children
4520 and zoom in further.
4521 3. SUBTREE: Show the entire subtree, including body text.
4523 - When there is a numeric prefix, go up to a heading with level ARG, do
4524 a `show-subtree' and return to the previous cursor position. If ARG
4525 is negative, go up that many levels.
4527 - When point is not at the beginning of a headline, execute the global
4528 binding for TAB, which is re-indenting the line. See the option
4529 `org-cycle-emulate-tab' for details.
4531 - Special case: if point is at the beginning of the buffer and there is
4532 no headline in line 1, this function will act as if called with prefix arg.
4533 But only if also the variable `org-cycle-global-at-bob' is t."
4534 (interactive "P")
4535 (org-load-modules-maybe)
4536 (let* ((limit-level
4537 (or org-cycle-max-level
4538 (and (boundp 'org-inlinetask-min-level)
4539 org-inlinetask-min-level
4540 (1- org-inlinetask-min-level))))
4541 (nstars (and limit-level
4542 (if org-odd-levels-only
4543 (and limit-level (1- (* limit-level 2)))
4544 limit-level)))
4545 (outline-regexp
4546 (cond
4547 ((not (org-mode-p)) outline-regexp)
4548 (org-cycle-include-plain-lists
4549 (concat "\\(?:\\*"
4550 (if nstars (format "\\{1,%d\\} " nstars) "+")
4551 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4552 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4553 (bob-special (and org-cycle-global-at-bob (bobp)
4554 (not (looking-at outline-regexp))))
4555 (org-cycle-hook
4556 (if bob-special
4557 (delq 'org-optimize-window-after-visibility-change
4558 (copy-sequence org-cycle-hook))
4559 org-cycle-hook))
4560 (pos (point)))
4562 (if (or bob-special (equal arg '(4)))
4563 ;; special case: use global cycling
4564 (setq arg t))
4566 (cond
4568 ((equal arg '(16))
4569 (org-set-startup-visibility)
4570 (message "Startup visibility, plus VISIBILITY properties"))
4572 ((equal arg '(64))
4573 (show-all)
4574 (message "Entire buffer visible, including drawers"))
4576 ((org-at-table-p 'any)
4577 ;; Enter the table or move to the next field in the table
4578 (or (org-table-recognize-table.el)
4579 (progn
4580 (if arg (org-table-edit-field t)
4581 (org-table-justify-field-maybe)
4582 (call-interactively 'org-table-next-field)))))
4584 ((eq arg t) ;; Global cycling
4586 (cond
4587 ((and (eq last-command this-command)
4588 (eq org-cycle-global-status 'overview))
4589 ;; We just created the overview - now do table of contents
4590 ;; This can be slow in very large buffers, so indicate action
4591 (message "CONTENTS...")
4592 (org-content)
4593 (message "CONTENTS...done")
4594 (setq org-cycle-global-status 'contents)
4595 (run-hook-with-args 'org-cycle-hook 'contents))
4597 ((and (eq last-command this-command)
4598 (eq org-cycle-global-status 'contents))
4599 ;; We just showed the table of contents - now show everything
4600 (show-all)
4601 (message "SHOW ALL")
4602 (setq org-cycle-global-status 'all)
4603 (run-hook-with-args 'org-cycle-hook 'all))
4606 ;; Default action: go to overview
4607 (org-overview)
4608 (message "OVERVIEW")
4609 (setq org-cycle-global-status 'overview)
4610 (run-hook-with-args 'org-cycle-hook 'overview))))
4612 ((and org-drawers org-drawer-regexp
4613 (save-excursion
4614 (beginning-of-line 1)
4615 (looking-at org-drawer-regexp)))
4616 ;; Toggle block visibility
4617 (org-flag-drawer
4618 (not (get-char-property (match-end 0) 'invisible))))
4620 ((integerp arg)
4621 ;; Show-subtree, ARG levels up from here.
4622 (save-excursion
4623 (org-back-to-heading)
4624 (outline-up-heading (if (< arg 0) (- arg)
4625 (- (funcall outline-level) arg)))
4626 (org-show-subtree)))
4628 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4629 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4630 ;; At a heading: rotate between three different views
4631 (org-back-to-heading)
4632 (let ((goal-column 0) eoh eol eos)
4633 ;; First, some boundaries
4634 (save-excursion
4635 (org-back-to-heading)
4636 (save-excursion
4637 (beginning-of-line 2)
4638 (while (and (not (eobp)) ;; this is like `next-line'
4639 (get-char-property (1- (point)) 'invisible))
4640 (beginning-of-line 2)) (setq eol (point)))
4641 (outline-end-of-heading) (setq eoh (point))
4642 (org-end-of-subtree t)
4643 (unless (eobp)
4644 (skip-chars-forward " \t\n")
4645 (beginning-of-line 1) ; in case this is an item
4647 (setq eos (1- (point))))
4648 ;; Find out what to do next and set `this-command'
4649 (cond
4650 ((= eos eoh)
4651 ;; Nothing is hidden behind this heading
4652 (message "EMPTY ENTRY")
4653 (setq org-cycle-subtree-status nil)
4654 (save-excursion
4655 (goto-char eos)
4656 (outline-next-heading)
4657 (if (org-invisible-p) (org-flag-heading nil))))
4658 ((or (>= eol eos)
4659 (not (string-match "\\S-" (buffer-substring eol eos))))
4660 ;; Entire subtree is hidden in one line: open it
4661 (org-show-entry)
4662 (show-children)
4663 (message "CHILDREN")
4664 (save-excursion
4665 (goto-char eos)
4666 (outline-next-heading)
4667 (if (org-invisible-p) (org-flag-heading nil)))
4668 (setq org-cycle-subtree-status 'children)
4669 (run-hook-with-args 'org-cycle-hook 'children))
4670 ((and (eq last-command this-command)
4671 (eq org-cycle-subtree-status 'children))
4672 ;; We just showed the children, now show everything.
4673 (org-show-subtree)
4674 (message "SUBTREE")
4675 (setq org-cycle-subtree-status 'subtree)
4676 (run-hook-with-args 'org-cycle-hook 'subtree))
4678 ;; Default action: hide the subtree.
4679 (hide-subtree)
4680 (message "FOLDED")
4681 (setq org-cycle-subtree-status 'folded)
4682 (run-hook-with-args 'org-cycle-hook 'folded)))))
4684 ;; TAB emulation and template completion
4685 (buffer-read-only (org-back-to-heading))
4687 ((org-try-structure-completion))
4689 ((org-try-cdlatex-tab))
4691 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4692 (or (not (bolp))
4693 (not (looking-at outline-regexp))))
4694 (call-interactively (global-key-binding "\t")))
4696 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4697 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4698 (or (and (eq org-cycle-emulate-tab 'white)
4699 (= (match-end 0) (point-at-eol)))
4700 (and (eq org-cycle-emulate-tab 'whitestart)
4701 (>= (match-end 0) pos))))
4703 (eq org-cycle-emulate-tab t))
4704 (call-interactively (global-key-binding "\t")))
4706 (t (save-excursion
4707 (org-back-to-heading)
4708 (org-cycle))))))
4710 ;;;###autoload
4711 (defun org-global-cycle (&optional arg)
4712 "Cycle the global visibility. For details see `org-cycle'.
4713 With C-u prefix arg, switch to startup visibility.
4714 With a numeric prefix, show all headlines up to that level."
4715 (interactive "P")
4716 (let ((org-cycle-include-plain-lists
4717 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4718 (cond
4719 ((integerp arg)
4720 (show-all)
4721 (hide-sublevels arg)
4722 (setq org-cycle-global-status 'contents))
4723 ((equal arg '(4))
4724 (org-set-startup-visibility)
4725 (message "Startup visibility, plus VISIBILITY properties."))
4727 (org-cycle '(4))))))
4729 (defun org-set-startup-visibility ()
4730 "Set the visibility required by startup options and properties."
4731 (cond
4732 ((eq org-startup-folded t)
4733 (org-cycle '(4)))
4734 ((eq org-startup-folded 'content)
4735 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4736 (org-cycle '(4)) (org-cycle '(4)))))
4737 (org-set-visibility-according-to-property 'no-cleanup)
4738 (org-cycle-hide-archived-subtrees 'all)
4739 (org-cycle-hide-drawers 'all)
4740 (org-cycle-show-empty-lines 'all))
4742 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4743 "Switch subtree visibilities according to :VISIBILITY: property."
4744 (interactive)
4745 (let (org-show-entry-below state)
4746 (save-excursion
4747 (goto-char (point-min))
4748 (while (re-search-forward
4749 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4750 nil t)
4751 (setq state (match-string 1))
4752 (save-excursion
4753 (org-back-to-heading t)
4754 (hide-subtree)
4755 (org-reveal)
4756 (cond
4757 ((equal state '("fold" "folded"))
4758 (hide-subtree))
4759 ((equal state "children")
4760 (org-show-hidden-entry)
4761 (show-children))
4762 ((equal state "content")
4763 (save-excursion
4764 (save-restriction
4765 (org-narrow-to-subtree)
4766 (org-content))))
4767 ((member state '("all" "showall"))
4768 (show-subtree)))))
4769 (unless no-cleanup
4770 (org-cycle-hide-archived-subtrees 'all)
4771 (org-cycle-hide-drawers 'all)
4772 (org-cycle-show-empty-lines 'all)))))
4774 (defun org-overview ()
4775 "Switch to overview mode, showing only top-level headlines.
4776 Really, this shows all headlines with level equal or greater than the level
4777 of the first headline in the buffer. This is important, because if the
4778 first headline is not level one, then (hide-sublevels 1) gives confusing
4779 results."
4780 (interactive)
4781 (let ((level (save-excursion
4782 (goto-char (point-min))
4783 (if (re-search-forward (concat "^" outline-regexp) nil t)
4784 (progn
4785 (goto-char (match-beginning 0))
4786 (funcall outline-level))))))
4787 (and level (hide-sublevels level))))
4789 (defun org-content (&optional arg)
4790 "Show all headlines in the buffer, like a table of contents.
4791 With numerical argument N, show content up to level N."
4792 (interactive "P")
4793 (save-excursion
4794 ;; Visit all headings and show their offspring
4795 (and (integerp arg) (org-overview))
4796 (goto-char (point-max))
4797 (catch 'exit
4798 (while (and (progn (condition-case nil
4799 (outline-previous-visible-heading 1)
4800 (error (goto-char (point-min))))
4802 (looking-at outline-regexp))
4803 (if (integerp arg)
4804 (show-children (1- arg))
4805 (show-branches))
4806 (if (bobp) (throw 'exit nil))))))
4809 (defun org-optimize-window-after-visibility-change (state)
4810 "Adjust the window after a change in outline visibility.
4811 This function is the default value of the hook `org-cycle-hook'."
4812 (when (get-buffer-window (current-buffer))
4813 (cond
4814 ((eq state 'content) nil)
4815 ((eq state 'all) nil)
4816 ((eq state 'folded) nil)
4817 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4818 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4820 (defun org-compact-display-after-subtree-move ()
4821 "Show a compacter version of the tree of the entry's parent."
4822 (save-excursion
4823 (if (org-up-heading-safe)
4824 (progn
4825 (hide-subtree)
4826 (show-entry)
4827 (show-children)
4828 (org-cycle-show-empty-lines 'children)
4829 (org-cycle-hide-drawers 'children))
4830 (org-overview))))
4832 (defun org-cycle-show-empty-lines (state)
4833 "Show empty lines above all visible headlines.
4834 The region to be covered depends on STATE when called through
4835 `org-cycle-hook'. Lisp program can use t for STATE to get the
4836 entire buffer covered. Note that an empty line is only shown if there
4837 are at least `org-cycle-separator-lines' empty lines before the headline."
4838 (when (> org-cycle-separator-lines 0)
4839 (save-excursion
4840 (let* ((n org-cycle-separator-lines)
4841 (re (cond
4842 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4843 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4844 (t (let ((ns (number-to-string (- n 2))))
4845 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4846 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4847 beg end)
4848 (cond
4849 ((memq state '(overview contents t))
4850 (setq beg (point-min) end (point-max)))
4851 ((memq state '(children folded))
4852 (setq beg (point) end (progn (org-end-of-subtree t t)
4853 (beginning-of-line 2)
4854 (point)))))
4855 (when beg
4856 (goto-char beg)
4857 (while (re-search-forward re end t)
4858 (if (not (get-char-property (match-end 1) 'invisible))
4859 (outline-flag-region
4860 (match-beginning 1) (match-end 1) nil)))))))
4861 ;; Never hide empty lines at the end of the file.
4862 (save-excursion
4863 (goto-char (point-max))
4864 (outline-previous-heading)
4865 (outline-end-of-heading)
4866 (if (and (looking-at "[ \t\n]+")
4867 (= (match-end 0) (point-max)))
4868 (outline-flag-region (point) (match-end 0) nil))))
4870 (defun org-show-empty-lines-in-parent ()
4871 "Move to the parent and re-show empty lines before visible headlines."
4872 (save-excursion
4873 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4874 (org-cycle-show-empty-lines context))))
4876 (defun org-cycle-hide-drawers (state)
4877 "Re-hide all drawers after a visibility state change."
4878 (when (and (org-mode-p)
4879 (not (memq state '(overview folded))))
4880 (save-excursion
4881 (let* ((globalp (memq state '(contents all)))
4882 (beg (if globalp (point-min) (point)))
4883 (end (if globalp (point-max) (org-end-of-subtree t))))
4884 (goto-char beg)
4885 (while (re-search-forward org-drawer-regexp end t)
4886 (org-flag-drawer t))))))
4888 (defun org-flag-drawer (flag)
4889 (save-excursion
4890 (beginning-of-line 1)
4891 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4892 (let ((b (match-end 0))
4893 (outline-regexp org-outline-regexp))
4894 (if (re-search-forward
4895 "^[ \t]*:END:"
4896 (save-excursion (outline-next-heading) (point)) t)
4897 (outline-flag-region b (point-at-eol) flag)
4898 (error ":END: line missing"))))))
4900 (defun org-subtree-end-visible-p ()
4901 "Is the end of the current subtree visible?"
4902 (pos-visible-in-window-p
4903 (save-excursion (org-end-of-subtree t) (point))))
4905 (defun org-first-headline-recenter (&optional N)
4906 "Move cursor to the first headline and recenter the headline.
4907 Optional argument N means, put the headline into the Nth line of the window."
4908 (goto-char (point-min))
4909 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4910 (beginning-of-line)
4911 (recenter (prefix-numeric-value N))))
4913 ;;; Org-goto
4915 (defvar org-goto-window-configuration nil)
4916 (defvar org-goto-marker nil)
4917 (defvar org-goto-map
4918 (let ((map (make-sparse-keymap)))
4919 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4920 (while (setq cmd (pop cmds))
4921 (substitute-key-definition cmd cmd map global-map)))
4922 (suppress-keymap map)
4923 (org-defkey map "\C-m" 'org-goto-ret)
4924 (org-defkey map [(return)] 'org-goto-ret)
4925 (org-defkey map [(left)] 'org-goto-left)
4926 (org-defkey map [(right)] 'org-goto-right)
4927 (org-defkey map [(control ?g)] 'org-goto-quit)
4928 (org-defkey map "\C-i" 'org-cycle)
4929 (org-defkey map [(tab)] 'org-cycle)
4930 (org-defkey map [(down)] 'outline-next-visible-heading)
4931 (org-defkey map [(up)] 'outline-previous-visible-heading)
4932 (if org-goto-auto-isearch
4933 (if (fboundp 'define-key-after)
4934 (define-key-after map [t] 'org-goto-local-auto-isearch)
4935 nil)
4936 (org-defkey map "q" 'org-goto-quit)
4937 (org-defkey map "n" 'outline-next-visible-heading)
4938 (org-defkey map "p" 'outline-previous-visible-heading)
4939 (org-defkey map "f" 'outline-forward-same-level)
4940 (org-defkey map "b" 'outline-backward-same-level)
4941 (org-defkey map "u" 'outline-up-heading))
4942 (org-defkey map "/" 'org-occur)
4943 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4944 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4945 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4946 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4947 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4948 map))
4950 (defconst org-goto-help
4951 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4952 RET=jump to location [Q]uit and return to previous location
4953 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4955 (defvar org-goto-start-pos) ; dynamically scoped parameter
4957 ;; FIXME: Docstring doe not mention both interfaces
4958 (defun org-goto (&optional alternative-interface)
4959 "Look up a different location in the current file, keeping current visibility.
4961 When you want look-up or go to a different location in a document, the
4962 fastest way is often to fold the entire buffer and then dive into the tree.
4963 This method has the disadvantage, that the previous location will be folded,
4964 which may not be what you want.
4966 This command works around this by showing a copy of the current buffer
4967 in an indirect buffer, in overview mode. You can dive into the tree in
4968 that copy, use org-occur and incremental search to find a location.
4969 When pressing RET or `Q', the command returns to the original buffer in
4970 which the visibility is still unchanged. After RET is will also jump to
4971 the location selected in the indirect buffer and expose the
4972 the headline hierarchy above."
4973 (interactive "P")
4974 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4975 (org-refile-use-outline-path t)
4976 (interface
4977 (if (not alternative-interface)
4978 org-goto-interface
4979 (if (eq org-goto-interface 'outline)
4980 'outline-path-completion
4981 'outline)))
4982 (org-goto-start-pos (point))
4983 (selected-point
4984 (if (eq interface 'outline)
4985 (car (org-get-location (current-buffer) org-goto-help))
4986 (nth 3 (org-refile-get-location "Goto: ")))))
4987 (if selected-point
4988 (progn
4989 (org-mark-ring-push org-goto-start-pos)
4990 (goto-char selected-point)
4991 (if (or (org-invisible-p) (org-invisible-p2))
4992 (org-show-context 'org-goto)))
4993 (message "Quit"))))
4995 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4996 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4997 (defvar org-goto-local-auto-isearch-map) ; defined below
4999 (defun org-get-location (buf help)
5000 "Let the user select a location in the Org-mode buffer BUF.
5001 This function uses a recursive edit. It returns the selected position
5002 or nil."
5003 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5004 (isearch-hide-immediately nil)
5005 (isearch-search-fun-function
5006 (lambda () 'org-goto-local-search-headings))
5007 (org-goto-selected-point org-goto-exit-command))
5008 (save-excursion
5009 (save-window-excursion
5010 (delete-other-windows)
5011 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5012 (switch-to-buffer
5013 (condition-case nil
5014 (make-indirect-buffer (current-buffer) "*org-goto*")
5015 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5016 (with-output-to-temp-buffer "*Help*"
5017 (princ help))
5018 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5019 (setq buffer-read-only nil)
5020 (let ((org-startup-truncated t)
5021 (org-startup-folded nil)
5022 (org-startup-align-all-tables nil))
5023 (org-mode)
5024 (org-overview))
5025 (setq buffer-read-only t)
5026 (if (and (boundp 'org-goto-start-pos)
5027 (integer-or-marker-p org-goto-start-pos))
5028 (let ((org-show-hierarchy-above t)
5029 (org-show-siblings t)
5030 (org-show-following-heading t))
5031 (goto-char org-goto-start-pos)
5032 (and (org-invisible-p) (org-show-context)))
5033 (goto-char (point-min)))
5034 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5035 (message "Select location and press RET")
5036 (use-local-map org-goto-map)
5037 (recursive-edit)
5039 (kill-buffer "*org-goto*")
5040 (cons org-goto-selected-point org-goto-exit-command)))
5042 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5043 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5044 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5045 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5047 (defun org-goto-local-search-headings (string bound noerror)
5048 "Search and make sure that any matches are in headlines."
5049 (catch 'return
5050 (while (if isearch-forward
5051 (search-forward string bound noerror)
5052 (search-backward string bound noerror))
5053 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5054 (and (member :headline context)
5055 (not (member :tags context))))
5056 (throw 'return (point))))))
5058 (defun org-goto-local-auto-isearch ()
5059 "Start isearch."
5060 (interactive)
5061 (goto-char (point-min))
5062 (let ((keys (this-command-keys)))
5063 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5064 (isearch-mode t)
5065 (isearch-process-search-char (string-to-char keys)))))
5067 (defun org-goto-ret (&optional arg)
5068 "Finish `org-goto' by going to the new location."
5069 (interactive "P")
5070 (setq org-goto-selected-point (point)
5071 org-goto-exit-command 'return)
5072 (throw 'exit nil))
5074 (defun org-goto-left ()
5075 "Finish `org-goto' by going to the new location."
5076 (interactive)
5077 (if (org-on-heading-p)
5078 (progn
5079 (beginning-of-line 1)
5080 (setq org-goto-selected-point (point)
5081 org-goto-exit-command 'left)
5082 (throw 'exit nil))
5083 (error "Not on a heading")))
5085 (defun org-goto-right ()
5086 "Finish `org-goto' by going to the new location."
5087 (interactive)
5088 (if (org-on-heading-p)
5089 (progn
5090 (setq org-goto-selected-point (point)
5091 org-goto-exit-command 'right)
5092 (throw 'exit nil))
5093 (error "Not on a heading")))
5095 (defun org-goto-quit ()
5096 "Finish `org-goto' without cursor motion."
5097 (interactive)
5098 (setq org-goto-selected-point nil)
5099 (setq org-goto-exit-command 'quit)
5100 (throw 'exit nil))
5102 ;;; Indirect buffer display of subtrees
5104 (defvar org-indirect-dedicated-frame nil
5105 "This is the frame being used for indirect tree display.")
5106 (defvar org-last-indirect-buffer nil)
5108 (defun org-tree-to-indirect-buffer (&optional arg)
5109 "Create indirect buffer and narrow it to current subtree.
5110 With numerical prefix ARG, go up to this level and then take that tree.
5111 If ARG is negative, go up that many levels.
5112 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5113 indirect buffer previously made with this command, to avoid proliferation of
5114 indirect buffers. However, when you call the command with a `C-u' prefix, or
5115 when `org-indirect-buffer-display' is `new-frame', the last buffer
5116 is kept so that you can work with several indirect buffers at the same time.
5117 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5118 requests that a new frame be made for the new buffer, so that the dedicated
5119 frame is not changed."
5120 (interactive "P")
5121 (let ((cbuf (current-buffer))
5122 (cwin (selected-window))
5123 (pos (point))
5124 beg end level heading ibuf)
5125 (save-excursion
5126 (org-back-to-heading t)
5127 (when (numberp arg)
5128 (setq level (org-outline-level))
5129 (if (< arg 0) (setq arg (+ level arg)))
5130 (while (> (setq level (org-outline-level)) arg)
5131 (outline-up-heading 1 t)))
5132 (setq beg (point)
5133 heading (org-get-heading))
5134 (org-end-of-subtree t) (setq end (point)))
5135 (if (and (buffer-live-p org-last-indirect-buffer)
5136 (not (eq org-indirect-buffer-display 'new-frame))
5137 (not arg))
5138 (kill-buffer org-last-indirect-buffer))
5139 (setq ibuf (org-get-indirect-buffer cbuf)
5140 org-last-indirect-buffer ibuf)
5141 (cond
5142 ((or (eq org-indirect-buffer-display 'new-frame)
5143 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5144 (select-frame (make-frame))
5145 (delete-other-windows)
5146 (switch-to-buffer ibuf)
5147 (org-set-frame-title heading))
5148 ((eq org-indirect-buffer-display 'dedicated-frame)
5149 (raise-frame
5150 (select-frame (or (and org-indirect-dedicated-frame
5151 (frame-live-p org-indirect-dedicated-frame)
5152 org-indirect-dedicated-frame)
5153 (setq org-indirect-dedicated-frame (make-frame)))))
5154 (delete-other-windows)
5155 (switch-to-buffer ibuf)
5156 (org-set-frame-title (concat "Indirect: " heading)))
5157 ((eq org-indirect-buffer-display 'current-window)
5158 (switch-to-buffer ibuf))
5159 ((eq org-indirect-buffer-display 'other-window)
5160 (pop-to-buffer ibuf))
5161 (t (error "Invalid value.")))
5162 (if (featurep 'xemacs)
5163 (save-excursion (org-mode) (turn-on-font-lock)))
5164 (narrow-to-region beg end)
5165 (show-all)
5166 (goto-char pos)
5167 (and (window-live-p cwin) (select-window cwin))))
5169 (defun org-get-indirect-buffer (&optional buffer)
5170 (setq buffer (or buffer (current-buffer)))
5171 (let ((n 1) (base (buffer-name buffer)) bname)
5172 (while (buffer-live-p
5173 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5174 (setq n (1+ n)))
5175 (condition-case nil
5176 (make-indirect-buffer buffer bname 'clone)
5177 (error (make-indirect-buffer buffer bname)))))
5179 (defun org-set-frame-title (title)
5180 "Set the title of the current frame to the string TITLE."
5181 ;; FIXME: how to name a single frame in XEmacs???
5182 (unless (featurep 'xemacs)
5183 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5185 ;;;; Structure editing
5187 ;;; Inserting headlines
5189 (defun org-previous-line-empty-p ()
5190 (save-excursion
5191 (and (not (bobp))
5192 (or (beginning-of-line 0) t)
5193 (save-match-data
5194 (looking-at "[ \t]*$")))))
5196 (defun org-insert-heading (&optional force-heading)
5197 "Insert a new heading or item with same depth at point.
5198 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5199 If point is at the beginning of a headline, insert a sibling before the
5200 current headline. If point is not at the beginning, do not split the line,
5201 but create the new headline after the current line."
5202 (interactive "P")
5203 (if (= (buffer-size) 0)
5204 (insert "\n* ")
5205 (when (or force-heading (not (org-insert-item)))
5206 (let* ((empty-line-p nil)
5207 (head (save-excursion
5208 (condition-case nil
5209 (progn
5210 (org-back-to-heading)
5211 (setq empty-line-p (org-previous-line-empty-p))
5212 (match-string 0))
5213 (error "*"))))
5214 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5215 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5216 pos hide-previous previous-pos)
5217 (cond
5218 ((and (org-on-heading-p) (bolp)
5219 (or (bobp)
5220 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5221 ;; insert before the current line
5222 (open-line (if blank 2 1)))
5223 ((and (bolp)
5224 (or (bobp)
5225 (save-excursion
5226 (backward-char 1) (not (org-invisible-p)))))
5227 ;; insert right here
5228 nil)
5230 ;; somewhere in the line
5231 (save-excursion
5232 (setq previous-pos (point-at-bol))
5233 (end-of-line)
5234 (setq hide-previous (org-invisible-p)))
5235 (and org-insert-heading-respect-content (org-show-subtree))
5236 (let ((split
5237 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5238 (save-excursion
5239 (let ((p (point)))
5240 (goto-char (point-at-bol))
5241 (and (looking-at org-complex-heading-regexp)
5242 (> p (match-beginning 4)))))))
5243 tags pos)
5244 (cond
5245 (org-insert-heading-respect-content
5246 (org-end-of-subtree nil t)
5247 (or (bolp) (newline))
5248 (or (org-previous-line-empty-p)
5249 (and blank (newline)))
5250 (open-line 1))
5251 ((org-on-heading-p)
5252 (when hide-previous
5253 (show-children)
5254 (org-show-entry))
5255 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5256 (setq tags (and (match-end 2) (match-string 2)))
5257 (and (match-end 1)
5258 (delete-region (match-beginning 1) (match-end 1)))
5259 (setq pos (point-at-bol))
5260 (or split (end-of-line 1))
5261 (delete-horizontal-space)
5262 (newline (if blank 2 1))
5263 (when tags
5264 (save-excursion
5265 (goto-char pos)
5266 (end-of-line 1)
5267 (insert " " tags)
5268 (org-set-tags nil 'align))))
5270 (or split (end-of-line 1))
5271 (newline (if blank 2 1)))))))
5272 (insert head) (just-one-space)
5273 (setq pos (point))
5274 (end-of-line 1)
5275 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5276 (when (and org-insert-heading-respect-content hide-previous)
5277 (save-excursion
5278 (goto-char previous-pos)
5279 (hide-subtree)))
5280 (run-hooks 'org-insert-heading-hook)))))
5282 (defun org-get-heading (&optional no-tags)
5283 "Return the heading of the current entry, without the stars."
5284 (save-excursion
5285 (org-back-to-heading t)
5286 (if (looking-at
5287 (if no-tags
5288 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5289 "\\*+[ \t]+\\([^\r\n]*\\)"))
5290 (match-string 1) "")))
5292 (defun org-heading-components ()
5293 "Return the components of the current heading.
5294 This is a list with the following elements:
5295 - the level as an integer
5296 - the reduced level, different if `org-odd-levels-only' is set.
5297 - the TODO keyword, or nil
5298 - the priority character, like ?A, or nil if no priority is given
5299 - the headline text itself, or the tags string if no headline text
5300 - the tags string, or nil."
5301 (save-excursion
5302 (org-back-to-heading t)
5303 (if (looking-at org-complex-heading-regexp)
5304 (list (length (match-string 1))
5305 (org-reduced-level (length (match-string 1)))
5306 (org-match-string-no-properties 2)
5307 (and (match-end 3) (aref (match-string 3) 2))
5308 (org-match-string-no-properties 4)
5309 (org-match-string-no-properties 5)))))
5311 (defun org-insert-heading-after-current ()
5312 "Insert a new heading with same level as current, after current subtree."
5313 (interactive)
5314 (org-back-to-heading)
5315 (org-insert-heading)
5316 (org-move-subtree-down)
5317 (end-of-line 1))
5319 (defun org-insert-heading-respect-content ()
5320 (interactive)
5321 (let ((org-insert-heading-respect-content t))
5322 (org-insert-heading t)))
5324 (defun org-insert-todo-heading-respect-content (&optional force-state)
5325 (interactive "P")
5326 (let ((org-insert-heading-respect-content t))
5327 (org-insert-todo-heading force-state t)))
5329 (defun org-insert-todo-heading (arg &optional force-heading)
5330 "Insert a new heading with the same level and TODO state as current heading.
5331 If the heading has no TODO state, or if the state is DONE, use the first
5332 state (TODO by default). Also with prefix arg, force first state."
5333 (interactive "P")
5334 (when (or force-heading (not (org-insert-item 'checkbox)))
5335 (org-insert-heading force-heading)
5336 (save-excursion
5337 (org-back-to-heading)
5338 (outline-previous-heading)
5339 (looking-at org-todo-line-regexp))
5340 (let*
5341 ((new-mark-x
5342 (if (or arg
5343 (not (match-beginning 2))
5344 (member (match-string 2) org-done-keywords))
5345 (car org-todo-keywords-1)
5346 (match-string 2)))
5347 (new-mark
5349 (run-hook-with-args-until-success
5350 'org-todo-get-default-hook new-mark-x nil)
5351 new-mark-x)))
5352 (beginning-of-line 1)
5353 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5354 (insert new-mark " ")))
5355 (when org-provide-todo-statistics
5356 (org-update-parent-todo-statistics))))
5358 (defun org-insert-subheading (arg)
5359 "Insert a new subheading and demote it.
5360 Works for outline headings and for plain lists alike."
5361 (interactive "P")
5362 (org-insert-heading arg)
5363 (cond
5364 ((org-on-heading-p) (org-do-demote))
5365 ((org-at-item-p) (org-indent-item 1))))
5367 (defun org-insert-todo-subheading (arg)
5368 "Insert a new subheading with TODO keyword or checkbox and demote it.
5369 Works for outline headings and for plain lists alike."
5370 (interactive "P")
5371 (org-insert-todo-heading arg)
5372 (cond
5373 ((org-on-heading-p) (org-do-demote))
5374 ((org-at-item-p) (org-indent-item 1))))
5376 ;;; Promotion and Demotion
5378 (defun org-promote-subtree ()
5379 "Promote the entire subtree.
5380 See also `org-promote'."
5381 (interactive)
5382 (save-excursion
5383 (org-map-tree 'org-promote))
5384 (org-fix-position-after-promote))
5386 (defun org-demote-subtree ()
5387 "Demote the entire subtree. See `org-demote'.
5388 See also `org-promote'."
5389 (interactive)
5390 (save-excursion
5391 (org-map-tree 'org-demote))
5392 (org-fix-position-after-promote))
5395 (defun org-do-promote ()
5396 "Promote the current heading higher up the tree.
5397 If the region is active in `transient-mark-mode', promote all headings
5398 in the region."
5399 (interactive)
5400 (save-excursion
5401 (if (org-region-active-p)
5402 (org-map-region 'org-promote (region-beginning) (region-end))
5403 (org-promote)))
5404 (org-fix-position-after-promote))
5406 (defun org-do-demote ()
5407 "Demote the current heading lower down the tree.
5408 If the region is active in `transient-mark-mode', demote all headings
5409 in the region."
5410 (interactive)
5411 (save-excursion
5412 (if (org-region-active-p)
5413 (org-map-region 'org-demote (region-beginning) (region-end))
5414 (org-demote)))
5415 (org-fix-position-after-promote))
5417 (defun org-fix-position-after-promote ()
5418 "Make sure that after pro/demotion cursor position is right."
5419 (let ((pos (point)))
5420 (when (save-excursion
5421 (beginning-of-line 1)
5422 (looking-at org-todo-line-regexp)
5423 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5424 (cond ((eobp) (insert " "))
5425 ((eolp) (insert " "))
5426 ((equal (char-after) ?\ ) (forward-char 1))))))
5428 (defun org-reduced-level (l)
5429 "Compute the effective level of a heading.
5430 This takes into account the setting of `org-odd-levels-only'."
5431 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5433 (defun org-get-valid-level (level &optional change)
5434 "Rectify a level change under the influence of `org-odd-levels-only'
5435 LEVEL is a current level, CHANGE is by how much the level should be
5436 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5437 even level numbers will become the next higher odd number."
5438 (if org-odd-levels-only
5439 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5440 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5441 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5442 (max 1 (+ level (or change 0)))))
5444 (if (boundp 'define-obsolete-function-alias)
5445 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5446 (define-obsolete-function-alias 'org-get-legal-level
5447 'org-get-valid-level)
5448 (define-obsolete-function-alias 'org-get-legal-level
5449 'org-get-valid-level "23.1")))
5451 (defun org-promote ()
5452 "Promote the current heading higher up the tree.
5453 If the region is active in `transient-mark-mode', promote all headings
5454 in the region."
5455 (org-back-to-heading t)
5456 (let* ((level (save-match-data (funcall outline-level)))
5457 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5458 (diff (abs (- level (length up-head) -1))))
5459 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5460 (replace-match up-head nil t)
5461 ;; Fixup tag positioning
5462 (and org-auto-align-tags (org-set-tags nil t))
5463 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5465 (defun org-demote ()
5466 "Demote the current heading lower down the tree.
5467 If the region is active in `transient-mark-mode', demote all headings
5468 in the region."
5469 (org-back-to-heading t)
5470 (let* ((level (save-match-data (funcall outline-level)))
5471 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5472 (diff (abs (- level (length down-head) -1))))
5473 (replace-match down-head nil t)
5474 ;; Fixup tag positioning
5475 (and org-auto-align-tags (org-set-tags nil t))
5476 (if org-adapt-indentation (org-fixup-indentation diff))))
5478 (defun org-map-tree (fun)
5479 "Call FUN for every heading underneath the current one."
5480 (org-back-to-heading)
5481 (let ((level (funcall outline-level)))
5482 (save-excursion
5483 (funcall fun)
5484 (while (and (progn
5485 (outline-next-heading)
5486 (> (funcall outline-level) level))
5487 (not (eobp)))
5488 (funcall fun)))))
5490 (defun org-map-region (fun beg end)
5491 "Call FUN for every heading between BEG and END."
5492 (let ((org-ignore-region t))
5493 (save-excursion
5494 (setq end (copy-marker end))
5495 (goto-char beg)
5496 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5497 (< (point) end))
5498 (funcall fun))
5499 (while (and (progn
5500 (outline-next-heading)
5501 (< (point) end))
5502 (not (eobp)))
5503 (funcall fun)))))
5505 (defun org-fixup-indentation (diff)
5506 "Change the indentation in the current entry by DIFF
5507 However, if any line in the current entry has no indentation, or if it
5508 would end up with no indentation after the change, nothing at all is done."
5509 (save-excursion
5510 (let ((end (save-excursion (outline-next-heading)
5511 (point-marker)))
5512 (prohibit (if (> diff 0)
5513 "^\\S-"
5514 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5515 col)
5516 (unless (save-excursion (end-of-line 1)
5517 (re-search-forward prohibit end t))
5518 (while (and (< (point) end)
5519 (re-search-forward "^[ \t]+" end t))
5520 (goto-char (match-end 0))
5521 (setq col (current-column))
5522 (if (< diff 0) (replace-match ""))
5523 (org-indent-to-column (+ diff col))))
5524 (move-marker end nil))))
5526 (defun org-convert-to-odd-levels ()
5527 "Convert an org-mode file with all levels allowed to one with odd levels.
5528 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5529 level 5 etc."
5530 (interactive)
5531 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5532 (let ((org-odd-levels-only nil) n)
5533 (save-excursion
5534 (goto-char (point-min))
5535 (while (re-search-forward "^\\*\\*+ " nil t)
5536 (setq n (- (length (match-string 0)) 2))
5537 (while (>= (setq n (1- n)) 0)
5538 (org-demote))
5539 (end-of-line 1))))))
5542 (defun org-convert-to-oddeven-levels ()
5543 "Convert an org-mode file with only odd levels to one with odd and even levels.
5544 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5545 section with an even level, conversion would destroy the structure of the file. An error
5546 is signaled in this case."
5547 (interactive)
5548 (goto-char (point-min))
5549 ;; First check if there are no even levels
5550 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5551 (org-show-context t)
5552 (error "Not all levels are odd in this file. Conversion not possible."))
5553 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5554 (let ((org-odd-levels-only nil) n)
5555 (save-excursion
5556 (goto-char (point-min))
5557 (while (re-search-forward "^\\*\\*+ " nil t)
5558 (setq n (/ (1- (length (match-string 0))) 2))
5559 (while (>= (setq n (1- n)) 0)
5560 (org-promote))
5561 (end-of-line 1))))))
5563 (defun org-tr-level (n)
5564 "Make N odd if required."
5565 (if org-odd-levels-only (1+ (/ n 2)) n))
5567 ;;; Vertical tree motion, cutting and pasting of subtrees
5569 (defun org-move-subtree-up (&optional arg)
5570 "Move the current subtree up past ARG headlines of the same level."
5571 (interactive "p")
5572 (org-move-subtree-down (- (prefix-numeric-value arg))))
5574 (defun org-move-subtree-down (&optional arg)
5575 "Move the current subtree down past ARG headlines of the same level."
5576 (interactive "p")
5577 (setq arg (prefix-numeric-value arg))
5578 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5579 'outline-get-last-sibling))
5580 (ins-point (make-marker))
5581 (cnt (abs arg))
5582 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5583 ;; Select the tree
5584 (org-back-to-heading)
5585 (setq beg0 (point))
5586 (save-excursion
5587 (setq ne-beg (org-back-over-empty-lines))
5588 (setq beg (point)))
5589 (save-match-data
5590 (save-excursion (outline-end-of-heading)
5591 (setq folded (org-invisible-p)))
5592 (outline-end-of-subtree))
5593 (outline-next-heading)
5594 (setq ne-end (org-back-over-empty-lines))
5595 (setq end (point))
5596 (goto-char beg0)
5597 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5598 ;; include less whitespace
5599 (save-excursion
5600 (goto-char beg)
5601 (forward-line (- ne-beg ne-end))
5602 (setq beg (point))))
5603 ;; Find insertion point, with error handling
5604 (while (> cnt 0)
5605 (or (and (funcall movfunc) (looking-at outline-regexp))
5606 (progn (goto-char beg0)
5607 (error "Cannot move past superior level or buffer limit")))
5608 (setq cnt (1- cnt)))
5609 (if (> arg 0)
5610 ;; Moving forward - still need to move over subtree
5611 (progn (org-end-of-subtree t t)
5612 (save-excursion
5613 (org-back-over-empty-lines)
5614 (or (bolp) (newline)))))
5615 (setq ne-ins (org-back-over-empty-lines))
5616 (move-marker ins-point (point))
5617 (setq txt (buffer-substring beg end))
5618 (org-save-markers-in-region beg end)
5619 (delete-region beg end)
5620 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5621 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5622 (and (not (bolp)) (looking-at "\n") (forward-char 1))
5623 (let ((bbb (point)))
5624 (insert-before-markers txt)
5625 (org-reinstall-markers-in-region bbb)
5626 (move-marker ins-point bbb))
5627 (or (bolp) (insert "\n"))
5628 (setq ins-end (point))
5629 (goto-char ins-point)
5630 (org-skip-whitespace)
5631 (when (and (< arg 0)
5632 (org-first-sibling-p)
5633 (> ne-ins ne-beg))
5634 ;; Move whitespace back to beginning
5635 (save-excursion
5636 (goto-char ins-end)
5637 (let ((kill-whole-line t))
5638 (kill-line (- ne-ins ne-beg)) (point)))
5639 (insert (make-string (- ne-ins ne-beg) ?\n)))
5640 (move-marker ins-point nil)
5641 (org-compact-display-after-subtree-move)
5642 (org-show-empty-lines-in-parent)
5643 (unless folded
5644 (org-show-entry)
5645 (show-children)
5646 (org-cycle-hide-drawers 'children))))
5648 (defvar org-subtree-clip ""
5649 "Clipboard for cut and paste of subtrees.
5650 This is actually only a copy of the kill, because we use the normal kill
5651 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5653 (defvar org-subtree-clip-folded nil
5654 "Was the last copied subtree folded?
5655 This is used to fold the tree back after pasting.")
5657 (defun org-cut-subtree (&optional n)
5658 "Cut the current subtree into the clipboard.
5659 With prefix arg N, cut this many sequential subtrees.
5660 This is a short-hand for marking the subtree and then cutting it."
5661 (interactive "p")
5662 (org-copy-subtree n 'cut))
5664 (defun org-copy-subtree (&optional n cut force-store-markers)
5665 "Cut the current subtree into the clipboard.
5666 With prefix arg N, cut this many sequential subtrees.
5667 This is a short-hand for marking the subtree and then copying it.
5668 If CUT is non-nil, actually cut the subtree.
5669 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5670 of some markers in the region, even if CUT is non-nil. This is
5671 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5672 (interactive "p")
5673 (let (beg end folded (beg0 (point)))
5674 (if (interactive-p)
5675 (org-back-to-heading nil) ; take what looks like a subtree
5676 (org-back-to-heading t)) ; take what is really there
5677 (org-back-over-empty-lines)
5678 (setq beg (point))
5679 (skip-chars-forward " \t\r\n")
5680 (save-match-data
5681 (save-excursion (outline-end-of-heading)
5682 (setq folded (org-invisible-p)))
5683 (condition-case nil
5684 (outline-forward-same-level (1- n))
5685 (error nil))
5686 (org-end-of-subtree t t))
5687 (org-back-over-empty-lines)
5688 (setq end (point))
5689 (goto-char beg0)
5690 (when (> end beg)
5691 (setq org-subtree-clip-folded folded)
5692 (when (or cut force-store-markers)
5693 (org-save-markers-in-region beg end))
5694 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5695 (setq org-subtree-clip (current-kill 0))
5696 (message "%s: Subtree(s) with %d characters"
5697 (if cut "Cut" "Copied")
5698 (length org-subtree-clip)))))
5700 (defun org-paste-subtree (&optional level tree for-yank)
5701 "Paste the clipboard as a subtree, with modification of headline level.
5702 The entire subtree is promoted or demoted in order to match a new headline
5703 level.
5705 If the cursor is at the beginning of a headline, the same level as
5706 that headline is used to paste the tree
5708 If not, the new level is derived from the *visible* headings
5709 before and after the insertion point, and taken to be the inferior headline
5710 level of the two. So if the previous visible heading is level 3 and the
5711 next is level 4 (or vice versa), level 4 will be used for insertion.
5712 This makes sure that the subtree remains an independent subtree and does
5713 not swallow low level entries.
5715 You can also force a different level, either by using a numeric prefix
5716 argument, or by inserting the heading marker by hand. For example, if the
5717 cursor is after \"*****\", then the tree will be shifted to level 5.
5719 If optional TREE is given, use this text instead of the kill ring.
5721 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5722 move back over whitespace before inserting, and move point to the end of
5723 the inserted text when done."
5724 (interactive "P")
5725 (unless (org-kill-is-subtree-p tree)
5726 (error "%s"
5727 (substitute-command-keys
5728 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5729 (let* ((visp (not (org-invisible-p)))
5730 (txt (or tree (and kill-ring (current-kill 0))))
5731 (^re (concat "^\\(" outline-regexp "\\)"))
5732 (re (concat "\\(" outline-regexp "\\)"))
5733 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5735 (old-level (if (string-match ^re txt)
5736 (- (match-end 0) (match-beginning 0) 1)
5737 -1))
5738 (force-level (cond (level (prefix-numeric-value level))
5739 ((and (looking-at "[ \t]*$")
5740 (string-match
5741 ^re_ (buffer-substring
5742 (point-at-bol) (point))))
5743 (- (match-end 1) (match-beginning 1)))
5744 ((and (bolp)
5745 (looking-at org-outline-regexp))
5746 (- (match-end 0) (point) 1))
5747 (t nil)))
5748 (previous-level (save-excursion
5749 (condition-case nil
5750 (progn
5751 (outline-previous-visible-heading 1)
5752 (if (looking-at re)
5753 (- (match-end 0) (match-beginning 0) 1)
5755 (error 1))))
5756 (next-level (save-excursion
5757 (condition-case nil
5758 (progn
5759 (or (looking-at outline-regexp)
5760 (outline-next-visible-heading 1))
5761 (if (looking-at re)
5762 (- (match-end 0) (match-beginning 0) 1)
5764 (error 1))))
5765 (new-level (or force-level (max previous-level next-level)))
5766 (shift (if (or (= old-level -1)
5767 (= new-level -1)
5768 (= old-level new-level))
5770 (- new-level old-level)))
5771 (delta (if (> shift 0) -1 1))
5772 (func (if (> shift 0) 'org-demote 'org-promote))
5773 (org-odd-levels-only nil)
5774 beg end newend)
5775 ;; Remove the forced level indicator
5776 (if force-level
5777 (delete-region (point-at-bol) (point)))
5778 ;; Paste
5779 (beginning-of-line 1)
5780 (unless for-yank (org-back-over-empty-lines))
5781 (setq beg (point))
5782 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5783 (insert-before-markers txt)
5784 (unless (string-match "\n\\'" txt) (insert "\n"))
5785 (setq newend (point))
5786 (org-reinstall-markers-in-region beg)
5787 (setq end (point))
5788 (goto-char beg)
5789 (skip-chars-forward " \t\n\r")
5790 (setq beg (point))
5791 (if (and (org-invisible-p) visp)
5792 (save-excursion (outline-show-heading)))
5793 ;; Shift if necessary
5794 (unless (= shift 0)
5795 (save-restriction
5796 (narrow-to-region beg end)
5797 (while (not (= shift 0))
5798 (org-map-region func (point-min) (point-max))
5799 (setq shift (+ delta shift)))
5800 (goto-char (point-min))
5801 (setq newend (point-max))))
5802 (when (or (interactive-p) for-yank)
5803 (message "Clipboard pasted as level %d subtree" new-level))
5804 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5805 kill-ring
5806 (eq org-subtree-clip (current-kill 0))
5807 org-subtree-clip-folded)
5808 ;; The tree was folded before it was killed/copied
5809 (hide-subtree))
5810 (and for-yank (goto-char newend))))
5812 (defun org-kill-is-subtree-p (&optional txt)
5813 "Check if the current kill is an outline subtree, or a set of trees.
5814 Returns nil if kill does not start with a headline, or if the first
5815 headline level is not the largest headline level in the tree.
5816 So this will actually accept several entries of equal levels as well,
5817 which is OK for `org-paste-subtree'.
5818 If optional TXT is given, check this string instead of the current kill."
5819 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5820 (start-level (and kill
5821 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5822 org-outline-regexp "\\)")
5823 kill)
5824 (- (match-end 2) (match-beginning 2) 1)))
5825 (re (concat "^" org-outline-regexp))
5826 (start (1+ (or (match-beginning 2) -1))))
5827 (if (not start-level)
5828 (progn
5829 nil) ;; does not even start with a heading
5830 (catch 'exit
5831 (while (setq start (string-match re kill (1+ start)))
5832 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5833 (throw 'exit nil)))
5834 t))))
5836 (defvar org-markers-to-move nil
5837 "Markers that should be moved with a cut-and-paste operation.
5838 Those markers are stored together with their positions relative to
5839 the start of the region.")
5841 (defun org-save-markers-in-region (beg end)
5842 "Check markers in region.
5843 If these markers are between BEG and END, record their position relative
5844 to BEG, so that after moving the block of text, we can put the markers back
5845 into place.
5846 This function gets called just before an entry or tree gets cut from the
5847 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5848 called immediately, to move the markers with the entries."
5849 (setq org-markers-to-move nil)
5850 (when (featurep 'org-clock)
5851 (org-clock-save-markers-for-cut-and-paste beg end))
5852 (when (featurep 'org-agenda)
5853 (org-agenda-save-markers-for-cut-and-paste beg end)))
5855 (defun org-check-and-save-marker (marker beg end)
5856 "Check if MARKER is between BEG and END.
5857 If yes, remember the marker and the distance to BEG."
5858 (when (and (marker-buffer marker)
5859 (equal (marker-buffer marker) (current-buffer)))
5860 (if (and (>= marker beg) (< marker end))
5861 (push (cons marker (- marker beg)) org-markers-to-move))))
5863 (defun org-reinstall-markers-in-region (beg)
5864 "Move all remembered markers to their position relative to BEG."
5865 (mapc (lambda (x)
5866 (move-marker (car x) (+ beg (cdr x))))
5867 org-markers-to-move)
5868 (setq org-markers-to-move nil))
5870 (defun org-narrow-to-subtree ()
5871 "Narrow buffer to the current subtree."
5872 (interactive)
5873 (save-excursion
5874 (save-match-data
5875 (narrow-to-region
5876 (progn (org-back-to-heading) (point))
5877 (progn (org-end-of-subtree t) (point))))))
5879 (defun org-clone-subtree-with-time-shift (n &optional shift)
5880 "Clone the task (subtree) at point N times.
5881 The clones will be inserted as siblings.
5883 In interactive use, the user will be prompted for the number of clones
5884 to be produced, and for a time SHIFT, which may be a repeater as used
5885 in time stamps, for example `+3d'.
5887 When a valid repeater is given and the entry contains any time stamps,
5888 the clones will become a sequence in time, with time stamps in the
5889 subtree shifted for each clone produced. If SHIFT is nil or the
5890 empty string, time stamps will be left alone.
5892 If the original subtree did contain time stamps with a repeater,
5893 the following will happen:
5894 - the repeater will be removed in each clone
5895 - an additional clone will be produced, with the current, unshifted
5896 date(s) in the entry.
5897 - the original entry will be placed *after* all the clones, with
5898 repeater intact.
5899 - the start days in the repeater in the original entry will be shifted
5900 to past the last clone.
5901 I this way you can spell out a number of instances of a repeating task,
5902 and still retain the repeater to cover future instances of the task."
5903 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
5904 (let (beg end template task
5905 shift-n shift-what doshift nmin nmax (n-no-remove -1))
5906 (if (not (and (integerp n) (> n 0)))
5907 (error "Invalid number of replications %s" n))
5908 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
5909 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
5910 shift)))
5911 (error "Invalid shift specification %s" shift))
5912 (when doshift
5913 (setq shift-n (string-to-number (match-string 1 shift))
5914 shift-what (cdr (assoc (match-string 2 shift)
5915 '(("d" . day) ("w" . week)
5916 ("m" . month) ("y" . year))))))
5917 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
5918 (setq nmin 1 nmax n)
5919 (org-back-to-heading t)
5920 (setq beg (point))
5921 (org-end-of-subtree t t)
5922 (setq end (point))
5923 (setq template (buffer-substring beg end))
5924 (when (and doshift
5925 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
5926 (delete-region beg end)
5927 (setq end beg)
5928 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
5929 (goto-char end)
5930 (loop for n from nmin to nmax do
5931 (if (not doshift)
5932 (setq task template)
5933 (with-temp-buffer
5934 (insert template)
5935 (org-mode)
5936 (goto-char (point-min))
5937 (while (re-search-forward org-ts-regexp nil t)
5938 (org-timestamp-change (* n shift-n) shift-what))
5939 (unless (= n n-no-remove)
5940 (goto-char (point-min))
5941 (while (re-search-forward org-ts-regexp nil t)
5942 (save-excursion
5943 (goto-char (match-beginning 0))
5944 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
5945 (delete-region (match-beginning 1) (match-end 1))))))
5946 (setq task (buffer-string))))
5947 (insert task))
5948 (goto-char beg)))
5950 ;;; Outline Sorting
5952 (defun org-sort (with-case)
5953 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5954 Optional argument WITH-CASE means sort case-sensitively.
5955 With a double prefix argument, also remove duplicate entries."
5956 (interactive "P")
5957 (if (org-at-table-p)
5958 (org-call-with-arg 'org-table-sort-lines with-case)
5959 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5961 (defun org-sort-remove-invisible (s)
5962 (remove-text-properties 0 (length s) org-rm-props s)
5963 (while (string-match org-bracket-link-regexp s)
5964 (setq s (replace-match (if (match-end 2)
5965 (match-string 3 s)
5966 (match-string 1 s)) t t s)))
5969 (defvar org-priority-regexp) ; defined later in the file
5971 (defun org-sort-entries-or-items
5972 (&optional with-case sorting-type getkey-func compare-func property)
5973 "Sort entries on a certain level of an outline tree.
5974 If there is an active region, the entries in the region are sorted.
5975 Else, if the cursor is before the first entry, sort the top-level items.
5976 Else, the children of the entry at point are sorted.
5978 Sorting can be alphabetically, numerically, and by date/time as given by
5979 the first time stamp in the entry. The command prompts for the sorting
5980 type unless it has been given to the function through the SORTING-TYPE
5981 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5982 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5983 called with point at the beginning of the record. It must return either
5984 a string or a number that should serve as the sorting key for that record.
5986 Comparing entries ignores case by default. However, with an optional argument
5987 WITH-CASE, the sorting considers case as well."
5988 (interactive "P")
5989 (let ((case-func (if with-case 'identity 'downcase))
5990 start beg end stars re re2
5991 txt what tmp plain-list-p)
5992 ;; Find beginning and end of region to sort
5993 (cond
5994 ((org-region-active-p)
5995 ;; we will sort the region
5996 (setq end (region-end)
5997 what "region")
5998 (goto-char (region-beginning))
5999 (if (not (org-on-heading-p)) (outline-next-heading))
6000 (setq start (point)))
6001 ((org-at-item-p)
6002 ;; we will sort this plain list
6003 (org-beginning-of-item-list) (setq start (point))
6004 (org-end-of-item-list) (setq end (point))
6005 (goto-char start)
6006 (setq plain-list-p t
6007 what "plain list"))
6008 ((or (org-on-heading-p)
6009 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6010 ;; we will sort the children of the current headline
6011 (org-back-to-heading)
6012 (setq start (point)
6013 end (progn (org-end-of-subtree t t)
6014 (org-back-over-empty-lines)
6015 (point))
6016 what "children")
6017 (goto-char start)
6018 (show-subtree)
6019 (outline-next-heading))
6021 ;; we will sort the top-level entries in this file
6022 (goto-char (point-min))
6023 (or (org-on-heading-p) (outline-next-heading))
6024 (setq start (point) end (point-max) what "top-level")
6025 (goto-char start)
6026 (show-all)))
6028 (setq beg (point))
6029 (if (>= beg end) (error "Nothing to sort"))
6031 (unless plain-list-p
6032 (looking-at "\\(\\*+\\)")
6033 (setq stars (match-string 1)
6034 re (concat "^" (regexp-quote stars) " +")
6035 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6036 txt (buffer-substring beg end))
6037 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6038 (if (and (not (equal stars "*")) (string-match re2 txt))
6039 (error "Region to sort contains a level above the first entry")))
6041 (unless sorting-type
6042 (message
6043 (if plain-list-p
6044 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6045 "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:")
6046 what)
6047 (setq sorting-type (read-char-exclusive))
6049 (and (= (downcase sorting-type) ?f)
6050 (setq getkey-func
6051 (org-ido-completing-read "Sort using function: "
6052 obarray 'fboundp t nil nil))
6053 (setq getkey-func (intern getkey-func)))
6055 (and (= (downcase sorting-type) ?r)
6056 (setq property
6057 (org-ido-completing-read "Property: "
6058 (mapcar 'list (org-buffer-property-keys t))
6059 nil t))))
6061 (message "Sorting entries...")
6063 (save-restriction
6064 (narrow-to-region start end)
6066 (let ((dcst (downcase sorting-type))
6067 (now (current-time)))
6068 (sort-subr
6069 (/= dcst sorting-type)
6070 ;; This function moves to the beginning character of the "record" to
6071 ;; be sorted.
6072 (if plain-list-p
6073 (lambda nil
6074 (if (org-at-item-p) t (goto-char (point-max))))
6075 (lambda nil
6076 (if (re-search-forward re nil t)
6077 (goto-char (match-beginning 0))
6078 (goto-char (point-max)))))
6079 ;; This function moves to the last character of the "record" being
6080 ;; sorted.
6081 (if plain-list-p
6082 'org-end-of-item
6083 (lambda nil
6084 (save-match-data
6085 (condition-case nil
6086 (outline-forward-same-level 1)
6087 (error
6088 (goto-char (point-max)))))))
6090 ;; This function returns the value that gets sorted against.
6091 (if plain-list-p
6092 (lambda nil
6093 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6094 (cond
6095 ((= dcst ?n)
6096 (string-to-number (buffer-substring (match-end 0)
6097 (point-at-eol))))
6098 ((= dcst ?a)
6099 (buffer-substring (match-end 0) (point-at-eol)))
6100 ((= dcst ?t)
6101 (if (re-search-forward org-ts-regexp
6102 (point-at-eol) t)
6103 (org-time-string-to-time (match-string 0))
6104 now))
6105 ((= dcst ?f)
6106 (if getkey-func
6107 (progn
6108 (setq tmp (funcall getkey-func))
6109 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6110 tmp)
6111 (error "Invalid key function `%s'" getkey-func)))
6112 (t (error "Invalid sorting type `%c'" sorting-type)))))
6113 (lambda nil
6114 (cond
6115 ((= dcst ?n)
6116 (if (looking-at org-complex-heading-regexp)
6117 (string-to-number (match-string 4))
6118 nil))
6119 ((= dcst ?a)
6120 (if (looking-at org-complex-heading-regexp)
6121 (funcall case-func (match-string 4))
6122 nil))
6123 ((= dcst ?t)
6124 (if (re-search-forward org-ts-regexp
6125 (save-excursion
6126 (forward-line 2)
6127 (point)) t)
6128 (org-time-string-to-time (match-string 0))
6129 now))
6130 ((= dcst ?p)
6131 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6132 (string-to-char (match-string 2))
6133 org-default-priority))
6134 ((= dcst ?r)
6135 (or (org-entry-get nil property) ""))
6136 ((= dcst ?o)
6137 (if (looking-at org-complex-heading-regexp)
6138 (- 9999 (length (member (match-string 2)
6139 org-todo-keywords-1)))))
6140 ((= dcst ?f)
6141 (if getkey-func
6142 (progn
6143 (setq tmp (funcall getkey-func))
6144 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6145 tmp)
6146 (error "Invalid key function `%s'" getkey-func)))
6147 (t (error "Invalid sorting type `%c'" sorting-type)))))
6149 (cond
6150 ((= dcst ?a) 'string<)
6151 ((= dcst ?t) 'time-less-p)
6152 ((= dcst ?f) compare-func)
6153 (t nil)))))
6154 (message "Sorting entries...done")))
6156 (defun org-do-sort (table what &optional with-case sorting-type)
6157 "Sort TABLE of WHAT according to SORTING-TYPE.
6158 The user will be prompted for the SORTING-TYPE if the call to this
6159 function does not specify it. WHAT is only for the prompt, to indicate
6160 what is being sorted. The sorting key will be extracted from
6161 the car of the elements of the table.
6162 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6163 (unless sorting-type
6164 (message
6165 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6166 what)
6167 (setq sorting-type (read-char-exclusive)))
6168 (let ((dcst (downcase sorting-type))
6169 extractfun comparefun)
6170 ;; Define the appropriate functions
6171 (cond
6172 ((= dcst ?n)
6173 (setq extractfun 'string-to-number
6174 comparefun (if (= dcst sorting-type) '< '>)))
6175 ((= dcst ?a)
6176 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6177 (lambda(x) (downcase (org-sort-remove-invisible x))))
6178 comparefun (if (= dcst sorting-type)
6179 'string<
6180 (lambda (a b) (and (not (string< a b))
6181 (not (string= a b)))))))
6182 ((= dcst ?t)
6183 (setq extractfun
6184 (lambda (x)
6185 (if (or (string-match org-ts-regexp x)
6186 (string-match org-ts-regexp-both x))
6187 (time-to-seconds
6188 (org-time-string-to-time (match-string 0 x)))
6190 comparefun (if (= dcst sorting-type) '< '>)))
6191 (t (error "Invalid sorting type `%c'" sorting-type)))
6193 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6194 table)
6195 (lambda (a b) (funcall comparefun (car a) (car b))))))
6197 ;;; Editing source examples
6199 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6200 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6201 (defvar org-edit-src-force-single-line nil)
6202 (defvar org-edit-src-from-org-mode nil)
6203 (defvar org-edit-src-picture nil)
6205 (define-minor-mode org-exit-edit-mode
6206 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6208 (defun org-edit-src-code ()
6209 "Edit the source code example at point.
6210 An indirect buffer is created, and that buffer is then narrowed to the
6211 example at point and switched to the correct language mode. When done,
6212 exit by killing the buffer with \\[org-edit-src-exit]."
6213 (interactive)
6214 (let ((line (org-current-line))
6215 (case-fold-search t)
6216 (msg (substitute-command-keys
6217 "Edit, then exit with C-c ' (C-c and single quote)"))
6218 (info (org-edit-src-find-region-and-lang))
6219 (org-mode-p (eq major-mode 'org-mode))
6220 beg end lang lang-f single lfmt)
6221 (if (not info)
6223 (setq beg (nth 0 info)
6224 end (nth 1 info)
6225 lang (nth 2 info)
6226 single (nth 3 info)
6227 lfmt (nth 4 info)
6228 lang-f (intern (concat lang "-mode")))
6229 (unless (functionp lang-f)
6230 (error "No such language mode: %s" lang-f))
6231 (goto-line line)
6232 (if (get-buffer "*Org Edit Src Example*")
6233 (kill-buffer "*Org Edit Src Example*"))
6234 (switch-to-buffer (make-indirect-buffer (current-buffer)
6235 "*Org Edit Src Example*"))
6236 (narrow-to-region beg end)
6237 (remove-text-properties beg end '(display nil invisible nil
6238 intangible nil))
6239 (let ((org-inhibit-startup t))
6240 (funcall lang-f))
6241 (set (make-local-variable 'org-edit-src-force-single-line) single)
6242 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6243 (when lfmt
6244 (set (make-local-variable 'org-coderef-label-format) lfmt))
6245 (when org-mode-p
6246 (goto-char (point-min))
6247 (while (re-search-forward "^," nil t)
6248 (replace-match "")))
6249 (goto-line line)
6250 (org-exit-edit-mode)
6251 (org-set-local 'header-line-format msg)
6252 (message "%s" msg)
6253 t)))
6255 (defun org-edit-fixed-width-region ()
6256 "Edit the fixed-width ascii drawing at point.
6257 This must be a region where each line starts with a colon followed by
6258 a space character.
6259 An indirect buffer is created, and that buffer is then narrowed to the
6260 example at point and switched to artist-mode. When done,
6261 exit by killing the buffer with \\[org-edit-src-exit]."
6262 (interactive)
6263 (let ((line (org-current-line))
6264 (case-fold-search t)
6265 (msg (substitute-command-keys
6266 "Edit, then exit with C-c ' (C-c and single quote)"))
6267 (org-mode-p (eq major-mode 'org-mode))
6268 beg end)
6269 (beginning-of-line 1)
6270 (if (looking-at "[ \t]*[^:\n \t]")
6272 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6273 (setq beg (point) end beg)
6274 (save-excursion
6275 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6276 (setq beg (point-at-bol 2))
6277 (setq beg (point))))
6278 (save-excursion
6279 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6280 (setq end (1- (match-beginning 0)))
6281 (setq end (point))))
6282 (goto-line line))
6283 (if (get-buffer "*Org Edit Picture*")
6284 (kill-buffer "*Org Edit Picture*"))
6285 (switch-to-buffer (make-indirect-buffer (current-buffer)
6286 "*Org Edit Picture*"))
6287 (narrow-to-region beg end)
6288 (remove-text-properties beg end '(display nil invisible nil
6289 intangible nil))
6290 (when (fboundp 'font-lock-unfontify-region)
6291 (font-lock-unfontify-region (point-min) (point-max)))
6292 (cond
6293 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6294 (fundamental-mode)
6295 (artist-mode 1))
6296 (t (funcall org-edit-fixed-width-region-mode)))
6297 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6298 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6299 (set (make-local-variable 'org-edit-src-picture) t)
6300 (goto-char (point-min))
6301 (while (re-search-forward "^[ \t]*: ?" nil t)
6302 (replace-match ""))
6303 (goto-line line)
6304 (org-exit-edit-mode)
6305 (org-set-local 'header-line-format msg)
6306 (message "%s" msg)
6307 t)))
6310 (defun org-edit-src-find-region-and-lang ()
6311 "Find the region and language for a local edit.
6312 Return a list with beginning and end of the region, a string representing
6313 the language, a switch telling of the content should be in a single line."
6314 (let ((re-list
6315 (append
6316 org-edit-src-region-extra
6318 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6319 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6320 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6321 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6322 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6323 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6324 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6325 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6326 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6327 ("^#\\+html:" "\n" "html" single-line)
6328 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6329 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6330 ("^#\\+latex:" "\n" "latex" single-line)
6331 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6332 ("^#\\+ascii:" "\n" "ascii" single-line)
6334 (pos (point))
6335 re1 re2 single beg end lang lfmt match-re1)
6336 (catch 'exit
6337 (while (setq entry (pop re-list))
6338 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6339 single (nth 3 entry))
6340 (save-excursion
6341 (if (or (looking-at re1)
6342 (re-search-backward re1 nil t))
6343 (progn
6344 (setq match-re1 (match-string 0))
6345 (setq beg (match-end 0)
6346 lang (org-edit-src-get-lang lang)
6347 lfmt (org-edit-src-get-label-format match-re1))
6348 (if (and (re-search-forward re2 nil t)
6349 (>= (match-end 0) pos))
6350 (throw 'exit (list beg (match-beginning 0)
6351 lang single lfmt))))
6352 (if (or (looking-at re2)
6353 (re-search-forward re2 nil t))
6354 (progn
6355 (setq end (match-beginning 0))
6356 (if (and (re-search-backward re1 nil t)
6357 (<= (match-beginning 0) pos))
6358 (progn
6359 (setq lfmt (org-edit-src-get-label-format
6360 (match-string 0)))
6361 (throw 'exit
6362 (list (match-end 0) end
6363 (org-edit-src-get-lang lang)
6364 single lfmt))))))))))))
6366 (defun org-edit-src-get-lang (lang)
6367 "Extract the src language."
6368 (let ((m (match-string 0)))
6369 (cond
6370 ((stringp lang) lang)
6371 ((integerp lang) (match-string lang))
6372 ((and (eq lang 'lang)
6373 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6374 (match-string 1 m))
6375 ((and (eq lang 'style)
6376 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6377 (match-string 1 m))
6378 (t "fundamental"))))
6380 (defun org-edit-src-get-label-format (s)
6381 "Extract the label format."
6382 (save-match-data
6383 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6384 (match-string 1 s))))
6386 (defun org-edit-src-exit ()
6387 "Exit special edit and protect problematic lines."
6388 (interactive)
6389 (unless (buffer-base-buffer (current-buffer))
6390 (error "This is not an indirect buffer, something is wrong..."))
6391 (unless (> (point-min) 1)
6392 (error "This buffer is not narrowed, something is wrong..."))
6393 (goto-char (point-min))
6394 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6395 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6396 (when (org-bound-and-true-p org-edit-src-force-single-line)
6397 (goto-char (point-min))
6398 (while (re-search-forward "\n" nil t)
6399 (replace-match " "))
6400 (goto-char (point-min))
6401 (if (looking-at "\\s-*") (replace-match " "))
6402 (if (re-search-forward "\\s-+\\'" nil t)
6403 (replace-match "")))
6404 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6405 (goto-char (point-min))
6406 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6407 (replace-match ",\\1"))
6408 (when font-lock-mode
6409 (font-lock-unfontify-region (point-min) (point-max)))
6410 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6411 (when (org-bound-and-true-p org-edit-src-picture)
6412 (untabify (point-min) (point-max))
6413 (goto-char (point-min))
6414 (while (re-search-forward "^" nil t)
6415 (replace-match ": "))
6416 (when font-lock-mode
6417 (font-lock-unfontify-region (point-min) (point-max)))
6418 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6419 (kill-buffer (current-buffer))
6420 (and (org-mode-p) (org-restart-font-lock)))
6423 ;;; The orgstruct minor mode
6425 ;; Define a minor mode which can be used in other modes in order to
6426 ;; integrate the org-mode structure editing commands.
6428 ;; This is really a hack, because the org-mode structure commands use
6429 ;; keys which normally belong to the major mode. Here is how it
6430 ;; works: The minor mode defines all the keys necessary to operate the
6431 ;; structure commands, but wraps the commands into a function which
6432 ;; tests if the cursor is currently at a headline or a plain list
6433 ;; item. If that is the case, the structure command is used,
6434 ;; temporarily setting many Org-mode variables like regular
6435 ;; expressions for filling etc. However, when any of those keys is
6436 ;; used at a different location, function uses `key-binding' to look
6437 ;; up if the key has an associated command in another currently active
6438 ;; keymap (minor modes, major mode, global), and executes that
6439 ;; command. There might be problems if any of the keys is otherwise
6440 ;; used as a prefix key.
6442 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6443 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6444 ;; addresses this by checking explicitly for both bindings.
6446 (defvar orgstruct-mode-map (make-sparse-keymap)
6447 "Keymap for the minor `orgstruct-mode'.")
6449 (defvar org-local-vars nil
6450 "List of local variables, for use by `orgstruct-mode'")
6452 ;;;###autoload
6453 (define-minor-mode orgstruct-mode
6454 "Toggle the minor more `orgstruct-mode'.
6455 This mode is for using Org-mode structure commands in other modes.
6456 The following key behave as if Org-mode was active, if the cursor
6457 is on a headline, or on a plain list item (both in the definition
6458 of Org-mode).
6460 M-up Move entry/item up
6461 M-down Move entry/item down
6462 M-left Promote
6463 M-right Demote
6464 M-S-up Move entry/item up
6465 M-S-down Move entry/item down
6466 M-S-left Promote subtree
6467 M-S-right Demote subtree
6468 M-q Fill paragraph and items like in Org-mode
6469 C-c ^ Sort entries
6470 C-c - Cycle list bullet
6471 TAB Cycle item visibility
6472 M-RET Insert new heading/item
6473 S-M-RET Insert new TODO heading / Checkbox item
6474 C-c C-c Set tags / toggle checkbox"
6475 nil " OrgStruct" nil
6476 (org-load-modules-maybe)
6477 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6479 ;;;###autoload
6480 (defun turn-on-orgstruct ()
6481 "Unconditionally turn on `orgstruct-mode'."
6482 (orgstruct-mode 1))
6484 (defun orgstruct++-mode (&optional arg)
6485 "Toggle `orgstruct-mode', the enhanced version of it.
6486 In addition to setting orgstruct-mode, this also exports all indentation and
6487 autofilling variables from org-mode into the buffer. It will also
6488 recognize item context in multiline items.
6489 Note that turning off orgstruct-mode will *not* remove the
6490 indentation/paragraph settings. This can only be done by refreshing the
6491 major mode, for example with \[normal-mode]."
6492 (interactive "P")
6493 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6494 (if (< arg 1)
6495 (orgstruct-mode -1)
6496 (orgstruct-mode 1)
6497 (let (var val)
6498 (mapc
6499 (lambda (x)
6500 (when (string-match
6501 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6502 (symbol-name (car x)))
6503 (setq var (car x) val (nth 1 x))
6504 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6505 org-local-vars)
6506 (org-set-local 'orgstruct-is-++ t))))
6508 (defvar orgstruct-is-++ nil
6509 "Is orgstruct-mode in ++ version in the current-buffer?")
6510 (make-variable-buffer-local 'orgstruct-is-++)
6512 ;;;###autoload
6513 (defun turn-on-orgstruct++ ()
6514 "Unconditionally turn on `orgstruct++-mode'."
6515 (orgstruct++-mode 1))
6517 (defun orgstruct-error ()
6518 "Error when there is no default binding for a structure key."
6519 (interactive)
6520 (error "This key has no function outside structure elements"))
6522 (defun orgstruct-setup ()
6523 "Setup orgstruct keymaps."
6524 (let ((nfunc 0)
6525 (bindings
6526 (list
6527 '([(meta up)] org-metaup)
6528 '([(meta down)] org-metadown)
6529 '([(meta left)] org-metaleft)
6530 '([(meta right)] org-metaright)
6531 '([(meta shift up)] org-shiftmetaup)
6532 '([(meta shift down)] org-shiftmetadown)
6533 '([(meta shift left)] org-shiftmetaleft)
6534 '([(meta shift right)] org-shiftmetaright)
6535 '([(shift up)] org-shiftup)
6536 '([(shift down)] org-shiftdown)
6537 '([(shift left)] org-shiftleft)
6538 '([(shift right)] org-shiftright)
6539 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6540 '("\M-q" fill-paragraph)
6541 '("\C-c^" org-sort)
6542 '("\C-c-" org-cycle-list-bullet)))
6543 elt key fun cmd)
6544 (while (setq elt (pop bindings))
6545 (setq nfunc (1+ nfunc))
6546 (setq key (org-key (car elt))
6547 fun (nth 1 elt)
6548 cmd (orgstruct-make-binding fun nfunc key))
6549 (org-defkey orgstruct-mode-map key cmd))
6551 ;; Special treatment needed for TAB and RET
6552 (org-defkey orgstruct-mode-map [(tab)]
6553 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6554 (org-defkey orgstruct-mode-map "\C-i"
6555 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6557 (org-defkey orgstruct-mode-map "\M-\C-m"
6558 (orgstruct-make-binding 'org-insert-heading 105
6559 "\M-\C-m" [(meta return)]))
6560 (org-defkey orgstruct-mode-map [(meta return)]
6561 (orgstruct-make-binding 'org-insert-heading 106
6562 [(meta return)] "\M-\C-m"))
6564 (org-defkey orgstruct-mode-map [(shift meta return)]
6565 (orgstruct-make-binding 'org-insert-todo-heading 107
6566 [(meta return)] "\M-\C-m"))
6568 (unless org-local-vars
6569 (setq org-local-vars (org-get-local-variables)))
6573 (defun orgstruct-make-binding (fun n &rest keys)
6574 "Create a function for binding in the structure minor mode.
6575 FUN is the command to call inside a table. N is used to create a unique
6576 command name. KEYS are keys that should be checked in for a command
6577 to execute outside of tables."
6578 (eval
6579 (list 'defun
6580 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6581 '(arg)
6582 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6583 "Outside of structure, run the binding of `"
6584 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6585 "'.")
6586 '(interactive "p")
6587 (list 'if
6588 `(org-context-p 'headline 'item
6589 (and orgstruct-is-++
6590 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6591 'item-body))
6592 (list 'org-run-like-in-org-mode (list 'quote fun))
6593 (list 'let '(orgstruct-mode)
6594 (list 'call-interactively
6595 (append '(or)
6596 (mapcar (lambda (k)
6597 (list 'key-binding k))
6598 keys)
6599 '('orgstruct-error))))))))
6601 (defun org-context-p (&rest contexts)
6602 "Check if local context is any of CONTEXTS.
6603 Possible values in the list of contexts are `table', `headline', and `item'."
6604 (let ((pos (point)))
6605 (goto-char (point-at-bol))
6606 (prog1 (or (and (memq 'table contexts)
6607 (looking-at "[ \t]*|"))
6608 (and (memq 'headline contexts)
6609 ;;????????? (looking-at "\\*+"))
6610 (looking-at outline-regexp))
6611 (and (memq 'item contexts)
6612 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6613 (and (memq 'item-body contexts)
6614 (org-in-item-p)))
6615 (goto-char pos))))
6617 (defun org-get-local-variables ()
6618 "Return a list of all local variables in an org-mode buffer."
6619 (let (varlist)
6620 (with-current-buffer (get-buffer-create "*Org tmp*")
6621 (erase-buffer)
6622 (org-mode)
6623 (setq varlist (buffer-local-variables)))
6624 (kill-buffer "*Org tmp*")
6625 (delq nil
6626 (mapcar
6627 (lambda (x)
6628 (setq x
6629 (if (symbolp x)
6630 (list x)
6631 (list (car x) (list 'quote (cdr x)))))
6632 (if (string-match
6633 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6634 (symbol-name (car x)))
6635 x nil))
6636 varlist))))
6638 ;;;###autoload
6639 (defun org-run-like-in-org-mode (cmd)
6640 "Run a command, pretending that the current buffer is in Org-mode.
6641 This will temporarily bind local variables that are typically bound in
6642 Org-mode to the values they have in Org-mode, and then interactively
6643 call CMD."
6644 (org-load-modules-maybe)
6645 (unless org-local-vars
6646 (setq org-local-vars (org-get-local-variables)))
6647 (eval (list 'let org-local-vars
6648 (list 'call-interactively (list 'quote cmd)))))
6650 ;;;; Archiving
6652 (defun org-get-category (&optional pos)
6653 "Get the category applying to position POS."
6654 (get-text-property (or pos (point)) 'org-category))
6656 (defun org-refresh-category-properties ()
6657 "Refresh category text properties in the buffer."
6658 (let ((def-cat (cond
6659 ((null org-category)
6660 (if buffer-file-name
6661 (file-name-sans-extension
6662 (file-name-nondirectory buffer-file-name))
6663 "???"))
6664 ((symbolp org-category) (symbol-name org-category))
6665 (t org-category)))
6666 beg end cat pos optionp)
6667 (org-unmodified
6668 (save-excursion
6669 (save-restriction
6670 (widen)
6671 (goto-char (point-min))
6672 (put-text-property (point) (point-max) 'org-category def-cat)
6673 (while (re-search-forward
6674 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6675 (setq pos (match-end 0)
6676 optionp (equal (char-after (match-beginning 0)) ?#)
6677 cat (org-trim (match-string 2)))
6678 (if optionp
6679 (setq beg (point-at-bol) end (point-max))
6680 (org-back-to-heading t)
6681 (setq beg (point) end (org-end-of-subtree t t)))
6682 (put-text-property beg end 'org-category cat)
6683 (goto-char pos)))))))
6686 ;;;; Link Stuff
6688 ;;; Link abbreviations
6690 (defun org-link-expand-abbrev (link)
6691 "Apply replacements as defined in `org-link-abbrev-alist."
6692 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6693 (let* ((key (match-string 1 link))
6694 (as (or (assoc key org-link-abbrev-alist-local)
6695 (assoc key org-link-abbrev-alist)))
6696 (tag (and (match-end 2) (match-string 3 link)))
6697 rpl)
6698 (if (not as)
6699 link
6700 (setq rpl (cdr as))
6701 (cond
6702 ((symbolp rpl) (funcall rpl tag))
6703 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6704 ((string-match "%h" rpl)
6705 (replace-match (url-hexify-string (or tag "")) t t rpl))
6706 (t (concat rpl tag)))))
6707 link))
6709 ;;; Storing and inserting links
6711 (defvar org-insert-link-history nil
6712 "Minibuffer history for links inserted with `org-insert-link'.")
6714 (defvar org-stored-links nil
6715 "Contains the links stored with `org-store-link'.")
6717 (defvar org-store-link-plist nil
6718 "Plist with info about the most recently link created with `org-store-link'.")
6720 (defvar org-link-protocols nil
6721 "Link protocols added to Org-mode using `org-add-link-type'.")
6723 (defvar org-store-link-functions nil
6724 "List of functions that are called to create and store a link.
6725 Each function will be called in turn until one returns a non-nil
6726 value. Each function should check if it is responsible for creating
6727 this link (for example by looking at the major mode).
6728 If not, it must exit and return nil.
6729 If yes, it should return a non-nil value after a calling
6730 `org-store-link-props' with a list of properties and values.
6731 Special properties are:
6733 :type The link prefix. like \"http\". This must be given.
6734 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6735 This is obligatory as well.
6736 :description Optional default description for the second pair
6737 of brackets in an Org-mode link. The user can still change
6738 this when inserting this link into an Org-mode buffer.
6740 In addition to these, any additional properties can be specified
6741 and then used in remember templates.")
6743 (defun org-add-link-type (type &optional follow export)
6744 "Add TYPE to the list of `org-link-types'.
6745 Re-compute all regular expressions depending on `org-link-types'
6747 FOLLOW and EXPORT are two functions.
6749 FOLLOW should take the link path as the single argument and do whatever
6750 is necessary to follow the link, for example find a file or display
6751 a mail message.
6753 EXPORT should format the link path for export to one of the export formats.
6754 It should be a function accepting three arguments:
6756 path the path of the link, the text after the prefix (like \"http:\")
6757 desc the description of the link, if any, nil if there was no description
6758 format the export format, a symbol like `html' or `latex'.
6760 The function may use the FORMAT information to return different values
6761 depending on the format. The return value will be put literally into
6762 the exported file.
6763 Org-mode has a built-in default for exporting links. If you are happy with
6764 this default, there is no need to define an export function for the link
6765 type. For a simple example of an export function, see `org-bbdb.el'."
6766 (add-to-list 'org-link-types type t)
6767 (org-make-link-regexps)
6768 (if (assoc type org-link-protocols)
6769 (setcdr (assoc type org-link-protocols) (list follow export))
6770 (push (list type follow export) org-link-protocols)))
6772 ;;;###autoload
6773 (defun org-store-link (arg)
6774 "\\<org-mode-map>Store an org-link to the current location.
6775 This link is added to `org-stored-links' and can later be inserted
6776 into an org-buffer with \\[org-insert-link].
6778 For some link types, a prefix arg is interpreted:
6779 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6780 For file links, arg negates `org-context-in-file-links'."
6781 (interactive "P")
6782 (org-load-modules-maybe)
6783 (setq org-store-link-plist nil) ; reset
6784 (let (link cpltxt desc description search txt)
6785 (cond
6787 ((run-hook-with-args-until-success 'org-store-link-functions)
6788 (setq link (plist-get org-store-link-plist :link)
6789 desc (or (plist-get org-store-link-plist :description) link)))
6791 ((equal (buffer-name) "*Org Edit Src Example*")
6792 (let (label gc)
6793 (while (or (not label)
6794 (save-excursion
6795 (save-restriction
6796 (widen)
6797 (goto-char (point-min))
6798 (re-search-forward
6799 (regexp-quote (format org-coderef-label-format label))
6800 nil t))))
6801 (when label (message "Label exists already") (sit-for 2))
6802 (setq label (read-string "Code line label: " label)))
6803 (end-of-line 1)
6804 (setq link (format org-coderef-label-format label))
6805 (setq gc (- 79 (length link)))
6806 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6807 (insert link)
6808 (setq link (concat "(" label ")") desc nil)))
6810 ((eq major-mode 'calendar-mode)
6811 (let ((cd (calendar-cursor-to-date)))
6812 (setq link
6813 (format-time-string
6814 (car org-time-stamp-formats)
6815 (apply 'encode-time
6816 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6817 nil nil nil))))
6818 (org-store-link-props :type "calendar" :date cd)))
6820 ((eq major-mode 'w3-mode)
6821 (setq cpltxt (if (and (buffer-name)
6822 (not (string-match "Untitled" (buffer-name))))
6823 (buffer-name)
6824 (url-view-url t))
6825 link (org-make-link (url-view-url t)))
6826 (org-store-link-props :type "w3" :url (url-view-url t)))
6828 ((eq major-mode 'w3m-mode)
6829 (setq cpltxt (or w3m-current-title w3m-current-url)
6830 link (org-make-link w3m-current-url))
6831 (org-store-link-props :type "w3m" :url (url-view-url t)))
6833 ((setq search (run-hook-with-args-until-success
6834 'org-create-file-search-functions))
6835 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6836 "::" search))
6837 (setq cpltxt (or description link)))
6839 ((eq major-mode 'image-mode)
6840 (setq cpltxt (concat "file:"
6841 (abbreviate-file-name buffer-file-name))
6842 link (org-make-link cpltxt))
6843 (org-store-link-props :type "image" :file buffer-file-name))
6845 ((eq major-mode 'dired-mode)
6846 ;; link to the file in the current line
6847 (setq cpltxt (concat "file:"
6848 (abbreviate-file-name
6849 (expand-file-name
6850 (dired-get-filename nil t))))
6851 link (org-make-link cpltxt)))
6853 ((and buffer-file-name (org-mode-p))
6854 (cond
6855 ((org-in-regexp "<<\\(.*?\\)>>")
6856 (setq cpltxt
6857 (concat "file:"
6858 (abbreviate-file-name buffer-file-name)
6859 "::" (match-string 1))
6860 link (org-make-link cpltxt)))
6861 ((and (featurep 'org-id)
6862 (or (eq org-link-to-org-use-id t)
6863 (and (eq org-link-to-org-use-id 'create-if-interactive)
6864 (interactive-p))
6865 (and org-link-to-org-use-id
6866 (condition-case nil
6867 (org-entry-get nil "ID")
6868 (error nil)))))
6869 ;; We can make a link using the ID.
6870 (setq link (condition-case nil
6871 (prog1 (org-id-store-link)
6872 (setq desc (plist-get org-store-link-plist
6873 :description)))
6874 (error
6875 ;; probably before first headline, link to file only
6876 (concat "file:"
6877 (abbreviate-file-name buffer-file-name))))))
6879 ;; Just link to current headline
6880 (setq cpltxt (concat "file:"
6881 (abbreviate-file-name buffer-file-name)))
6882 ;; Add a context search string
6883 (when (org-xor org-context-in-file-links arg)
6884 (setq txt (cond
6885 ((org-on-heading-p) nil)
6886 ((org-region-active-p)
6887 (buffer-substring (region-beginning) (region-end)))
6888 (t nil)))
6889 (when (or (null txt) (string-match "\\S-" txt))
6890 (setq cpltxt
6891 (concat cpltxt "::"
6892 (condition-case nil
6893 (org-make-org-heading-search-string txt)
6894 (error "")))
6895 desc "NONE")))
6896 (if (string-match "::\\'" cpltxt)
6897 (setq cpltxt (substring cpltxt 0 -2)))
6898 (setq link (org-make-link cpltxt)))))
6900 ((buffer-file-name (buffer-base-buffer))
6901 ;; Just link to this file here.
6902 (setq cpltxt (concat "file:"
6903 (abbreviate-file-name
6904 (buffer-file-name (buffer-base-buffer)))))
6905 ;; Add a context string
6906 (when (org-xor org-context-in-file-links arg)
6907 (setq txt (if (org-region-active-p)
6908 (buffer-substring (region-beginning) (region-end))
6909 (buffer-substring (point-at-bol) (point-at-eol))))
6910 ;; Only use search option if there is some text.
6911 (when (string-match "\\S-" txt)
6912 (setq cpltxt
6913 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6914 desc "NONE")))
6915 (setq link (org-make-link cpltxt)))
6917 ((interactive-p)
6918 (error "Cannot link to a buffer which is not visiting a file"))
6920 (t (setq link nil)))
6922 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6923 (setq link (or link cpltxt)
6924 desc (or desc cpltxt))
6925 (if (equal desc "NONE") (setq desc nil))
6927 (if (and (interactive-p) link)
6928 (progn
6929 (setq org-stored-links
6930 (cons (list link desc) org-stored-links))
6931 (message "Stored: %s" (or desc link)))
6932 (and link (org-make-link-string link desc)))))
6934 (defun org-store-link-props (&rest plist)
6935 "Store link properties, extract names and addresses."
6936 (let (x adr)
6937 (when (setq x (plist-get plist :from))
6938 (setq adr (mail-extract-address-components x))
6939 (setq plist (plist-put plist :fromname (car adr)))
6940 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6941 (when (setq x (plist-get plist :to))
6942 (setq adr (mail-extract-address-components x))
6943 (setq plist (plist-put plist :toname (car adr)))
6944 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6945 (let ((from (plist-get plist :from))
6946 (to (plist-get plist :to)))
6947 (when (and from to org-from-is-user-regexp)
6948 (setq plist
6949 (plist-put plist :fromto
6950 (if (string-match org-from-is-user-regexp from)
6951 (concat "to %t")
6952 (concat "from %f"))))))
6953 (setq org-store-link-plist plist))
6955 (defun org-add-link-props (&rest plist)
6956 "Add these properties to the link property list."
6957 (let (key value)
6958 (while plist
6959 (setq key (pop plist) value (pop plist))
6960 (setq org-store-link-plist
6961 (plist-put org-store-link-plist key value)))))
6963 (defun org-email-link-description (&optional fmt)
6964 "Return the description part of an email link.
6965 This takes information from `org-store-link-plist' and formats it
6966 according to FMT (default from `org-email-link-description-format')."
6967 (setq fmt (or fmt org-email-link-description-format))
6968 (let* ((p org-store-link-plist)
6969 (to (plist-get p :toaddress))
6970 (from (plist-get p :fromaddress))
6971 (table
6972 (list
6973 (cons "%c" (plist-get p :fromto))
6974 (cons "%F" (plist-get p :from))
6975 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6976 (cons "%T" (plist-get p :to))
6977 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6978 (cons "%s" (plist-get p :subject))
6979 (cons "%m" (plist-get p :message-id)))))
6980 (when (string-match "%c" fmt)
6981 ;; Check if the user wrote this message
6982 (if (and org-from-is-user-regexp from to
6983 (save-match-data (string-match org-from-is-user-regexp from)))
6984 (setq fmt (replace-match "to %t" t t fmt))
6985 (setq fmt (replace-match "from %f" t t fmt))))
6986 (org-replace-escapes fmt table)))
6988 (defun org-make-org-heading-search-string (&optional string heading)
6989 "Make search string for STRING or current headline."
6990 (interactive)
6991 (let ((s (or string (org-get-heading))))
6992 (unless (and string (not heading))
6993 ;; We are using a headline, clean up garbage in there.
6994 (if (string-match org-todo-regexp s)
6995 (setq s (replace-match "" t t s)))
6996 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6997 (setq s (replace-match "" t t s)))
6998 (setq s (org-trim s))
6999 (if (string-match (concat "^\\(" org-quote-string "\\|"
7000 org-comment-string "\\)") s)
7001 (setq s (replace-match "" t t s)))
7002 (while (string-match org-ts-regexp s)
7003 (setq s (replace-match "" t t s))))
7004 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7005 (setq s (replace-match " " t t s)))
7006 (or string (setq s (concat "*" s))) ; Add * for headlines
7007 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7009 (defun org-make-link (&rest strings)
7010 "Concatenate STRINGS."
7011 (apply 'concat strings))
7013 (defun org-make-link-string (link &optional description)
7014 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7015 (unless (string-match "\\S-" link)
7016 (error "Empty link"))
7017 (when (stringp description)
7018 ;; Remove brackets from the description, they are fatal.
7019 (while (string-match "\\[" description)
7020 (setq description (replace-match "{" t t description)))
7021 (while (string-match "\\]" description)
7022 (setq description (replace-match "}" t t description))))
7023 (when (equal (org-link-escape link) description)
7024 ;; No description needed, it is identical
7025 (setq description nil))
7026 (when (and (not description)
7027 (not (equal link (org-link-escape link))))
7028 (setq description (org-extract-attributes link)))
7029 (concat "[[" (org-link-escape link) "]"
7030 (if description (concat "[" description "]") "")
7031 "]"))
7033 (defconst org-link-escape-chars
7034 '((?\ . "%20")
7035 (?\[ . "%5B")
7036 (?\] . "%5D")
7037 (?\340 . "%E0") ; `a
7038 (?\342 . "%E2") ; ^a
7039 (?\347 . "%E7") ; ,c
7040 (?\350 . "%E8") ; `e
7041 (?\351 . "%E9") ; 'e
7042 (?\352 . "%EA") ; ^e
7043 (?\356 . "%EE") ; ^i
7044 (?\364 . "%F4") ; ^o
7045 (?\371 . "%F9") ; `u
7046 (?\373 . "%FB") ; ^u
7047 (?\; . "%3B")
7048 (?? . "%3F")
7049 (?= . "%3D")
7050 (?+ . "%2B")
7052 "Association list of escapes for some characters problematic in links.
7053 This is the list that is used for internal purposes.")
7055 (defconst org-link-escape-chars-browser
7056 '((?\ . "%20")) ; 32 for the SPC char
7057 "Association list of escapes for some characters problematic in links.
7058 This is the list that is used before handing over to the browser.")
7060 (defun org-link-escape (text &optional table)
7061 "Escape characters in TEXT that are problematic for links."
7062 (setq table (or table org-link-escape-chars))
7063 (when text
7064 (let ((re (mapconcat (lambda (x) (regexp-quote
7065 (char-to-string (car x))))
7066 table "\\|")))
7067 (while (string-match re text)
7068 (setq text
7069 (replace-match
7070 (cdr (assoc (string-to-char (match-string 0 text))
7071 table))
7072 t t text)))
7073 text)))
7075 (defun org-link-unescape (text &optional table)
7076 "Reverse the action of `org-link-escape'."
7077 (setq table (or table org-link-escape-chars))
7078 (when text
7079 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7080 table "\\|")))
7081 (while (string-match re text)
7082 (setq text
7083 (replace-match
7084 (char-to-string (car (rassoc (match-string 0 text) table)))
7085 t t text)))
7086 text)))
7088 (defun org-xor (a b)
7089 "Exclusive or."
7090 (if a (not b) b))
7092 (defun org-fixup-message-id-for-http (s)
7093 "Replace special characters in a message id, so it can be used in an http query."
7094 (while (string-match "<" s)
7095 (setq s (replace-match "%3C" t t s)))
7096 (while (string-match ">" s)
7097 (setq s (replace-match "%3E" t t s)))
7098 (while (string-match "@" s)
7099 (setq s (replace-match "%40" t t s)))
7102 ;;;###autoload
7103 (defun org-insert-link-global ()
7104 "Insert a link like Org-mode does.
7105 This command can be called in any mode to insert a link in Org-mode syntax."
7106 (interactive)
7107 (org-load-modules-maybe)
7108 (org-run-like-in-org-mode 'org-insert-link))
7110 (defun org-insert-link (&optional complete-file link-location)
7111 "Insert a link. At the prompt, enter the link.
7113 Completion can be used to insert any of the link protocol prefixes like
7114 http or ftp in use.
7116 The history can be used to select a link previously stored with
7117 `org-store-link'. When the empty string is entered (i.e. if you just
7118 press RET at the prompt), the link defaults to the most recently
7119 stored link. As SPC triggers completion in the minibuffer, you need to
7120 use M-SPC or C-q SPC to force the insertion of a space character.
7122 You will also be prompted for a description, and if one is given, it will
7123 be displayed in the buffer instead of the link.
7125 If there is already a link at point, this command will allow you to edit link
7126 and description parts.
7128 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7129 be selected using completion. The path to the file will be relative to the
7130 current directory if the file is in the current directory or a subdirectory.
7131 Otherwise, the link will be the absolute path as completed in the minibuffer
7132 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7133 option `org-link-file-path-type'.
7135 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7136 the current directory or below.
7138 With three \\[universal-argument] prefixes, negate the meaning of
7139 `org-keep-stored-link-after-insertion'.
7141 If `org-make-link-description-function' is non-nil, this function will be
7142 called with the link target, and the result will be the default
7143 link description.
7145 If the LINK-LOCATION parameter is non-nil, this value will be
7146 used as the link location instead of reading one interactively."
7147 (interactive "P")
7148 (let* ((wcf (current-window-configuration))
7149 (region (if (org-region-active-p)
7150 (buffer-substring (region-beginning) (region-end))))
7151 (remove (and region (list (region-beginning) (region-end))))
7152 (desc region)
7153 tmphist ; byte-compile incorrectly complains about this
7154 (link link-location)
7155 entry file)
7156 (cond
7157 (link-location) ; specified by arg, just use it.
7158 ((org-in-regexp org-bracket-link-regexp 1)
7159 ;; We do have a link at point, and we are going to edit it.
7160 (setq remove (list (match-beginning 0) (match-end 0)))
7161 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7162 (setq link (read-string "Link: "
7163 (org-link-unescape
7164 (org-match-string-no-properties 1)))))
7165 ((or (org-in-regexp org-angle-link-re)
7166 (org-in-regexp org-plain-link-re))
7167 ;; Convert to bracket link
7168 (setq remove (list (match-beginning 0) (match-end 0))
7169 link (read-string "Link: "
7170 (org-remove-angle-brackets (match-string 0)))))
7171 ((member complete-file '((4) (16)))
7172 ;; Completing read for file names.
7173 (setq file (read-file-name "File: "))
7174 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7175 (pwd1 (file-name-as-directory (abbreviate-file-name
7176 (expand-file-name ".")))))
7177 (cond
7178 ((equal complete-file '(16))
7179 (setq link (org-make-link
7180 "file:"
7181 (abbreviate-file-name (expand-file-name file)))))
7182 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7183 (setq link (org-make-link "file:" (match-string 1 file))))
7184 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7185 (expand-file-name file))
7186 (setq link (org-make-link
7187 "file:" (match-string 1 (expand-file-name file)))))
7188 (t (setq link (org-make-link "file:" file))))))
7190 ;; Read link, with completion for stored links.
7191 (with-output-to-temp-buffer "*Org Links*"
7192 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7193 (when org-stored-links
7194 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7195 (princ (mapconcat
7196 (lambda (x)
7197 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7198 (reverse org-stored-links) "\n"))))
7199 (let ((cw (selected-window)))
7200 (select-window (get-buffer-window "*Org Links*"))
7201 (setq truncate-lines t)
7202 (org-fit-window-to-buffer)
7203 (select-window cw))
7204 ;; Fake a link history, containing the stored links.
7205 (setq tmphist (append (mapcar 'car org-stored-links)
7206 org-insert-link-history))
7207 (unwind-protect
7208 (setq link
7209 (let ((org-completion-use-ido nil))
7210 (org-completing-read
7211 "Link: "
7212 (append
7213 (mapcar (lambda (x) (list (concat (car x) ":")))
7214 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7215 (mapcar (lambda (x) (list (concat x ":")))
7216 org-link-types))
7217 nil nil nil
7218 'tmphist
7219 (or (car (car org-stored-links))))))
7220 (set-window-configuration wcf)
7221 (kill-buffer "*Org Links*"))
7222 (setq entry (assoc link org-stored-links))
7223 (or entry (push link org-insert-link-history))
7224 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7225 (not org-keep-stored-link-after-insertion))
7226 (setq org-stored-links (delq (assoc link org-stored-links)
7227 org-stored-links)))
7228 (setq desc (or desc (nth 1 entry)))))
7230 (if (string-match org-plain-link-re link)
7231 ;; URL-like link, normalize the use of angular brackets.
7232 (setq link (org-make-link (org-remove-angle-brackets link))))
7234 ;; Check if we are linking to the current file with a search option
7235 ;; If yes, simplify the link by using only the search option.
7236 (when (and buffer-file-name
7237 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7238 (let* ((path (match-string 1 link))
7239 (case-fold-search nil)
7240 (search (match-string 2 link)))
7241 (save-match-data
7242 (if (equal (file-truename buffer-file-name) (file-truename path))
7243 ;; We are linking to this same file, with a search option
7244 (setq link search)))))
7246 ;; Check if we can/should use a relative path. If yes, simplify the link
7247 (when (string-match "^file:\\(.*\\)" link)
7248 (let* ((path (match-string 1 link))
7249 (origpath path)
7250 (case-fold-search nil))
7251 (cond
7252 ((or (eq org-link-file-path-type 'absolute)
7253 (equal complete-file '(16)))
7254 (setq path (abbreviate-file-name (expand-file-name path))))
7255 ((eq org-link-file-path-type 'noabbrev)
7256 (setq path (expand-file-name path)))
7257 ((eq org-link-file-path-type 'relative)
7258 (setq path (file-relative-name path)))
7260 (save-match-data
7261 (if (string-match (concat "^" (regexp-quote
7262 (file-name-as-directory
7263 (expand-file-name "."))))
7264 (expand-file-name path))
7265 ;; We are linking a file with relative path name.
7266 (setq path (substring (expand-file-name path)
7267 (match-end 0)))
7268 (setq path (abbreviate-file-name (expand-file-name path)))))))
7269 (setq link (concat "file:" path))
7270 (if (equal desc origpath)
7271 (setq desc path))))
7273 (if org-make-link-description-function
7274 (setq desc (funcall org-make-link-description-function link desc)))
7276 (setq desc (read-string "Description: " desc))
7277 (unless (string-match "\\S-" desc) (setq desc nil))
7278 (if remove (apply 'delete-region remove))
7279 (insert (org-make-link-string link desc))))
7281 (defun org-completing-read (&rest args)
7282 "Completing-read with SPACE being a normal character."
7283 (let ((minibuffer-local-completion-map
7284 (copy-keymap minibuffer-local-completion-map)))
7285 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7286 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7287 (apply 'org-ido-completing-read args)))
7289 (defun org-completing-read-no-ido (&rest args)
7290 (let (org-completion-use-ido)
7291 (apply 'org-completing-read args)))
7293 (defun org-ido-completing-read (&rest args)
7294 "Completing-read using `ido-mode' speedups if available"
7295 (if (and org-completion-use-ido
7296 (fboundp 'ido-completing-read)
7297 (boundp 'ido-mode) ido-mode
7298 (listp (second args)))
7299 (let ((ido-enter-matching-directory nil))
7300 (apply 'ido-completing-read (concat (car args))
7301 (mapcar (lambda (x) (car x)) (nth 1 args))
7302 (cddr args)))
7303 (apply 'completing-read args)))
7305 (defun org-extract-attributes (s)
7306 "Extract the attributes cookie from a string and set as text property."
7307 (let (a attr (start 0) key value)
7308 (save-match-data
7309 (when (string-match "{{\\([^}]+\\)}}$" s)
7310 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7311 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7312 (setq key (match-string 1 a) value (match-string 2 a)
7313 start (match-end 0)
7314 attr (plist-put attr (intern key) value))))
7315 (org-add-props s nil 'org-attr attr))
7318 (defun org-extract-attributes-from-string (tag)
7319 (let (key value attr)
7320 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7321 (setq key (match-string 1 tag) value (match-string 2 tag)
7322 tag (replace-match "" t t tag)
7323 attr (plist-put attr (intern key) value)))
7324 (cons tag attr)))
7326 (defun org-attributes-to-string (plist)
7327 "Format a property list into an HTML attribute list."
7328 (let ((s "") key value)
7329 (while plist
7330 (setq key (pop plist) value (pop plist))
7331 (and value
7332 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7335 ;;; Opening/following a link
7337 (defvar org-link-search-failed nil)
7339 (defun org-next-link ()
7340 "Move forward to the next link.
7341 If the link is in hidden text, expose it."
7342 (interactive)
7343 (when (and org-link-search-failed (eq this-command last-command))
7344 (goto-char (point-min))
7345 (message "Link search wrapped back to beginning of buffer"))
7346 (setq org-link-search-failed nil)
7347 (let* ((pos (point))
7348 (ct (org-context))
7349 (a (assoc :link ct)))
7350 (if a (goto-char (nth 2 a)))
7351 (if (re-search-forward org-any-link-re nil t)
7352 (progn
7353 (goto-char (match-beginning 0))
7354 (if (org-invisible-p) (org-show-context)))
7355 (goto-char pos)
7356 (setq org-link-search-failed t)
7357 (error "No further link found"))))
7359 (defun org-previous-link ()
7360 "Move backward to the previous link.
7361 If the link is in hidden text, expose it."
7362 (interactive)
7363 (when (and org-link-search-failed (eq this-command last-command))
7364 (goto-char (point-max))
7365 (message "Link search wrapped back to end of buffer"))
7366 (setq org-link-search-failed nil)
7367 (let* ((pos (point))
7368 (ct (org-context))
7369 (a (assoc :link ct)))
7370 (if a (goto-char (nth 1 a)))
7371 (if (re-search-backward org-any-link-re nil t)
7372 (progn
7373 (goto-char (match-beginning 0))
7374 (if (org-invisible-p) (org-show-context)))
7375 (goto-char pos)
7376 (setq org-link-search-failed t)
7377 (error "No further link found"))))
7379 (defun org-translate-link (s)
7380 "Translate a link string if a translation function has been defined."
7381 (if (and org-link-translation-function
7382 (fboundp org-link-translation-function)
7383 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7384 (progn
7385 (setq s (funcall org-link-translation-function
7386 (match-string 1) (match-string 2)))
7387 (concat (car s) ":" (cdr s)))
7390 (defun org-translate-link-from-planner (type path)
7391 "Translate a link from Emacs Planner syntax so that Org can follow it.
7392 This is still an experimental function, your mileage may vary."
7393 (cond
7394 ((member type '("http" "https" "news" "ftp"))
7395 ;; standard Internet links are the same.
7396 nil)
7397 ((and (equal type "irc") (string-match "^//" path))
7398 ;; Planner has two / at the beginning of an irc link, we have 1.
7399 ;; We should have zero, actually....
7400 (setq path (substring path 1)))
7401 ((and (equal type "lisp") (string-match "^/" path))
7402 ;; Planner has a slash, we do not.
7403 (setq type "elisp" path (substring path 1)))
7404 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7405 ;; A typical message link. Planner has the id after the fina slash,
7406 ;; we separate it with a hash mark
7407 (setq path (concat (match-string 1 path) "#"
7408 (org-remove-angle-brackets (match-string 2 path)))))
7410 (cons type path))
7412 (defun org-find-file-at-mouse (ev)
7413 "Open file link or URL at mouse."
7414 (interactive "e")
7415 (mouse-set-point ev)
7416 (org-open-at-point 'in-emacs))
7418 (defun org-open-at-mouse (ev)
7419 "Open file link or URL at mouse."
7420 (interactive "e")
7421 (mouse-set-point ev)
7422 (if (eq major-mode 'org-agenda-mode)
7423 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7424 (org-open-at-point))
7426 (defvar org-window-config-before-follow-link nil
7427 "The window configuration before following a link.
7428 This is saved in case the need arises to restore it.")
7430 (defvar org-open-link-marker (make-marker)
7431 "Marker pointing to the location where `org-open-at-point; was called.")
7433 ;;;###autoload
7434 (defun org-open-at-point-global ()
7435 "Follow a link like Org-mode does.
7436 This command can be called in any mode to follow a link that has
7437 Org-mode syntax."
7438 (interactive)
7439 (org-run-like-in-org-mode 'org-open-at-point))
7441 ;;;###autoload
7442 (defun org-open-link-from-string (s &optional arg)
7443 "Open a link in the string S, as if it was in Org-mode."
7444 (interactive "sLink: \nP")
7445 (with-temp-buffer
7446 (let ((org-inhibit-startup t))
7447 (org-mode)
7448 (insert s)
7449 (goto-char (point-min))
7450 (org-open-at-point arg))))
7452 (defun org-open-at-point (&optional in-emacs)
7453 "Open link at or after point.
7454 If there is no link at point, this function will search forward up to
7455 the end of the current subtree.
7456 Normally, files will be opened by an appropriate application. If the
7457 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7458 With a double prefix argument, try to open outside of Emacs, in the
7459 application the system uses for this file type."
7460 (interactive "P")
7461 (org-load-modules-maybe)
7462 (move-marker org-open-link-marker (point))
7463 (setq org-window-config-before-follow-link (current-window-configuration))
7464 (org-remove-occur-highlights nil nil t)
7465 (cond
7466 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7467 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7468 (org-footnote-action))
7470 (let (type path link line search (pos (point)))
7471 (catch 'match
7472 (save-excursion
7473 (skip-chars-forward "^]\n\r")
7474 (when (org-in-regexp org-bracket-link-regexp)
7475 (setq link (org-extract-attributes
7476 (org-link-unescape (org-match-string-no-properties 1))))
7477 (while (string-match " *\n *" link)
7478 (setq link (replace-match " " t t link)))
7479 (setq link (org-link-expand-abbrev link))
7480 (cond
7481 ((or (file-name-absolute-p link)
7482 (string-match "^\\.\\.?/" link))
7483 (setq type "file" path link))
7484 ((string-match org-link-re-with-space3 link)
7485 (setq type (match-string 1 link) path (match-string 2 link)))
7486 (t (setq type "thisfile" path link)))
7487 (throw 'match t)))
7489 (when (get-text-property (point) 'org-linked-text)
7490 (setq type "thisfile"
7491 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7492 (1+ (point)) (point))
7493 path (buffer-substring
7494 (previous-single-property-change pos 'org-linked-text)
7495 (next-single-property-change pos 'org-linked-text)))
7496 (throw 'match t))
7498 (save-excursion
7499 (when (or (org-in-regexp org-angle-link-re)
7500 (org-in-regexp org-plain-link-re))
7501 (setq type (match-string 1) path (match-string 2))
7502 (throw 'match t)))
7503 (save-excursion
7504 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7505 (setq type "tags"
7506 path (match-string 1))
7507 (while (string-match ":" path)
7508 (setq path (replace-match "+" t t path)))
7509 (throw 'match t)))
7510 (when (org-in-regexp "<\\([^><\n]+\\)>")
7511 (setq type "tree-match"
7512 path (match-string 1))
7513 (throw 'match t)))
7514 (unless path
7515 (error "No link found"))
7516 ;; Remove any trailing spaces in path
7517 (if (string-match " +\\'" path)
7518 (setq path (replace-match "" t t path)))
7519 (if (and org-link-translation-function
7520 (fboundp org-link-translation-function))
7521 ;; Check if we need to translate the link
7522 (let ((tmp (funcall org-link-translation-function type path)))
7523 (setq type (car tmp) path (cdr tmp))))
7525 (cond
7527 ((assoc type org-link-protocols)
7528 (funcall (nth 1 (assoc type org-link-protocols)) path))
7530 ((equal type "mailto")
7531 (let ((cmd (car org-link-mailto-program))
7532 (args (cdr org-link-mailto-program)) args1
7533 (address path) (subject "") a)
7534 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7535 (setq address (match-string 1 path)
7536 subject (org-link-escape (match-string 2 path))))
7537 (while args
7538 (cond
7539 ((not (stringp (car args))) (push (pop args) args1))
7540 (t (setq a (pop args))
7541 (if (string-match "%a" a)
7542 (setq a (replace-match address t t a)))
7543 (if (string-match "%s" a)
7544 (setq a (replace-match subject t t a)))
7545 (push a args1))))
7546 (apply cmd (nreverse args1))))
7548 ((member type '("http" "https" "ftp" "news"))
7549 (browse-url (concat type ":" (org-link-escape
7550 path org-link-escape-chars-browser))))
7552 ((member type '("message"))
7553 (browse-url (concat type ":" path)))
7555 ((string= type "tags")
7556 (org-tags-view in-emacs path))
7557 ((string= type "thisfile")
7558 (if in-emacs
7559 (switch-to-buffer-other-window
7560 (org-get-buffer-for-internal-link (current-buffer)))
7561 (org-mark-ring-push))
7562 (let ((cmd `(org-link-search
7563 ,path
7564 ,(cond ((equal in-emacs '(4)) 'occur)
7565 ((equal in-emacs '(16)) 'org-occur)
7566 (t nil))
7567 ,pos)))
7568 (condition-case nil (eval cmd)
7569 (error (progn (widen) (eval cmd))))))
7571 ((string= type "tree-match")
7572 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7574 ((string= type "file")
7575 (if (string-match "::\\([0-9]+\\)\\'" path)
7576 (setq line (string-to-number (match-string 1 path))
7577 path (substring path 0 (match-beginning 0)))
7578 (if (string-match "::\\(.+\\)\\'" path)
7579 (setq search (match-string 1 path)
7580 path (substring path 0 (match-beginning 0)))))
7581 (if (string-match "[*?{]" (file-name-nondirectory path))
7582 (dired path)
7583 (org-open-file path in-emacs line search)))
7585 ((string= type "news")
7586 (require 'org-gnus)
7587 (org-gnus-follow-link path))
7589 ((string= type "shell")
7590 (let ((cmd path))
7591 (if (or (not org-confirm-shell-link-function)
7592 (funcall org-confirm-shell-link-function
7593 (format "Execute \"%s\" in shell? "
7594 (org-add-props cmd nil
7595 'face 'org-warning))))
7596 (progn
7597 (message "Executing %s" cmd)
7598 (shell-command cmd))
7599 (error "Abort"))))
7601 ((string= type "elisp")
7602 (let ((cmd path))
7603 (if (or (not org-confirm-elisp-link-function)
7604 (funcall org-confirm-elisp-link-function
7605 (format "Execute \"%s\" as elisp? "
7606 (org-add-props cmd nil
7607 'face 'org-warning))))
7608 (message "%s => %s" cmd
7609 (if (equal (string-to-char cmd) ?\()
7610 (eval (read cmd))
7611 (call-interactively (read cmd))))
7612 (error "Abort"))))
7615 (browse-url-at-point))))))
7616 (move-marker org-open-link-marker nil)
7617 (run-hook-with-args 'org-follow-link-hook))
7619 ;;;; Time estimates
7621 (defun org-get-effort (&optional pom)
7622 "Get the effort estimate for the current entry."
7623 (org-entry-get pom org-effort-property))
7625 ;;; File search
7627 (defvar org-create-file-search-functions nil
7628 "List of functions to construct the right search string for a file link.
7629 These functions are called in turn with point at the location to
7630 which the link should point.
7632 A function in the hook should first test if it would like to
7633 handle this file type, for example by checking the major-mode or
7634 the file extension. If it decides not to handle this file, it
7635 should just return nil to give other functions a chance. If it
7636 does handle the file, it must return the search string to be used
7637 when following the link. The search string will be part of the
7638 file link, given after a double colon, and `org-open-at-point'
7639 will automatically search for it. If special measures must be
7640 taken to make the search successful, another function should be
7641 added to the companion hook `org-execute-file-search-functions',
7642 which see.
7644 A function in this hook may also use `setq' to set the variable
7645 `description' to provide a suggestion for the descriptive text to
7646 be used for this link when it gets inserted into an Org-mode
7647 buffer with \\[org-insert-link].")
7649 (defvar org-execute-file-search-functions nil
7650 "List of functions to execute a file search triggered by a link.
7652 Functions added to this hook must accept a single argument, the
7653 search string that was part of the file link, the part after the
7654 double colon. The function must first check if it would like to
7655 handle this search, for example by checking the major-mode or the
7656 file extension. If it decides not to handle this search, it
7657 should just return nil to give other functions a chance. If it
7658 does handle the search, it must return a non-nil value to keep
7659 other functions from trying.
7661 Each function can access the current prefix argument through the
7662 variable `current-prefix-argument'. Note that a single prefix is
7663 used to force opening a link in Emacs, so it may be good to only
7664 use a numeric or double prefix to guide the search function.
7666 In case this is needed, a function in this hook can also restore
7667 the window configuration before `org-open-at-point' was called using:
7669 (set-window-configuration org-window-config-before-follow-link)")
7671 (defun org-link-search (s &optional type avoid-pos)
7672 "Search for a link search option.
7673 If S is surrounded by forward slashes, it is interpreted as a
7674 regular expression. In org-mode files, this will create an `org-occur'
7675 sparse tree. In ordinary files, `occur' will be used to list matches.
7676 If the current buffer is in `dired-mode', grep will be used to search
7677 in all files. If AVOID-POS is given, ignore matches near that position."
7678 (let ((case-fold-search t)
7679 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7680 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7681 (append '(("") (" ") ("\t") ("\n"))
7682 org-emphasis-alist)
7683 "\\|") "\\)"))
7684 (pos (point))
7685 (pre nil) (post nil)
7686 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7687 (cond
7688 ;; First check if there are any special
7689 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7690 ;; Now try the builtin stuff
7691 ((save-excursion
7692 (goto-char (point-min))
7693 (and
7694 (re-search-forward
7695 (concat "<<" (regexp-quote s0) ">>") nil t)
7696 (setq type 'dedicated
7697 pos (match-beginning 0))))
7698 ;; There is an exact target for this
7699 (goto-char pos))
7700 ((and (string-match "^(\\(.*\\))$" s0)
7701 (save-excursion
7702 (goto-char (point-min))
7703 (and
7704 (re-search-forward
7705 (concat "[^[]" (regexp-quote
7706 (format org-coderef-label-format
7707 (match-string 1 s0))))
7708 nil t)
7709 (setq type 'dedicated
7710 pos (1+ (match-beginning 0))))))
7711 ;; There is a coderef target for this
7712 (goto-char pos))
7713 ((string-match "^/\\(.*\\)/$" s)
7714 ;; A regular expression
7715 (cond
7716 ((org-mode-p)
7717 (org-occur (match-string 1 s)))
7718 ;;((eq major-mode 'dired-mode)
7719 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7720 (t (org-do-occur (match-string 1 s)))))
7722 ;; A normal search strings
7723 (when (equal (string-to-char s) ?*)
7724 ;; Anchor on headlines, post may include tags.
7725 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7726 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7727 s (substring s 1)))
7728 (remove-text-properties
7729 0 (length s)
7730 '(face nil mouse-face nil keymap nil fontified nil) s)
7731 ;; Make a series of regular expressions to find a match
7732 (setq words (org-split-string s "[ \n\r\t]+")
7734 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7735 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7736 "\\)" markers)
7737 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7738 re2a (concat "[ \t\r\n]" re2a_)
7739 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7740 re4 (concat "[^a-zA-Z_]" re4_)
7742 re1 (concat pre re2 post)
7743 re3 (concat pre (if pre re4_ re4) post)
7744 re5 (concat pre ".*" re4)
7745 re2 (concat pre re2)
7746 re2a (concat pre (if pre re2a_ re2a))
7747 re4 (concat pre (if pre re4_ re4))
7748 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7749 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7750 re5 "\\)"
7752 (cond
7753 ((eq type 'org-occur) (org-occur reall))
7754 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7755 (t (goto-char (point-min))
7756 (setq type 'fuzzy)
7757 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7758 (org-search-not-self 1 re1 nil t)
7759 (org-search-not-self 1 re2 nil t)
7760 (org-search-not-self 1 re2a nil t)
7761 (org-search-not-self 1 re3 nil t)
7762 (org-search-not-self 1 re4 nil t)
7763 (org-search-not-self 1 re5 nil t)
7765 (goto-char (match-beginning 1))
7766 (goto-char pos)
7767 (error "No match")))))
7769 ;; Normal string-search
7770 (goto-char (point-min))
7771 (if (search-forward s nil t)
7772 (goto-char (match-beginning 0))
7773 (error "No match"))))
7774 (and (org-mode-p) (org-show-context 'link-search))
7775 type))
7777 (defun org-search-not-self (group &rest args)
7778 "Execute `re-search-forward', but only accept matches that do not
7779 enclose the position of `org-open-link-marker'."
7780 (let ((m org-open-link-marker))
7781 (catch 'exit
7782 (while (apply 're-search-forward args)
7783 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7784 (goto-char (match-end group))
7785 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7786 (> (match-beginning 0) (marker-position m))
7787 (< (match-end 0) (marker-position m)))
7788 (save-match-data
7789 (or (not (org-in-regexp
7790 org-bracket-link-analytic-regexp 1))
7791 (not (match-end 4)) ; no description
7792 (and (<= (match-beginning 4) (point))
7793 (>= (match-end 4) (point))))))
7794 (throw 'exit (point))))))))
7796 (defun org-get-buffer-for-internal-link (buffer)
7797 "Return a buffer to be used for displaying the link target of internal links."
7798 (cond
7799 ((not org-display-internal-link-with-indirect-buffer)
7800 buffer)
7801 ((string-match "(Clone)$" (buffer-name buffer))
7802 (message "Buffer is already a clone, not making another one")
7803 ;; we also do not modify visibility in this case
7804 buffer)
7805 (t ; make a new indirect buffer for displaying the link
7806 (let* ((bn (buffer-name buffer))
7807 (ibn (concat bn "(Clone)"))
7808 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7809 (with-current-buffer ib (org-overview))
7810 ib))))
7812 (defun org-do-occur (regexp &optional cleanup)
7813 "Call the Emacs command `occur'.
7814 If CLEANUP is non-nil, remove the printout of the regular expression
7815 in the *Occur* buffer. This is useful if the regex is long and not useful
7816 to read."
7817 (occur regexp)
7818 (when cleanup
7819 (let ((cwin (selected-window)) win beg end)
7820 (when (setq win (get-buffer-window "*Occur*"))
7821 (select-window win))
7822 (goto-char (point-min))
7823 (when (re-search-forward "match[a-z]+" nil t)
7824 (setq beg (match-end 0))
7825 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7826 (setq end (1- (match-beginning 0)))))
7827 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7828 (goto-char (point-min))
7829 (select-window cwin))))
7831 ;;; The mark ring for links jumps
7833 (defvar org-mark-ring nil
7834 "Mark ring for positions before jumps in Org-mode.")
7835 (defvar org-mark-ring-last-goto nil
7836 "Last position in the mark ring used to go back.")
7837 ;; Fill and close the ring
7838 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7839 (loop for i from 1 to org-mark-ring-length do
7840 (push (make-marker) org-mark-ring))
7841 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7842 org-mark-ring)
7844 (defun org-mark-ring-push (&optional pos buffer)
7845 "Put the current position or POS into the mark ring and rotate it."
7846 (interactive)
7847 (setq pos (or pos (point)))
7848 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7849 (move-marker (car org-mark-ring)
7850 (or pos (point))
7851 (or buffer (current-buffer)))
7852 (message "%s"
7853 (substitute-command-keys
7854 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7856 (defun org-mark-ring-goto (&optional n)
7857 "Jump to the previous position in the mark ring.
7858 With prefix arg N, jump back that many stored positions. When
7859 called several times in succession, walk through the entire ring.
7860 Org-mode commands jumping to a different position in the current file,
7861 or to another Org-mode file, automatically push the old position
7862 onto the ring."
7863 (interactive "p")
7864 (let (p m)
7865 (if (eq last-command this-command)
7866 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7867 (setq p org-mark-ring))
7868 (setq org-mark-ring-last-goto p)
7869 (setq m (car p))
7870 (switch-to-buffer (marker-buffer m))
7871 (goto-char m)
7872 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7874 (defun org-remove-angle-brackets (s)
7875 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7876 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7878 (defun org-add-angle-brackets (s)
7879 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7880 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7882 (defun org-remove-double-quotes (s)
7883 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7884 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7887 ;;; Following specific links
7889 (defun org-follow-timestamp-link ()
7890 (cond
7891 ((org-at-date-range-p t)
7892 (let ((org-agenda-start-on-weekday)
7893 (t1 (match-string 1))
7894 (t2 (match-string 2)))
7895 (setq t1 (time-to-days (org-time-string-to-time t1))
7896 t2 (time-to-days (org-time-string-to-time t2)))
7897 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7898 ((org-at-timestamp-p t)
7899 (org-agenda-list nil (time-to-days (org-time-string-to-time
7900 (substring (match-string 1) 0 10)))
7902 (t (error "This should not happen"))))
7905 ;;; Following file links
7906 (defvar org-wait nil)
7907 (defun org-open-file (path &optional in-emacs line search)
7908 "Open the file at PATH.
7909 First, this expands any special file name abbreviations. Then the
7910 configuration variable `org-file-apps' is checked if it contains an
7911 entry for this file type, and if yes, the corresponding command is launched.
7913 If no application is found, Emacs simply visits the file.
7915 With optional prefix argument IN-EMACS, Emacs will visit the file.
7916 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7917 and o use an external application to visit the file.
7919 Optional LINE specifies a line to go to, optional SEARCH a string to
7920 search for. If LINE or SEARCH is given, the file will always be
7921 opened in Emacs.
7922 If the file does not exist, an error is thrown."
7923 (setq in-emacs (or in-emacs line search))
7924 (let* ((file (if (equal path "")
7925 buffer-file-name
7926 (substitute-in-file-name (expand-file-name path))))
7927 (apps (append org-file-apps (org-default-apps)))
7928 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7929 (dirp (if remp nil (file-directory-p file)))
7930 (file (if (and dirp org-open-directory-means-index-dot-org)
7931 (concat (file-name-as-directory file) "index.org")
7932 file))
7933 (a-m-a-p (assq 'auto-mode apps))
7934 (dfile (downcase file))
7935 (old-buffer (current-buffer))
7936 (old-pos (point))
7937 (old-mode major-mode)
7938 ext cmd)
7939 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7940 (setq ext (match-string 1 dfile))
7941 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7942 (setq ext (match-string 1 dfile))))
7943 (cond
7944 ((equal in-emacs '(16))
7945 (setq cmd (cdr (assoc 'system apps))))
7946 (in-emacs (setq cmd 'emacs))
7948 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7949 (and dirp (cdr (assoc 'directory apps)))
7950 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7951 'string-match)
7952 (cdr (assoc ext apps))
7953 (cdr (assoc t apps))))))
7954 (when (eq cmd 'system)
7955 (setq cmd (cdr (assoc 'system apps))))
7956 (when (eq cmd 'default)
7957 (setq cmd (cdr (assoc t apps))))
7958 (when (eq cmd 'mailcap)
7959 (require 'mailcap)
7960 (mailcap-parse-mailcaps)
7961 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7962 (command (mailcap-mime-info mime-type)))
7963 (if (stringp command)
7964 (setq cmd command)
7965 (setq cmd 'emacs))))
7966 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7967 (not (file-exists-p file))
7968 (not org-open-non-existing-files))
7969 (error "No such file: %s" file))
7970 (cond
7971 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7972 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7973 (while (string-match "['\"]%s['\"]" cmd)
7974 (setq cmd (replace-match "%s" t t cmd)))
7975 (while (string-match "%s" cmd)
7976 (setq cmd (replace-match
7977 (save-match-data
7978 (shell-quote-argument
7979 (convert-standard-filename file)))
7980 t t cmd)))
7981 (save-window-excursion
7982 (start-process-shell-command cmd nil cmd)
7983 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7985 ((or (stringp cmd)
7986 (eq cmd 'emacs))
7987 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7988 (widen)
7989 (if line (goto-line line)
7990 (if search (org-link-search search))))
7991 ((consp cmd)
7992 (let ((file (convert-standard-filename file)))
7993 (eval cmd)))
7994 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7995 (and (org-mode-p) (eq old-mode 'org-mode)
7996 (or (not (equal old-buffer (current-buffer)))
7997 (not (equal old-pos (point))))
7998 (org-mark-ring-push old-pos old-buffer))))
8000 (defun org-default-apps ()
8001 "Return the default applications for this operating system."
8002 (cond
8003 ((eq system-type 'darwin)
8004 org-file-apps-defaults-macosx)
8005 ((eq system-type 'windows-nt)
8006 org-file-apps-defaults-windowsnt)
8007 (t org-file-apps-defaults-gnu)))
8009 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8010 "Convert extensions to regular expressions in the cars of LIST.
8011 Also, weed out any non-string entries, because the return value is used
8012 only for regexp matching.
8013 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8014 point to the symbol `emacs', indicating that the file should
8015 be opened in Emacs."
8016 (append
8017 (delq nil
8018 (mapcar (lambda (x)
8019 (if (not (stringp (car x)))
8021 (if (string-match "\\W" (car x))
8023 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8024 list))
8025 (if add-auto-mode
8026 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8028 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8029 (defun org-file-remote-p (file)
8030 "Test whether FILE specifies a location on a remote system.
8031 Return non-nil if the location is indeed remote.
8033 For example, the filename \"/user@host:/foo\" specifies a location
8034 on the system \"/user@host:\"."
8035 (cond ((fboundp 'file-remote-p)
8036 (file-remote-p file))
8037 ((fboundp 'tramp-handle-file-remote-p)
8038 (tramp-handle-file-remote-p file))
8039 ((and (boundp 'ange-ftp-name-format)
8040 (string-match (car ange-ftp-name-format) file))
8042 (t nil)))
8045 ;;;; Refiling
8047 (defun org-get-org-file ()
8048 "Read a filename, with default directory `org-directory'."
8049 (let ((default (or org-default-notes-file remember-data-file)))
8050 (read-file-name (format "File name [%s]: " default)
8051 (file-name-as-directory org-directory)
8052 default)))
8054 (defun org-notes-order-reversed-p ()
8055 "Check if the current file should receive notes in reversed order."
8056 (cond
8057 ((not org-reverse-note-order) nil)
8058 ((eq t org-reverse-note-order) t)
8059 ((not (listp org-reverse-note-order)) nil)
8060 (t (catch 'exit
8061 (let ((all org-reverse-note-order)
8062 entry)
8063 (while (setq entry (pop all))
8064 (if (string-match (car entry) buffer-file-name)
8065 (throw 'exit (cdr entry))))
8066 nil)))))
8068 (defvar org-refile-target-table nil
8069 "The list of refile targets, created by `org-refile'.")
8071 (defvar org-agenda-new-buffers nil
8072 "Buffers created to visit agenda files.")
8074 (defun org-get-refile-targets (&optional default-buffer)
8075 "Produce a table with refile targets."
8076 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8077 targets txt re files f desc descre fast-path-p level)
8078 (message "Getting targets...")
8079 (with-current-buffer (or default-buffer (current-buffer))
8080 (while (setq entry (pop entries))
8081 (setq files (car entry) desc (cdr entry))
8082 (setq fast-path-p nil)
8083 (cond
8084 ((null files) (setq files (list (current-buffer))))
8085 ((eq files 'org-agenda-files)
8086 (setq files (org-agenda-files 'unrestricted)))
8087 ((and (symbolp files) (fboundp files))
8088 (setq files (funcall files)))
8089 ((and (symbolp files) (boundp files))
8090 (setq files (symbol-value files))))
8091 (if (stringp files) (setq files (list files)))
8092 (cond
8093 ((eq (car desc) :tag)
8094 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8095 ((eq (car desc) :todo)
8096 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8097 ((eq (car desc) :regexp)
8098 (setq descre (cdr desc)))
8099 ((eq (car desc) :level)
8100 (setq descre (concat "^\\*\\{" (number-to-string
8101 (if org-odd-levels-only
8102 (1- (* 2 (cdr desc)))
8103 (cdr desc)))
8104 "\\}[ \t]")))
8105 ((eq (car desc) :maxlevel)
8106 (setq fast-path-p t)
8107 (setq descre (concat "^\\*\\{1," (number-to-string
8108 (if org-odd-levels-only
8109 (1- (* 2 (cdr desc)))
8110 (cdr desc)))
8111 "\\}[ \t]")))
8112 (t (error "Bad refiling target description %s" desc)))
8113 (while (setq f (pop files))
8114 (save-excursion
8115 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8116 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8117 (setq f (expand-file-name f))
8118 (save-excursion
8119 (save-restriction
8120 (widen)
8121 (goto-char (point-min))
8122 (while (re-search-forward descre nil t)
8123 (goto-char (point-at-bol))
8124 (when (looking-at org-complex-heading-regexp)
8125 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8126 txt (org-link-display-format (match-string 4))
8127 re (concat "^" (regexp-quote
8128 (buffer-substring (match-beginning 1)
8129 (match-end 4)))))
8130 (if (match-end 5) (setq re (concat re "[ \t]+"
8131 (regexp-quote
8132 (match-string 5)))))
8133 (setq re (concat re "[ \t]*$"))
8134 (when org-refile-use-outline-path
8135 (setq txt (mapconcat 'org-protect-slash
8136 (append
8137 (if (eq org-refile-use-outline-path 'file)
8138 (list (file-name-nondirectory
8139 (buffer-file-name (buffer-base-buffer))))
8140 (if (eq org-refile-use-outline-path 'full-file-path)
8141 (list (buffer-file-name (buffer-base-buffer)))))
8142 (org-get-outline-path fast-path-p level txt)
8143 (list txt))
8144 "/")))
8145 (push (list txt f re (point)) targets))
8146 (goto-char (point-at-eol))))))))
8147 (message "Getting targets...done")
8148 (nreverse targets))))
8150 (defun org-protect-slash (s)
8151 (while (string-match "/" s)
8152 (setq s (replace-match "\\" t t s)))
8155 (defvar org-olpa (make-vector 20 nil))
8157 (defun org-get-outline-path (&optional fastp level heading)
8158 "Return the outline path to the current entry, as a list."
8159 (if fastp
8160 (progn
8161 (if (> level 19)
8162 (error "Outline path failure, more than 19 levels."))
8163 (loop for i from level upto 19 do
8164 (aset org-olpa i nil))
8165 (prog1
8166 (delq nil (append org-olpa nil))
8167 (aset org-olpa level heading)))
8168 (let (rtn)
8169 (save-excursion
8170 (while (org-up-heading-safe)
8171 (when (looking-at org-complex-heading-regexp)
8172 (push (org-match-string-no-properties 4) rtn)))
8173 rtn))))
8175 (defvar org-refile-history nil
8176 "History for refiling operations.")
8178 (defun org-refile (&optional goto default-buffer)
8179 "Move the entry at point to another heading.
8180 The list of target headings is compiled using the information in
8181 `org-refile-targets', which see. This list is created before each use
8182 and will therefore always be up-to-date.
8184 At the target location, the entry is filed as a subitem of the target heading.
8185 Depending on `org-reverse-note-order', the new subitem will either be the
8186 first or the last subitem.
8188 If there is an active region, all entries in that region will be moved.
8189 However, the region must fulfil the requirement that the first heading
8190 is the first one sets the top-level of the moved text - at most siblings
8191 below it are allowed.
8193 With prefix arg GOTO, the command will only visit the target location,
8194 not actually move anything.
8195 With a double prefix `C-u C-u', go to the location where the last refiling
8196 operation has put the subtree."
8197 (interactive "P")
8198 (let* ((cbuf (current-buffer))
8199 (regionp (org-region-active-p))
8200 (region-start (and regionp (region-beginning)))
8201 (region-end (and regionp (region-end)))
8202 (region-length (and regionp (- region-end region-start)))
8203 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8204 pos it nbuf file re level reversed)
8205 (when regionp (goto-char region-start)
8206 (unless (org-kill-is-subtree-p
8207 (buffer-substring region-start region-end))
8208 (error "The region is not a (sequence of) subtree(s)")))
8209 (if (equal goto '(16))
8210 (org-refile-goto-last-stored)
8211 (when (setq it (org-refile-get-location
8212 (if goto "Goto: " "Refile to: ") default-buffer))
8213 (setq file (nth 1 it)
8214 re (nth 2 it)
8215 pos (nth 3 it))
8216 (if (and (not goto)
8217 (equal (buffer-file-name) file)
8218 (if regionp
8219 (and (>= pos region-start)
8220 (<= pos region-end))
8221 (and (>= pos (point))
8222 (< pos (save-excursion
8223 (org-end-of-subtree t t))))))
8224 (error "Cannot refile to position inside the tree or region"))
8226 (setq nbuf (or (find-buffer-visiting file)
8227 (find-file-noselect file)))
8228 (if goto
8229 (progn
8230 (switch-to-buffer nbuf)
8231 (goto-char pos)
8232 (org-show-context 'org-goto))
8233 (if regionp
8234 (progn
8235 (kill-new (buffer-substring region-start region-end))
8236 (org-save-markers-in-region region-start region-end))
8237 (org-copy-subtree 1 nil t))
8238 (save-excursion
8239 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8240 (find-file-noselect file))))
8241 (setq reversed (org-notes-order-reversed-p))
8242 (save-excursion
8243 (save-restriction
8244 (widen)
8245 (goto-char pos)
8246 (looking-at outline-regexp)
8247 (setq level (org-get-valid-level (funcall outline-level) 1))
8248 (goto-char
8249 (if reversed
8250 (or (outline-next-heading) (point-max))
8251 (or (save-excursion (outline-get-next-sibling))
8252 (org-end-of-subtree t t)
8253 (point-max))))
8254 (if (not (bolp)) (newline))
8255 (bookmark-set "org-refile-last-stored")
8256 (org-paste-subtree level))))
8257 (if regionp
8258 (delete-region (point) (+ (point) region-length))
8259 (org-cut-subtree))
8260 (setq org-markers-to-move nil)
8261 (message "Refiled to \"%s\"" (car it)))))))
8263 (defun org-refile-goto-last-stored ()
8264 "Go to the location where the last refile was stored."
8265 (interactive)
8266 (bookmark-jump "org-refile-last-stored")
8267 (message "This is the location of the last refile"))
8269 (defun org-refile-get-location (&optional prompt default-buffer)
8270 "Prompt the user for a refile location, using PROMPT."
8271 (let ((org-refile-targets org-refile-targets)
8272 (org-refile-use-outline-path org-refile-use-outline-path))
8273 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8274 (unless org-refile-target-table
8275 (error "No refile targets"))
8276 (let* ((cbuf (current-buffer))
8277 (partial-completion-mode nil)
8278 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8279 (cfunc (if (and org-refile-use-outline-path
8280 org-outline-path-complete-in-steps)
8281 'org-olpath-completing-read
8282 'org-ido-completing-read))
8283 (extra (if org-refile-use-outline-path "/" ""))
8284 (filename (and cfn (expand-file-name cfn)))
8285 (tbl (mapcar
8286 (lambda (x)
8287 (if (and (not (member org-refile-use-outline-path
8288 '(file full-file-path)))
8289 (not (equal filename (nth 1 x))))
8290 (cons (concat (car x) extra " ("
8291 (file-name-nondirectory (nth 1 x)) ")")
8292 (cdr x))
8293 (cons (concat (car x) extra) (cdr x))))
8294 org-refile-target-table))
8295 (completion-ignore-case t))
8296 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
8297 tbl)))
8299 (defun org-olpath-completing-read (prompt collection &rest args)
8300 "Read an outline path like a file name."
8301 (let ((thetable collection)
8302 (org-completion-use-ido nil)) ; does not work with ido.
8303 (apply
8304 'org-ido-completing-read prompt
8305 (lambda (string predicate &optional flag)
8306 (let (rtn r f (l (length string)))
8307 (cond
8308 ((eq flag nil)
8309 ;; try completion
8310 (try-completion string thetable))
8311 ((eq flag t)
8312 ;; all-completions
8313 (setq rtn (all-completions string thetable predicate))
8314 (mapcar
8315 (lambda (x)
8316 (setq r (substring x l))
8317 (if (string-match " ([^)]*)$" x)
8318 (setq f (match-string 0 x))
8319 (setq f ""))
8320 (if (string-match "/" r)
8321 (concat string (substring r 0 (match-end 0)) f)
8323 rtn))
8324 ((eq flag 'lambda)
8325 ;; exact match?
8326 (assoc string thetable)))
8328 args)))
8330 ;;;; Dynamic blocks
8332 (defun org-find-dblock (name)
8333 "Find the first dynamic block with name NAME in the buffer.
8334 If not found, stay at current position and return nil."
8335 (let (pos)
8336 (save-excursion
8337 (goto-char (point-min))
8338 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8339 nil t)
8340 (match-beginning 0))))
8341 (if pos (goto-char pos))
8342 pos))
8344 (defconst org-dblock-start-re
8345 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8346 "Matches the startline of a dynamic block, with parameters.")
8348 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8349 "Matches the end of a dynamic block.")
8351 (defun org-create-dblock (plist)
8352 "Create a dynamic block section, with parameters taken from PLIST.
8353 PLIST must contain a :name entry which is used as name of the block."
8354 (unless (bolp) (newline))
8355 (let ((name (plist-get plist :name)))
8356 (insert "#+BEGIN: " name)
8357 (while plist
8358 (if (eq (car plist) :name)
8359 (setq plist (cddr plist))
8360 (insert " " (prin1-to-string (pop plist)))))
8361 (insert "\n\n#+END:\n")
8362 (beginning-of-line -2)))
8364 (defun org-prepare-dblock ()
8365 "Prepare dynamic block for refresh.
8366 This empties the block, puts the cursor at the insert position and returns
8367 the property list including an extra property :name with the block name."
8368 (unless (looking-at org-dblock-start-re)
8369 (error "Not at a dynamic block"))
8370 (let* ((begdel (1+ (match-end 0)))
8371 (name (org-no-properties (match-string 1)))
8372 (params (append (list :name name)
8373 (read (concat "(" (match-string 3) ")")))))
8374 (unless (re-search-forward org-dblock-end-re nil t)
8375 (error "Dynamic block not terminated"))
8376 (setq params
8377 (append params
8378 (list :content (buffer-substring
8379 begdel (match-beginning 0)))))
8380 (delete-region begdel (match-beginning 0))
8381 (goto-char begdel)
8382 (open-line 1)
8383 params))
8385 (defun org-map-dblocks (&optional command)
8386 "Apply COMMAND to all dynamic blocks in the current buffer.
8387 If COMMAND is not given, use `org-update-dblock'."
8388 (let ((cmd (or command 'org-update-dblock))
8389 pos)
8390 (save-excursion
8391 (goto-char (point-min))
8392 (while (re-search-forward org-dblock-start-re nil t)
8393 (goto-char (setq pos (match-beginning 0)))
8394 (condition-case nil
8395 (funcall cmd)
8396 (error (message "Error during update of dynamic block")))
8397 (goto-char pos)
8398 (unless (re-search-forward org-dblock-end-re nil t)
8399 (error "Dynamic block not terminated"))))))
8401 (defun org-dblock-update (&optional arg)
8402 "User command for updating dynamic blocks.
8403 Update the dynamic block at point. With prefix ARG, update all dynamic
8404 blocks in the buffer."
8405 (interactive "P")
8406 (if arg
8407 (org-update-all-dblocks)
8408 (or (looking-at org-dblock-start-re)
8409 (org-beginning-of-dblock))
8410 (org-update-dblock)))
8412 (defun org-update-dblock ()
8413 "Update the dynamic block at point
8414 This means to empty the block, parse for parameters and then call
8415 the correct writing function."
8416 (save-window-excursion
8417 (let* ((pos (point))
8418 (line (org-current-line))
8419 (params (org-prepare-dblock))
8420 (name (plist-get params :name))
8421 (cmd (intern (concat "org-dblock-write:" name))))
8422 (message "Updating dynamic block `%s' at line %d..." name line)
8423 (funcall cmd params)
8424 (message "Updating dynamic block `%s' at line %d...done" name line)
8425 (goto-char pos))))
8427 (defun org-beginning-of-dblock ()
8428 "Find the beginning of the dynamic block at point.
8429 Error if there is no such block at point."
8430 (let ((pos (point))
8431 beg)
8432 (end-of-line 1)
8433 (if (and (re-search-backward org-dblock-start-re nil t)
8434 (setq beg (match-beginning 0))
8435 (re-search-forward org-dblock-end-re nil t)
8436 (> (match-end 0) pos))
8437 (goto-char beg)
8438 (goto-char pos)
8439 (error "Not in a dynamic block"))))
8441 (defun org-update-all-dblocks ()
8442 "Update all dynamic blocks in the buffer.
8443 This function can be used in a hook."
8444 (when (org-mode-p)
8445 (org-map-dblocks 'org-update-dblock)))
8448 ;;;; Completion
8450 (defconst org-additional-option-like-keywords
8451 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8452 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8453 "BEGIN_EXAMPLE" "END_EXAMPLE"
8454 "BEGIN_QUOTE" "END_QUOTE"
8455 "BEGIN_VERSE" "END_VERSE"
8456 "BEGIN_CENTER" "END_CENTER"
8457 "BEGIN_SRC" "END_SRC"
8458 "CATEGORY" "COLUMNS"
8459 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8461 (defcustom org-structure-template-alist
8463 ("s" "#+begin_src ?\n\n#+end_src"
8464 "<src lang=\"?\">\n\n</src>")
8465 ("e" "#+begin_example\n?\n#+end_example"
8466 "<example>\n?\n</example>")
8467 ("q" "#+begin_quote\n?\n#+end_quote"
8468 "<quote>\n?\n</quote>")
8469 ("v" "#+begin_verse\n?\n#+end_verse"
8470 "<verse>\n?\n/verse>")
8471 ("c" "#+begin_center\n?\n#+end_center"
8472 "<center>\n?\n/center>")
8473 ("l" "#+begin_latex\n?\n#+end_latex"
8474 "<literal style=\"latex\">\n?\n</literal>")
8475 ("L" "#+latex: "
8476 "<literal style=\"latex\">?</literal>")
8477 ("h" "#+begin_html\n?\n#+end_html"
8478 "<literal style=\"html\">\n?\n</literal>")
8479 ("H" "#+html: "
8480 "<literal style=\"html\">?</literal>")
8481 ("a" "#+begin_ascii\n?\n#+end_ascii")
8482 ("A" "#+ascii: ")
8483 ("i" "#+include %file ?"
8484 "<include file=%file markup=\"?\">")
8486 "Structure completion elements.
8487 This is a list of abbreviation keys and values. The value gets inserted
8488 it you type @samp{.} followed by the key and then the completion key,
8489 usually `M-TAB'. %file will be replaced by a file name after prompting
8490 for the file using completion.
8491 There are two templates for each key, the first uses the original Org syntax,
8492 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8493 the default when the /org-mtags.el/ module has been loaded. See also the
8494 variable `org-mtags-prefer-muse-templates'.
8495 This is an experimental feature, it is undecided if it is going to stay in."
8496 :group 'org-completion
8497 :type '(repeat
8498 (string :tag "Key")
8499 (string :tag "Template")
8500 (string :tag "Muse Template")))
8502 (defun org-try-structure-completion ()
8503 "Try to complete a structure template before point.
8504 This looks for strings like \"<e\" on an otherwise empty line and
8505 expands them."
8506 (let ((l (buffer-substring (point-at-bol) (point)))
8508 (when (and (looking-at "[ \t]*$")
8509 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8510 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8511 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8512 (match-beginning 1)) a)
8513 t)))
8515 (defun org-complete-expand-structure-template (start cell)
8516 "Expand a structure template."
8517 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8518 (rpl (nth (if musep 2 1) cell)))
8519 (delete-region start (point))
8520 (when (string-match "\\`#\\+" rpl)
8521 (cond
8522 ((bolp))
8523 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8524 (delete-region (point-at-bol) (point)))
8525 (t (newline))))
8526 (setq start (point))
8527 (if (string-match "%file" rpl)
8528 (setq rpl (replace-match
8529 (concat
8530 "\""
8531 (save-match-data
8532 (abbreviate-file-name (read-file-name "Include file: ")))
8533 "\"")
8534 t t rpl)))
8535 (insert rpl)
8536 (if (re-search-backward "\\?" start t) (delete-char 1))))
8539 (defun org-complete (&optional arg)
8540 "Perform completion on word at point.
8541 At the beginning of a headline, this completes TODO keywords as given in
8542 `org-todo-keywords'.
8543 If the current word is preceded by a backslash, completes the TeX symbols
8544 that are supported for HTML support.
8545 If the current word is preceded by \"#+\", completes special words for
8546 setting file options.
8547 In the line after \"#+STARTUP:, complete valid keywords.\"
8548 At all other locations, this simply calls the value of
8549 `org-completion-fallback-command'."
8550 (interactive "P")
8551 (org-without-partial-completion
8552 (catch 'exit
8553 (let* ((a nil)
8554 (end (point))
8555 (beg1 (save-excursion
8556 (skip-chars-backward (org-re "[:alnum:]_@"))
8557 (point)))
8558 (beg (save-excursion
8559 (skip-chars-backward "a-zA-Z0-9_:$")
8560 (point)))
8561 (confirm (lambda (x) (stringp (car x))))
8562 (searchhead (equal (char-before beg) ?*))
8563 (struct
8564 (when (and (member (char-before beg1) '(?. ?<))
8565 (setq a (assoc (buffer-substring beg1 (point))
8566 org-structure-template-alist)))
8567 (org-complete-expand-structure-template (1- beg1) a)
8568 (throw 'exit t)))
8569 (tag (and (equal (char-before beg1) ?:)
8570 (equal (char-after (point-at-bol)) ?*)))
8571 (prop (and (equal (char-before beg1) ?:)
8572 (not (equal (char-after (point-at-bol)) ?*))))
8573 (texp (equal (char-before beg) ?\\))
8574 (link (equal (char-before beg) ?\[))
8575 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8576 beg)
8577 "#+"))
8578 (startup (string-match "^#\\+STARTUP:.*"
8579 (buffer-substring (point-at-bol) (point))))
8580 (completion-ignore-case opt)
8581 (type nil)
8582 (tbl nil)
8583 (table (cond
8584 (opt
8585 (setq type :opt)
8586 (require 'org-exp)
8587 (append
8588 (mapcar
8589 (lambda (x)
8590 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8591 (cons (match-string 2 x) (match-string 1 x)))
8592 (org-split-string (org-get-current-options) "\n"))
8593 (mapcar 'list org-additional-option-like-keywords)))
8594 (startup
8595 (setq type :startup)
8596 org-startup-options)
8597 (link (append org-link-abbrev-alist-local
8598 org-link-abbrev-alist))
8599 (texp
8600 (setq type :tex)
8601 org-html-entities)
8602 ((string-match "\\`\\*+[ \t]+\\'"
8603 (buffer-substring (point-at-bol) beg))
8604 (setq type :todo)
8605 (mapcar 'list org-todo-keywords-1))
8606 (searchhead
8607 (setq type :searchhead)
8608 (save-excursion
8609 (goto-char (point-min))
8610 (while (re-search-forward org-todo-line-regexp nil t)
8611 (push (list
8612 (org-make-org-heading-search-string
8613 (match-string 3) t))
8614 tbl)))
8615 tbl)
8616 (tag (setq type :tag beg beg1)
8617 (or org-tag-alist (org-get-buffer-tags)))
8618 (prop (setq type :prop beg beg1)
8619 (mapcar 'list (org-buffer-property-keys nil t t)))
8620 (t (progn
8621 (call-interactively org-completion-fallback-command)
8622 (throw 'exit nil)))))
8623 (pattern (buffer-substring-no-properties beg end))
8624 (completion (try-completion pattern table confirm)))
8625 (cond ((eq completion t)
8626 (if (not (assoc (upcase pattern) table))
8627 (message "Already complete")
8628 (if (and (equal type :opt)
8629 (not (member (car (assoc (upcase pattern) table))
8630 org-additional-option-like-keywords)))
8631 (insert (substring (cdr (assoc (upcase pattern) table))
8632 (length pattern)))
8633 (if (memq type '(:tag :prop)) (insert ":")))))
8634 ((null completion)
8635 (message "Can't find completion for \"%s\"" pattern)
8636 (ding))
8637 ((not (string= pattern completion))
8638 (delete-region beg end)
8639 (if (string-match " +$" completion)
8640 (setq completion (replace-match "" t t completion)))
8641 (insert completion)
8642 (if (get-buffer-window "*Completions*")
8643 (delete-window (get-buffer-window "*Completions*")))
8644 (if (assoc completion table)
8645 (if (eq type :todo) (insert " ")
8646 (if (memq type '(:tag :prop)) (insert ":"))))
8647 (if (and (equal type :opt) (assoc completion table))
8648 (message "%s" (substitute-command-keys
8649 "Press \\[org-complete] again to insert example settings"))))
8651 (message "Making completion list...")
8652 (let ((list (sort (all-completions pattern table confirm)
8653 'string<)))
8654 (with-output-to-temp-buffer "*Completions*"
8655 (condition-case nil
8656 ;; Protection needed for XEmacs and emacs 21
8657 (display-completion-list list pattern)
8658 (error (display-completion-list list)))))
8659 (message "Making completion list...%s" "done")))))))
8661 ;;;; TODO, DEADLINE, Comments
8663 (defun org-toggle-comment ()
8664 "Change the COMMENT state of an entry."
8665 (interactive)
8666 (save-excursion
8667 (org-back-to-heading)
8668 (let (case-fold-search)
8669 (if (looking-at (concat outline-regexp
8670 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8671 (replace-match "" t t nil 1)
8672 (if (looking-at outline-regexp)
8673 (progn
8674 (goto-char (match-end 0))
8675 (insert org-comment-string " ")))))))
8677 (defvar org-last-todo-state-is-todo nil
8678 "This is non-nil when the last TODO state change led to a TODO state.
8679 If the last change removed the TODO tag or switched to DONE, then
8680 this is nil.")
8682 (defvar org-setting-tags nil) ; dynamically skipped
8684 (defun org-parse-local-options (string var)
8685 "Parse STRING for startup setting relevant for variable VAR."
8686 (let ((rtn (symbol-value var))
8687 e opts)
8688 (save-match-data
8689 (if (or (not string) (not (string-match "\\S-" string)))
8691 (setq opts (delq nil (mapcar (lambda (x)
8692 (setq e (assoc x org-startup-options))
8693 (if (eq (nth 1 e) var) e nil))
8694 (org-split-string string "[ \t]+"))))
8695 (if (not opts)
8697 (setq rtn nil)
8698 (while (setq e (pop opts))
8699 (if (not (nth 3 e))
8700 (setq rtn (nth 2 e))
8701 (if (not (listp rtn)) (setq rtn nil))
8702 (push (nth 2 e) rtn)))
8703 rtn)))))
8705 (defvar org-todo-setup-filter-hook nil
8706 "Hook for functions that pre-filter todo specs.
8708 Each function takes a todo spec and returns either `nil' or the spec
8709 transformed into canonical form." )
8711 (defvar org-todo-get-default-hook nil
8712 "Hook for functions that get a default item for todo.
8714 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8715 `nil' or a string to be used for the todo mark." )
8717 (defvar org-agenda-headline-snapshot-before-repeat)
8718 (defun org-todo (&optional arg)
8719 "Change the TODO state of an item.
8720 The state of an item is given by a keyword at the start of the heading,
8721 like
8722 *** TODO Write paper
8723 *** DONE Call mom
8725 The different keywords are specified in the variable `org-todo-keywords'.
8726 By default the available states are \"TODO\" and \"DONE\".
8727 So for this example: when the item starts with TODO, it is changed to DONE.
8728 When it starts with DONE, the DONE is removed. And when neither TODO nor
8729 DONE are present, add TODO at the beginning of the heading.
8731 With C-u prefix arg, use completion to determine the new state.
8732 With numeric prefix arg, switch to that state.
8733 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8734 With a tripple C-u prefix, circumvent any state blocking.
8736 For calling through lisp, arg is also interpreted in the following way:
8737 'none -> empty state
8738 \"\"(empty string) -> switch to empty state
8739 'done -> switch to DONE
8740 'nextset -> switch to the next set of keywords
8741 'previousset -> switch to the previous set of keywords
8742 \"WAITING\" -> switch to the specified keyword, but only if it
8743 really is a member of `org-todo-keywords'."
8744 (interactive "P")
8745 (if (equal arg '(16)) (setq arg 'nextset))
8746 (let ((org-blocker-hook org-blocker-hook))
8747 (when (equal arg '(64))
8748 (setq arg nil org-blocker-hook nil))
8749 (save-excursion
8750 (catch 'exit
8751 (org-back-to-heading)
8752 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8753 (or (looking-at (concat " +" org-todo-regexp " *"))
8754 (looking-at " *"))
8755 (let* ((match-data (match-data))
8756 (startpos (point-at-bol))
8757 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8758 (org-log-done org-log-done)
8759 (org-log-repeat org-log-repeat)
8760 (org-todo-log-states org-todo-log-states)
8761 (this (match-string 1))
8762 (hl-pos (match-beginning 0))
8763 (head (org-get-todo-sequence-head this))
8764 (ass (assoc head org-todo-kwd-alist))
8765 (interpret (nth 1 ass))
8766 (done-word (nth 3 ass))
8767 (final-done-word (nth 4 ass))
8768 (last-state (or this ""))
8769 (completion-ignore-case t)
8770 (member (member this org-todo-keywords-1))
8771 (tail (cdr member))
8772 (state (cond
8773 ((and org-todo-key-trigger
8774 (or (and (equal arg '(4))
8775 (eq org-use-fast-todo-selection 'prefix))
8776 (and (not arg) org-use-fast-todo-selection
8777 (not (eq org-use-fast-todo-selection
8778 'prefix)))))
8779 ;; Use fast selection
8780 (org-fast-todo-selection))
8781 ((and (equal arg '(4))
8782 (or (not org-use-fast-todo-selection)
8783 (not org-todo-key-trigger)))
8784 ;; Read a state with completion
8785 (org-ido-completing-read
8786 "State: " (mapcar (lambda(x) (list x))
8787 org-todo-keywords-1)
8788 nil t))
8789 ((eq arg 'right)
8790 (if this
8791 (if tail (car tail) nil)
8792 (car org-todo-keywords-1)))
8793 ((eq arg 'left)
8794 (if (equal member org-todo-keywords-1)
8796 (if this
8797 (nth (- (length org-todo-keywords-1)
8798 (length tail) 2)
8799 org-todo-keywords-1)
8800 (org-last org-todo-keywords-1))))
8801 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8802 (setq arg nil))) ; hack to fall back to cycling
8803 (arg
8804 ;; user or caller requests a specific state
8805 (cond
8806 ((equal arg "") nil)
8807 ((eq arg 'none) nil)
8808 ((eq arg 'done) (or done-word (car org-done-keywords)))
8809 ((eq arg 'nextset)
8810 (or (car (cdr (member head org-todo-heads)))
8811 (car org-todo-heads)))
8812 ((eq arg 'previousset)
8813 (let ((org-todo-heads (reverse org-todo-heads)))
8814 (or (car (cdr (member head org-todo-heads)))
8815 (car org-todo-heads))))
8816 ((car (member arg org-todo-keywords-1)))
8817 ((nth (1- (prefix-numeric-value arg))
8818 org-todo-keywords-1))))
8819 ((null member) (or head (car org-todo-keywords-1)))
8820 ((equal this final-done-word) nil) ;; -> make empty
8821 ((null tail) nil) ;; -> first entry
8822 ((memq interpret '(type priority))
8823 (if (eq this-command last-command)
8824 (car tail)
8825 (if (> (length tail) 0)
8826 (or done-word (car org-done-keywords))
8827 nil)))
8829 (car tail))))
8830 (state (or
8831 (run-hook-with-args-until-success
8832 'org-todo-get-default-hook state last-state)
8833 state))
8834 (next (if state (concat " " state " ") " "))
8835 (change-plist (list :type 'todo-state-change :from this :to state
8836 :position startpos))
8837 dolog now-done-p)
8838 (when org-blocker-hook
8839 (setq org-last-todo-state-is-todo
8840 (not (member this org-done-keywords)))
8841 (unless (save-excursion
8842 (save-match-data
8843 (run-hook-with-args-until-failure
8844 'org-blocker-hook change-plist)))
8845 (if (interactive-p)
8846 (error "TODO state change from %s to %s blocked" this state)
8847 ;; fail silently
8848 (message "TODO state change from %s to %s blocked" this state)
8849 (throw 'exit nil))))
8850 (store-match-data match-data)
8851 (replace-match next t t)
8852 (unless (pos-visible-in-window-p hl-pos)
8853 (message "TODO state changed to %s" (org-trim next)))
8854 (unless head
8855 (setq head (org-get-todo-sequence-head state)
8856 ass (assoc head org-todo-kwd-alist)
8857 interpret (nth 1 ass)
8858 done-word (nth 3 ass)
8859 final-done-word (nth 4 ass)))
8860 (when (memq arg '(nextset previousset))
8861 (message "Keyword-Set %d/%d: %s"
8862 (- (length org-todo-sets) -1
8863 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8864 (length org-todo-sets)
8865 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8866 (setq org-last-todo-state-is-todo
8867 (not (member state org-done-keywords)))
8868 (setq now-done-p (and (member state org-done-keywords)
8869 (not (member this org-done-keywords))))
8870 (and logging (org-local-logging logging))
8871 (when (and (or org-todo-log-states org-log-done)
8872 (not (memq arg '(nextset previousset))))
8873 ;; we need to look at recording a time and note
8874 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8875 (nth 2 (assoc this org-todo-log-states))))
8876 (when (and state
8877 (member state org-not-done-keywords)
8878 (not (member this org-not-done-keywords)))
8879 ;; This is now a todo state and was not one before
8880 ;; If there was a CLOSED time stamp, get rid of it.
8881 (org-add-planning-info nil nil 'closed))
8882 (when (and now-done-p org-log-done)
8883 ;; It is now done, and it was not done before
8884 (org-add-planning-info 'closed (org-current-time))
8885 (if (and (not dolog) (eq 'note org-log-done))
8886 (org-add-log-setup 'done state this 'findpos 'note)))
8887 (when (and state dolog)
8888 ;; This is a non-nil state, and we need to log it
8889 (org-add-log-setup 'state state this 'findpos dolog)))
8890 ;; Fixup tag positioning
8891 (org-todo-trigger-tag-changes state)
8892 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8893 (when org-provide-todo-statistics
8894 (org-update-parent-todo-statistics))
8895 (run-hooks 'org-after-todo-state-change-hook)
8896 (if (and arg (not (member state org-done-keywords)))
8897 (setq head (org-get-todo-sequence-head state)))
8898 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8899 ;; Do we need to trigger a repeat?
8900 (when now-done-p
8901 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8902 ;; This is for the agenda, take a snapshot of the headline.
8903 (save-match-data
8904 (setq org-agenda-headline-snapshot-before-repeat
8905 (org-get-heading))))
8906 (org-auto-repeat-maybe state))
8907 ;; Fixup cursor location if close to the keyword
8908 (if (and (outline-on-heading-p)
8909 (not (bolp))
8910 (save-excursion (beginning-of-line 1)
8911 (looking-at org-todo-line-regexp))
8912 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8913 (progn
8914 (goto-char (or (match-end 2) (match-end 1)))
8915 (just-one-space)))
8916 (when org-trigger-hook
8917 (save-excursion
8918 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8920 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
8921 "Block turning an entry into a TODO, using the hierarchy.
8922 This checks whether the current task should be blocked from state
8923 changes. Such blocking occurs when:
8925 1. The task has children which are not all in a completed state.
8927 2. A task has a parent with the property :ORDERED:, and there
8928 are siblings prior to the current task with incomplete
8929 status.
8931 3. The parent of the task is blocked because it has siblings that should
8932 be done first, or is child of a block grandparent TODO entry."
8934 (catch 'dont-block
8935 ;; If this is not a todo state change, or if this entry is already DONE,
8936 ;; do not block
8937 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8938 (member (plist-get change-plist :from)
8939 (cons 'done org-done-keywords))
8940 (member (plist-get change-plist :to)
8941 (cons 'todo org-not-done-keywords)))
8942 (throw 'dont-block t))
8943 ;; If this task has children, and any are undone, it's blocked
8944 (save-excursion
8945 (org-back-to-heading t)
8946 (let ((this-level (funcall outline-level)))
8947 (outline-next-heading)
8948 (let ((child-level (funcall outline-level)))
8949 (while (and (not (eobp))
8950 (> child-level this-level))
8951 ;; this todo has children, check whether they are all
8952 ;; completed
8953 (if (and (not (org-entry-is-done-p))
8954 (org-entry-is-todo-p))
8955 (throw 'dont-block nil))
8956 (outline-next-heading)
8957 (setq child-level (funcall outline-level))))))
8958 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8959 ;; any previous siblings are undone, it's blocked
8960 (save-excursion
8961 (org-back-to-heading t)
8962 (let* ((pos (point))
8963 (parent-pos (and (org-up-heading-safe) (point))))
8964 (if (not parent-pos) (throw 'dont-block t)) ; no parent
8965 (when (and (org-entry-get (point) "ORDERED")
8966 (forward-line 1)
8967 (re-search-forward org-not-done-heading-regexp pos t))
8968 (throw 'dont-block nil)) ; block, there is an older sibling not done.
8969 ;; Search further up the hierarchy, to see if an anchestor is blocked
8970 (while t
8971 (goto-char parent-pos)
8972 (if (not (looking-at org-not-done-heading-regexp))
8973 (throw 'dont-block t)) ; do not block, parent is not a TODO
8974 (setq pos (point))
8975 (setq parent-pos (and (org-up-heading-safe) (point)))
8976 (if (not parent-pos) (throw 'dont-block t)) ; no parent
8977 (when (and (org-entry-get (point) "ORDERED")
8978 (forward-line 1)
8979 (re-search-forward org-not-done-heading-regexp pos t))
8980 (throw 'dont-block nil))))))) ; block, older sibling not done.
8982 (defcustom org-track-ordered-property-with-tag nil
8983 "Should the ORDERED property also be shown as a tag?
8984 The ORDERED property decides if an entry should require subtasks to be
8985 completed in sequence. Since a property is not very visible, setting
8986 this option means that toggling the ORDERED property with the command
8987 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
8988 not relevant for the behavior, but it makes things more visible.
8990 Note that toggling the tag with tags commands will not change the property
8991 and therefore not influence behavior!
8993 This can be t, meaning the tag ORDERED should be used, It can also be a
8994 string to select a different tag for this task."
8995 :group 'org-todo
8996 :type '(choice
8997 (const :tag "No tracking" nil)
8998 (const :tag "Track with ORDERED tag" t)
8999 (string :tag "Use other tag")))
9001 (defun org-toggle-ordered-property ()
9002 "Toggle the ORDERED property of the current entry.
9003 For better visibility, you can track the value of this property with a tag.
9004 See variable `org-track-ordered-property-with-tag'."
9005 (interactive)
9006 (let* ((t1 org-track-ordered-property-with-tag)
9007 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9008 (save-excursion
9009 (org-back-to-heading)
9010 (if (org-entry-get nil "ORDERED")
9011 (progn
9012 (org-delete-property "ORDERED")
9013 (and tag (org-toggle-tag tag 'off))
9014 (message "Subtasks can be completed in arbitrary order"))
9015 (org-entry-put nil "ORDERED" "t")
9016 (and tag (org-toggle-tag tag 'on))
9017 (message "Subtasks must be completed in sequence")))))
9019 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9020 (defun org-block-todo-from-checkboxes (change-plist)
9021 "Block turning an entry into a TODO, using checkboxes.
9022 This checks whether the current task should be blocked from state
9023 changes because there are uncheckd boxes in this entry."
9024 (catch 'dont-block
9025 ;; If this is not a todo state change, or if this entry is already DONE,
9026 ;; do not block
9027 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9028 (member (plist-get change-plist :from)
9029 (cons 'done org-done-keywords))
9030 (member (plist-get change-plist :to)
9031 (cons 'todo org-not-done-keywords)))
9032 (throw 'dont-block t))
9033 ;; If this task has checkboxes that are not checked, it's blocked
9034 (save-excursion
9035 (org-back-to-heading t)
9036 (let ((beg (point)) end)
9037 (outline-next-heading)
9038 (setq end (point))
9039 (goto-char beg)
9040 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9041 end t)
9042 (progn
9043 (if (boundp 'org-blocked-by-checkboxes)
9044 (setq org-blocked-by-checkboxes t))
9045 (throw 'dont-block nil)))))
9046 t)) ; do not block
9048 (defun org-update-parent-todo-statistics ()
9049 "Update any statistics cookie in the parent of the current headline."
9050 (interactive)
9051 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9052 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9053 (catch 'exit
9054 (save-excursion
9055 (setq level (org-up-heading-safe))
9056 (unless level
9057 (throw 'exit nil))
9058 (while (re-search-forward box-re (point-at-eol) t)
9059 (setq cnt-all 0 cnt-done 0 cookie-present t)
9060 (setq is-percent (match-end 2))
9061 (save-match-data
9062 (unless (outline-next-heading) (throw 'exit nil))
9063 (while (looking-at org-todo-line-regexp)
9064 (setq kwd (match-string 2))
9065 (and kwd (setq cnt-all (1+ cnt-all)))
9066 (and (member kwd org-done-keywords)
9067 (setq cnt-done (1+ cnt-done)))
9068 (condition-case nil
9069 (org-forward-same-level 1)
9070 (error (end-of-line 1)))))
9071 (replace-match
9072 (if is-percent
9073 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9074 (format "[%d/%d]" cnt-done cnt-all))))
9075 (when cookie-present
9076 (run-hook-with-args 'org-after-todo-statistics-hook
9077 cnt-done (- cnt-all cnt-done)))))))
9079 (defvar org-after-todo-statistics-hook nil
9080 "Hook that is called after a TODO statistics cookie has been updated.
9081 Each function is called with two arguments: the number of not-done entries
9082 and the number of done entries.
9084 For example, the following function, when added to this hook, will switch
9085 an entry to DONE when all children are done, and back to TODO when new
9086 entries are set to a TODO status. Note that this hook is only called
9087 when there is a statistics cookie in the headline!
9089 (defun org-summary-todo (n-done n-not-done)
9090 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9091 (let (org-log-done org-log-states) ; turn off logging
9092 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9095 (defun org-todo-trigger-tag-changes (state)
9096 "Apply the changes defined in `org-todo-state-tags-triggers'."
9097 (let ((l org-todo-state-tags-triggers)
9098 changes)
9099 (when (or (not state) (equal state ""))
9100 (setq changes (append changes (cdr (assoc "" l)))))
9101 (when (and (stringp state) (> (length state) 0))
9102 (setq changes (append changes (cdr (assoc state l)))))
9103 (when (member state org-not-done-keywords)
9104 (setq changes (append changes (cdr (assoc 'todo l)))))
9105 (when (member state org-done-keywords)
9106 (setq changes (append changes (cdr (assoc 'done l)))))
9107 (dolist (c changes)
9108 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9110 (defun org-local-logging (value)
9111 "Get logging settings from a property VALUE."
9112 (let* (words w a)
9113 ;; directly set the variables, they are already local.
9114 (setq org-log-done nil
9115 org-log-repeat nil
9116 org-todo-log-states nil)
9117 (setq words (org-split-string value))
9118 (while (setq w (pop words))
9119 (cond
9120 ((setq a (assoc w org-startup-options))
9121 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9122 (set (nth 1 a) (nth 2 a))))
9123 ((setq a (org-extract-log-state-settings w))
9124 (and (member (car a) org-todo-keywords-1)
9125 (push a org-todo-log-states)))))))
9127 (defun org-get-todo-sequence-head (kwd)
9128 "Return the head of the TODO sequence to which KWD belongs.
9129 If KWD is not set, check if there is a text property remembering the
9130 right sequence."
9131 (let (p)
9132 (cond
9133 ((not kwd)
9134 (or (get-text-property (point-at-bol) 'org-todo-head)
9135 (progn
9136 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9137 nil (point-at-eol)))
9138 (get-text-property p 'org-todo-head))))
9139 ((not (member kwd org-todo-keywords-1))
9140 (car org-todo-keywords-1))
9141 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9143 (defun org-fast-todo-selection ()
9144 "Fast TODO keyword selection with single keys.
9145 Returns the new TODO keyword, or nil if no state change should occur."
9146 (let* ((fulltable org-todo-key-alist)
9147 (done-keywords org-done-keywords) ;; needed for the faces.
9148 (maxlen (apply 'max (mapcar
9149 (lambda (x)
9150 (if (stringp (car x)) (string-width (car x)) 0))
9151 fulltable)))
9152 (expert nil)
9153 (fwidth (+ maxlen 3 1 3))
9154 (ncol (/ (- (window-width) 4) fwidth))
9155 tg cnt e c tbl
9156 groups ingroup)
9157 (save-excursion
9158 (save-window-excursion
9159 (if expert
9160 (set-buffer (get-buffer-create " *Org todo*"))
9161 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9162 (erase-buffer)
9163 (org-set-local 'org-done-keywords done-keywords)
9164 (setq tbl fulltable cnt 0)
9165 (while (setq e (pop tbl))
9166 (cond
9167 ((equal e '(:startgroup))
9168 (push '() groups) (setq ingroup t)
9169 (when (not (= cnt 0))
9170 (setq cnt 0)
9171 (insert "\n"))
9172 (insert "{ "))
9173 ((equal e '(:endgroup))
9174 (setq ingroup nil cnt 0)
9175 (insert "}\n"))
9176 ((equal e '(:newline))
9177 (when (not (= cnt 0))
9178 (setq cnt 0)
9179 (insert "\n")
9180 (setq e (car tbl))
9181 (while (equal (car tbl) '(:newline))
9182 (insert "\n")
9183 (setq tbl (cdr tbl)))))
9185 (setq tg (car e) c (cdr e))
9186 (if ingroup (push tg (car groups)))
9187 (setq tg (org-add-props tg nil 'face
9188 (org-get-todo-face tg)))
9189 (if (and (= cnt 0) (not ingroup)) (insert " "))
9190 (insert "[" c "] " tg (make-string
9191 (- fwidth 4 (length tg)) ?\ ))
9192 (when (= (setq cnt (1+ cnt)) ncol)
9193 (insert "\n")
9194 (if ingroup (insert " "))
9195 (setq cnt 0)))))
9196 (insert "\n")
9197 (goto-char (point-min))
9198 (if (not expert) (org-fit-window-to-buffer))
9199 (message "[a-z..]:Set [SPC]:clear")
9200 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9201 (cond
9202 ((or (= c ?\C-g)
9203 (and (= c ?q) (not (rassoc c fulltable))))
9204 (setq quit-flag t))
9205 ((= c ?\ ) nil)
9206 ((setq e (rassoc c fulltable) tg (car e))
9208 (t (setq quit-flag t)))))))
9210 (defun org-entry-is-todo-p ()
9211 (member (org-get-todo-state) org-not-done-keywords))
9213 (defun org-entry-is-done-p ()
9214 (member (org-get-todo-state) org-done-keywords))
9216 (defun org-get-todo-state ()
9217 (save-excursion
9218 (org-back-to-heading t)
9219 (and (looking-at org-todo-line-regexp)
9220 (match-end 2)
9221 (match-string 2))))
9223 (defun org-at-date-range-p (&optional inactive-ok)
9224 "Is the cursor inside a date range?"
9225 (interactive)
9226 (save-excursion
9227 (catch 'exit
9228 (let ((pos (point)))
9229 (skip-chars-backward "^[<\r\n")
9230 (skip-chars-backward "<[")
9231 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9232 (>= (match-end 0) pos)
9233 (throw 'exit t))
9234 (skip-chars-backward "^<[\r\n")
9235 (skip-chars-backward "<[")
9236 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9237 (>= (match-end 0) pos)
9238 (throw 'exit t)))
9239 nil)))
9241 (defun org-get-repeat ()
9242 "Check if there is a deadline/schedule with repeater in this entry."
9243 (save-match-data
9244 (save-excursion
9245 (org-back-to-heading t)
9246 (if (re-search-forward
9247 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9248 (match-string 1)))))
9250 (defvar org-last-changed-timestamp)
9251 (defvar org-last-inserted-timestamp)
9252 (defvar org-log-post-message)
9253 (defvar org-log-note-purpose)
9254 (defvar org-log-note-how)
9255 (defvar org-log-note-extra)
9256 (defun org-auto-repeat-maybe (done-word)
9257 "Check if the current headline contains a repeated deadline/schedule.
9258 If yes, set TODO state back to what it was and change the base date
9259 of repeating deadline/scheduled time stamps to new date.
9260 This function is run automatically after each state change to a DONE state."
9261 ;; last-state is dynamically scoped into this function
9262 (let* ((repeat (org-get-repeat))
9263 (aa (assoc last-state org-todo-kwd-alist))
9264 (interpret (nth 1 aa))
9265 (head (nth 2 aa))
9266 (whata '(("d" . day) ("m" . month) ("y" . year)))
9267 (msg "Entry repeats: ")
9268 (org-log-done nil)
9269 (org-todo-log-states nil)
9270 (nshiftmax 10) (nshift 0)
9271 re type n what ts time)
9272 (when repeat
9273 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9274 (org-todo (if (eq interpret 'type) last-state head))
9275 (when org-log-repeat
9276 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9277 (memq 'org-add-log-note post-command-hook))
9278 ;; OK, we are already setup for some record
9279 (if (eq org-log-repeat 'note)
9280 ;; make sure we take a note, not only a time stamp
9281 (setq org-log-note-how 'note))
9282 ;; Set up for taking a record
9283 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9284 last-state
9285 'findpos org-log-repeat)))
9286 (org-back-to-heading t)
9287 (org-add-planning-info nil nil 'closed)
9288 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9289 org-deadline-time-regexp "\\)\\|\\("
9290 org-ts-regexp "\\)"))
9291 (while (re-search-forward
9292 re (save-excursion (outline-next-heading) (point)) t)
9293 (setq type (if (match-end 1) org-scheduled-string
9294 (if (match-end 3) org-deadline-string "Plain:"))
9295 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9296 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9297 (setq n (string-to-number (match-string 2 ts))
9298 what (match-string 3 ts))
9299 (if (equal what "w") (setq n (* n 7) what "d"))
9300 ;; Preparation, see if we need to modify the start date for the change
9301 (when (match-end 1)
9302 (setq time (save-match-data (org-time-string-to-time ts)))
9303 (cond
9304 ((equal (match-string 1 ts) ".")
9305 ;; Shift starting date to today
9306 (org-timestamp-change
9307 (- (time-to-days (current-time)) (time-to-days time))
9308 'day))
9309 ((equal (match-string 1 ts) "+")
9310 (while (or (= nshift 0)
9311 (<= (time-to-days time) (time-to-days (current-time))))
9312 (when (= (incf nshift) nshiftmax)
9313 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9314 (error "Abort")))
9315 (org-timestamp-change n (cdr (assoc what whata)))
9316 (org-at-timestamp-p t)
9317 (setq ts (match-string 1))
9318 (setq time (save-match-data (org-time-string-to-time ts))))
9319 (org-timestamp-change (- n) (cdr (assoc what whata)))
9320 ;; rematch, so that we have everything in place for the real shift
9321 (org-at-timestamp-p t)
9322 (setq ts (match-string 1))
9323 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9324 (org-timestamp-change n (cdr (assoc what whata)))
9325 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9326 (setq org-log-post-message msg)
9327 (message "%s" msg))))
9329 (defun org-show-todo-tree (arg)
9330 "Make a compact tree which shows all headlines marked with TODO.
9331 The tree will show the lines where the regexp matches, and all higher
9332 headlines above the match.
9333 With a \\[universal-argument] prefix, also show the DONE entries.
9334 With a numeric prefix N, construct a sparse tree for the Nth element
9335 of `org-todo-keywords-1'."
9336 (interactive "P")
9337 (let ((case-fold-search nil)
9338 (kwd-re
9339 (cond ((null arg) org-not-done-regexp)
9340 ((equal arg '(4))
9341 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9342 (mapcar 'list org-todo-keywords-1))))
9343 (concat "\\("
9344 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9345 "\\)\\>")))
9346 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9347 (regexp-quote (nth (1- (prefix-numeric-value arg))
9348 org-todo-keywords-1)))
9349 (t (error "Invalid prefix argument: %s" arg)))))
9350 (message "%d TODO entries found"
9351 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9353 (defun org-deadline (&optional remove time)
9354 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9355 With argument REMOVE, remove any deadline from the item.
9356 When TIME is set, it should be an internal time specification, and the
9357 scheduling will use the corresponding date."
9358 (interactive "P")
9359 (if remove
9360 (progn
9361 (org-remove-timestamp-with-keyword org-deadline-string)
9362 (message "Item no longer has a deadline."))
9363 (if (org-get-repeat)
9364 (error "Cannot change deadline on task with repeater, please do that by hand")
9365 (org-add-planning-info 'deadline time 'closed)
9366 (message "Deadline on %s" org-last-inserted-timestamp))))
9368 (defun org-schedule (&optional remove time)
9369 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9370 With argument REMOVE, remove any scheduling date from the item.
9371 When TIME is set, it should be an internal time specification, and the
9372 scheduling will use the corresponding date."
9373 (interactive "P")
9374 (if remove
9375 (progn
9376 (org-remove-timestamp-with-keyword org-scheduled-string)
9377 (message "Item is no longer scheduled."))
9378 (if (org-get-repeat)
9379 (error "Cannot reschedule task with repeater, please do that by hand")
9380 (org-add-planning-info 'scheduled time 'closed)
9381 (message "Scheduled to %s" org-last-inserted-timestamp))))
9383 (defun org-get-scheduled-time (pom &optional inherit)
9384 "Get the scheduled time as a time tuple, of a format suitable
9385 for calling org-schedule with, or if there is no scheduling,
9386 returns nil."
9387 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9388 (when time
9389 (apply 'encode-time (org-parse-time-string time)))))
9391 (defun org-get-deadline-time (pom &optional inherit)
9392 "Get the deadine as a time tuple, of a format suitable for
9393 calling org-deadlin with, or if there is no scheduling, returns
9394 nil."
9395 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9396 (when time
9397 (apply 'encode-time (org-parse-time-string time)))))
9399 (defun org-remove-timestamp-with-keyword (keyword)
9400 "Remove all time stamps with KEYWORD in the current entry."
9401 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9402 beg)
9403 (save-excursion
9404 (org-back-to-heading t)
9405 (setq beg (point))
9406 (org-end-of-subtree t t)
9407 (while (re-search-backward re beg t)
9408 (replace-match "")
9409 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9410 (equal (char-before) ?\ ))
9411 (backward-delete-char 1)
9412 (if (string-match "^[ \t]*$" (buffer-substring
9413 (point-at-bol) (point-at-eol)))
9414 (delete-region (point-at-bol)
9415 (min (point-max) (1+ (point-at-eol))))))))))
9417 (defun org-add-planning-info (what &optional time &rest remove)
9418 "Insert new timestamp with keyword in the line directly after the headline.
9419 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9420 If non is given, the user is prompted for a date.
9421 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9422 be removed."
9423 (interactive)
9424 (let (org-time-was-given org-end-time-was-given ts
9425 end default-time default-input)
9427 (catch 'exit
9428 (when (and (not time) (memq what '(scheduled deadline)))
9429 ;; Try to get a default date/time from existing timestamp
9430 (save-excursion
9431 (org-back-to-heading t)
9432 (setq end (save-excursion (outline-next-heading) (point)))
9433 (when (re-search-forward (if (eq what 'scheduled)
9434 org-scheduled-time-regexp
9435 org-deadline-time-regexp)
9436 end t)
9437 (setq ts (match-string 1)
9438 default-time
9439 (apply 'encode-time (org-parse-time-string ts))
9440 default-input (and ts (org-get-compact-tod ts))))))
9441 (when what
9442 ;; If necessary, get the time from the user
9443 (setq time (or time (org-read-date nil 'to-time nil nil
9444 default-time default-input))))
9446 (when (and org-insert-labeled-timestamps-at-point
9447 (member what '(scheduled deadline)))
9448 (insert
9449 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9450 (org-insert-time-stamp time org-time-was-given
9451 nil nil nil (list org-end-time-was-given))
9452 (setq what nil))
9453 (save-excursion
9454 (save-restriction
9455 (let (col list elt ts buffer-invisibility-spec)
9456 (org-back-to-heading t)
9457 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9458 (goto-char (match-end 1))
9459 (setq col (current-column))
9460 (goto-char (match-end 0))
9461 (if (eobp) (insert "\n") (forward-char 1))
9462 (when (and (not what)
9463 (not (looking-at
9464 (concat "[ \t]*"
9465 org-keyword-time-not-clock-regexp))))
9466 ;; Nothing to add, nothing to remove...... :-)
9467 (throw 'exit nil))
9468 (if (and (not (looking-at outline-regexp))
9469 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9470 "[^\r\n]*"))
9471 (not (equal (match-string 1) org-clock-string)))
9472 (narrow-to-region (match-beginning 0) (match-end 0))
9473 (insert-before-markers "\n")
9474 (backward-char 1)
9475 (narrow-to-region (point) (point))
9476 (and org-adapt-indentation (org-indent-to-column col)))
9477 ;; Check if we have to remove something.
9478 (setq list (cons what remove))
9479 (while list
9480 (setq elt (pop list))
9481 (goto-char (point-min))
9482 (when (or (and (eq elt 'scheduled)
9483 (re-search-forward org-scheduled-time-regexp nil t))
9484 (and (eq elt 'deadline)
9485 (re-search-forward org-deadline-time-regexp nil t))
9486 (and (eq elt 'closed)
9487 (re-search-forward org-closed-time-regexp nil t)))
9488 (replace-match "")
9489 (if (looking-at "--+<[^>]+>") (replace-match ""))
9490 (if (looking-at " +") (replace-match ""))))
9491 (goto-char (point-max))
9492 (when what
9493 (insert
9494 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9495 (cond ((eq what 'scheduled) org-scheduled-string)
9496 ((eq what 'deadline) org-deadline-string)
9497 ((eq what 'closed) org-closed-string))
9498 " ")
9499 (setq ts (org-insert-time-stamp
9500 time
9501 (or org-time-was-given
9502 (and (eq what 'closed) org-log-done-with-time))
9503 (eq what 'closed)
9504 nil nil (list org-end-time-was-given)))
9505 (end-of-line 1))
9506 (goto-char (point-min))
9507 (widen)
9508 (if (and (looking-at "[ \t]+\n")
9509 (equal (char-before) ?\n))
9510 (delete-region (1- (point)) (point-at-eol)))
9511 ts))))))
9513 (defvar org-log-note-marker (make-marker))
9514 (defvar org-log-note-purpose nil)
9515 (defvar org-log-note-state nil)
9516 (defvar org-log-note-previous-state nil)
9517 (defvar org-log-note-how nil)
9518 (defvar org-log-note-extra nil)
9519 (defvar org-log-note-window-configuration nil)
9520 (defvar org-log-note-return-to (make-marker))
9521 (defvar org-log-post-message nil
9522 "Message to be displayed after a log note has been stored.
9523 The auto-repeater uses this.")
9525 (defun org-add-note ()
9526 "Add a note to the current entry.
9527 This is done in the same way as adding a state change note."
9528 (interactive)
9529 (org-add-log-setup 'note nil nil 'findpos nil))
9531 (defvar org-property-end-re)
9532 (defun org-add-log-setup (&optional purpose state prev-state
9533 findpos how &optional extra)
9534 "Set up the post command hook to take a note.
9535 If this is about to TODO state change, the new state is expected in STATE.
9536 When FINDPOS is non-nil, find the correct position for the note in
9537 the current entry. If not, assume that it can be inserted at point.
9538 HOW is an indicator what kind of note should be created.
9539 EXTRA is additional text that will be inserted into the notes buffer."
9540 (let ((drawer (cond ((stringp org-log-into-drawer)
9541 org-log-into-drawer)
9542 (org-log-into-drawer "LOGBOOK")
9543 (t nil))))
9544 (save-restriction
9545 (save-excursion
9546 (when findpos
9547 (org-back-to-heading t)
9548 (narrow-to-region (point) (save-excursion
9549 (outline-next-heading) (point)))
9550 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9551 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9552 "[^\r\n]*\\)?"))
9553 (goto-char (match-end 0))
9554 (cond
9555 (drawer
9556 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9557 nil t)
9558 (progn
9559 (goto-char (match-end 0))
9560 (or org-log-states-order-reversed
9561 (and (re-search-forward org-property-end-re nil t)
9562 (goto-char (1- (match-beginning 0))))))
9563 (insert "\n:" drawer ":\n:END:")
9564 (beginning-of-line 0)
9565 (org-indent-line-function)
9566 (beginning-of-line 2)
9567 (org-indent-line-function)
9568 (end-of-line 0)))
9569 ((and org-log-state-notes-insert-after-drawers
9570 (save-excursion
9571 (forward-line) (looking-at org-drawer-regexp)))
9572 (forward-line)
9573 (while (looking-at org-drawer-regexp)
9574 (goto-char (match-end 0))
9575 (re-search-forward org-property-end-re (point-max) t)
9576 (forward-line))
9577 (forward-line -1)))
9578 (unless org-log-states-order-reversed
9579 (and (= (char-after) ?\n) (forward-char 1))
9580 (org-skip-over-state-notes)
9581 (skip-chars-backward " \t\n\r")))
9582 (move-marker org-log-note-marker (point))
9583 (setq org-log-note-purpose purpose
9584 org-log-note-state state
9585 org-log-note-previous-state prev-state
9586 org-log-note-how how
9587 org-log-note-extra extra)
9588 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9590 (defun org-skip-over-state-notes ()
9591 "Skip past the list of State notes in an entry."
9592 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9593 (while (looking-at "[ \t]*- State")
9594 (condition-case nil
9595 (org-next-item)
9596 (error (org-end-of-item)))))
9598 (defun org-add-log-note (&optional purpose)
9599 "Pop up a window for taking a note, and add this note later at point."
9600 (remove-hook 'post-command-hook 'org-add-log-note)
9601 (setq org-log-note-window-configuration (current-window-configuration))
9602 (delete-other-windows)
9603 (move-marker org-log-note-return-to (point))
9604 (switch-to-buffer (marker-buffer org-log-note-marker))
9605 (goto-char org-log-note-marker)
9606 (org-switch-to-buffer-other-window "*Org Note*")
9607 (erase-buffer)
9608 (if (memq org-log-note-how '(time state))
9609 (let (current-prefix-arg) (org-store-log-note))
9610 (let ((org-inhibit-startup t)) (org-mode))
9611 (insert (format "# Insert note for %s.
9612 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9613 (cond
9614 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9615 ((eq org-log-note-purpose 'done) "closed todo item")
9616 ((eq org-log-note-purpose 'state)
9617 (format "state change from \"%s\" to \"%s\""
9618 (or org-log-note-previous-state "")
9619 (or org-log-note-state "")))
9620 ((eq org-log-note-purpose 'note)
9621 "this entry")
9622 (t (error "This should not happen")))))
9623 (if org-log-note-extra (insert org-log-note-extra))
9624 (org-set-local 'org-finish-function 'org-store-log-note)))
9626 (defvar org-note-abort nil) ; dynamically scoped
9627 (defun org-store-log-note ()
9628 "Finish taking a log note, and insert it to where it belongs."
9629 (let ((txt (buffer-string))
9630 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9631 lines ind)
9632 (kill-buffer (current-buffer))
9633 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9634 (setq txt (replace-match "" t t txt)))
9635 (if (string-match "\\s-+\\'" txt)
9636 (setq txt (replace-match "" t t txt)))
9637 (setq lines (org-split-string txt "\n"))
9638 (when (and note (string-match "\\S-" note))
9639 (setq note
9640 (org-replace-escapes
9641 note
9642 (list (cons "%u" (user-login-name))
9643 (cons "%U" user-full-name)
9644 (cons "%t" (format-time-string
9645 (org-time-stamp-format 'long 'inactive)
9646 (current-time)))
9647 (cons "%s" (if org-log-note-state
9648 (concat "\"" org-log-note-state "\"")
9649 ""))
9650 (cons "%S" (if org-log-note-previous-state
9651 (concat "\"" org-log-note-previous-state "\"")
9652 "\"\"")))))
9653 (if lines (setq note (concat note " \\\\")))
9654 (push note lines))
9655 (when (or current-prefix-arg org-note-abort)
9656 (when org-log-into-drawer
9657 (org-remove-empty-drawer-at
9658 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
9659 org-log-note-marker))
9660 (setq lines nil))
9661 (when lines
9662 (save-excursion
9663 (set-buffer (marker-buffer org-log-note-marker))
9664 (save-excursion
9665 (goto-char org-log-note-marker)
9666 (move-marker org-log-note-marker nil)
9667 (end-of-line 1)
9668 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9669 (insert "- " (pop lines))
9670 (org-indent-line-function)
9671 (beginning-of-line 1)
9672 (looking-at "[ \t]*")
9673 (setq ind (concat (match-string 0) " "))
9674 (end-of-line 1)
9675 (while lines (insert "\n" ind (pop lines)))
9676 (message "Note stored")
9677 (org-back-to-heading t)
9678 (org-cycle-hide-drawers 'children)))))
9679 (set-window-configuration org-log-note-window-configuration)
9680 (with-current-buffer (marker-buffer org-log-note-return-to)
9681 (goto-char org-log-note-return-to))
9682 (move-marker org-log-note-return-to nil)
9683 (and org-log-post-message (message "%s" org-log-post-message)))
9685 (defun org-remove-empty-drawer-at (drawer pos)
9686 "Remove an emptyr DARWER drawer at position POS.
9687 POS may also be a marker."
9688 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
9689 (save-excursion
9690 (save-restriction
9691 (widen)
9692 (goto-char pos)
9693 (if (org-in-regexp
9694 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
9695 (replace-match ""))))))
9697 (defun org-sparse-tree (&optional arg)
9698 "Create a sparse tree, prompt for the details.
9699 This command can create sparse trees. You first need to select the type
9700 of match used to create the tree:
9702 t Show entries with a specific TODO keyword.
9703 m Show entries selected by a tags/property match.
9704 p Enter a property name and its value (both with completion on existing
9705 names/values) and show entries with that property.
9706 r Show entries matching a regular expression.
9707 d Show deadlines due within `org-deadline-warning-days'.
9708 b Show deadlines and scheduled items before a date.
9709 a Show deadlines and scheduled items after a date."
9710 (interactive "P")
9711 (let (ans kwd value)
9712 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
9713 (setq ans (read-char-exclusive))
9714 (cond
9715 ((equal ans ?d)
9716 (call-interactively 'org-check-deadlines))
9717 ((equal ans ?b)
9718 (call-interactively 'org-check-before-date))
9719 ((equal ans ?a)
9720 (call-interactively 'org-check-after-date))
9721 ((equal ans ?t)
9722 (org-show-todo-tree '(4)))
9723 ((member ans '(?T ?m))
9724 (call-interactively 'org-match-sparse-tree))
9725 ((member ans '(?p ?P))
9726 (setq kwd (org-ido-completing-read "Property: "
9727 (mapcar 'list (org-buffer-property-keys))))
9728 (setq value (org-ido-completing-read "Value: "
9729 (mapcar 'list (org-property-values kwd))))
9730 (unless (string-match "\\`{.*}\\'" value)
9731 (setq value (concat "\"" value "\"")))
9732 (org-match-sparse-tree arg (concat kwd "=" value)))
9733 ((member ans '(?r ?R ?/))
9734 (call-interactively 'org-occur))
9735 (t (error "No such sparse tree command \"%c\"" ans)))))
9737 (defvar org-occur-highlights nil
9738 "List of overlays used for occur matches.")
9739 (make-variable-buffer-local 'org-occur-highlights)
9740 (defvar org-occur-parameters nil
9741 "Parameters of the active org-occur calls.
9742 This is a list, each call to org-occur pushes as cons cell,
9743 containing the regular expression and the callback, onto the list.
9744 The list can contain several entries if `org-occur' has been called
9745 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9746 will only contain one set of parameters. When the highlights are
9747 removed (for example with `C-c C-c', or with the next edit (depending
9748 on `org-remove-highlights-with-change'), this variable is emptied
9749 as well.")
9750 (make-variable-buffer-local 'org-occur-parameters)
9752 (defun org-occur (regexp &optional keep-previous callback)
9753 "Make a compact tree which shows all matches of REGEXP.
9754 The tree will show the lines where the regexp matches, and all higher
9755 headlines above the match. It will also show the heading after the match,
9756 to make sure editing the matching entry is easy.
9757 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9758 call to `org-occur' will be kept, to allow stacking of calls to this
9759 command.
9760 If CALLBACK is non-nil, it is a function which is called to confirm
9761 that the match should indeed be shown."
9762 (interactive "sRegexp: \nP")
9763 (unless keep-previous
9764 (org-remove-occur-highlights nil nil t))
9765 (push (cons regexp callback) org-occur-parameters)
9766 (let ((cnt 0))
9767 (save-excursion
9768 (goto-char (point-min))
9769 (if (or (not keep-previous) ; do not want to keep
9770 (not org-occur-highlights)) ; no previous matches
9771 ;; hide everything
9772 (org-overview))
9773 (while (re-search-forward regexp nil t)
9774 (when (or (not callback)
9775 (save-match-data (funcall callback)))
9776 (setq cnt (1+ cnt))
9777 (when org-highlight-sparse-tree-matches
9778 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9779 (org-show-context 'occur-tree))))
9780 (when org-remove-highlights-with-change
9781 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9782 nil 'local))
9783 (unless org-sparse-tree-open-archived-trees
9784 (org-hide-archived-subtrees (point-min) (point-max)))
9785 (run-hooks 'org-occur-hook)
9786 (if (interactive-p)
9787 (message "%d match(es) for regexp %s" cnt regexp))
9788 cnt))
9790 (defun org-show-context (&optional key)
9791 "Make sure point and context and visible.
9792 How much context is shown depends upon the variables
9793 `org-show-hierarchy-above', `org-show-following-heading'. and
9794 `org-show-siblings'."
9795 (let ((heading-p (org-on-heading-p t))
9796 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9797 (following-p (org-get-alist-option org-show-following-heading key))
9798 (entry-p (org-get-alist-option org-show-entry-below key))
9799 (siblings-p (org-get-alist-option org-show-siblings key)))
9800 (catch 'exit
9801 ;; Show heading or entry text
9802 (if (and heading-p (not entry-p))
9803 (org-flag-heading nil) ; only show the heading
9804 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9805 (org-show-hidden-entry))) ; show entire entry
9806 (when following-p
9807 ;; Show next sibling, or heading below text
9808 (save-excursion
9809 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9810 (org-flag-heading nil))))
9811 (when siblings-p (org-show-siblings))
9812 (when hierarchy-p
9813 ;; show all higher headings, possibly with siblings
9814 (save-excursion
9815 (while (and (condition-case nil
9816 (progn (org-up-heading-all 1) t)
9817 (error nil))
9818 (not (bobp)))
9819 (org-flag-heading nil)
9820 (when siblings-p (org-show-siblings))))))))
9822 (defun org-reveal (&optional siblings)
9823 "Show current entry, hierarchy above it, and the following headline.
9824 This can be used to show a consistent set of context around locations
9825 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9826 not t for the search context.
9828 With optional argument SIBLINGS, on each level of the hierarchy all
9829 siblings are shown. This repairs the tree structure to what it would
9830 look like when opened with hierarchical calls to `org-cycle'."
9831 (interactive "P")
9832 (let ((org-show-hierarchy-above t)
9833 (org-show-following-heading t)
9834 (org-show-siblings (if siblings t org-show-siblings)))
9835 (org-show-context nil)))
9837 (defun org-highlight-new-match (beg end)
9838 "Highlight from BEG to END and mark the highlight is an occur headline."
9839 (let ((ov (org-make-overlay beg end)))
9840 (org-overlay-put ov 'face 'secondary-selection)
9841 (push ov org-occur-highlights)))
9843 (defun org-remove-occur-highlights (&optional beg end noremove)
9844 "Remove the occur highlights from the buffer.
9845 BEG and END are ignored. If NOREMOVE is nil, remove this function
9846 from the `before-change-functions' in the current buffer."
9847 (interactive)
9848 (unless org-inhibit-highlight-removal
9849 (mapc 'org-delete-overlay org-occur-highlights)
9850 (setq org-occur-highlights nil)
9851 (setq org-occur-parameters nil)
9852 (unless noremove
9853 (remove-hook 'before-change-functions
9854 'org-remove-occur-highlights 'local))))
9856 ;;;; Priorities
9858 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9859 "Regular expression matching the priority indicator.")
9861 (defvar org-remove-priority-next-time nil)
9863 (defun org-priority-up ()
9864 "Increase the priority of the current item."
9865 (interactive)
9866 (org-priority 'up))
9868 (defun org-priority-down ()
9869 "Decrease the priority of the current item."
9870 (interactive)
9871 (org-priority 'down))
9873 (defun org-priority (&optional action)
9874 "Change the priority of an item by ARG.
9875 ACTION can be `set', `up', `down', or a character."
9876 (interactive)
9877 (setq action (or action 'set))
9878 (let (current new news have remove)
9879 (save-excursion
9880 (org-back-to-heading t)
9881 (if (looking-at org-priority-regexp)
9882 (setq current (string-to-char (match-string 2))
9883 have t)
9884 (setq current org-default-priority))
9885 (cond
9886 ((or (eq action 'set)
9887 (if (featurep 'xemacs) (characterp action) (integerp action)))
9888 (if (not (eq action 'set))
9889 (setq new action)
9890 (message "Priority %c-%c, SPC to remove: "
9891 org-highest-priority org-lowest-priority)
9892 (setq new (read-char-exclusive)))
9893 (if (and (= (upcase org-highest-priority) org-highest-priority)
9894 (= (upcase org-lowest-priority) org-lowest-priority))
9895 (setq new (upcase new)))
9896 (cond ((equal new ?\ ) (setq remove t))
9897 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9898 (error "Priority must be between `%c' and `%c'"
9899 org-highest-priority org-lowest-priority))))
9900 ((eq action 'up)
9901 (if (and (not have) (eq last-command this-command))
9902 (setq new org-lowest-priority)
9903 (setq new (if (and org-priority-start-cycle-with-default (not have))
9904 org-default-priority (1- current)))))
9905 ((eq action 'down)
9906 (if (and (not have) (eq last-command this-command))
9907 (setq new org-highest-priority)
9908 (setq new (if (and org-priority-start-cycle-with-default (not have))
9909 org-default-priority (1+ current)))))
9910 (t (error "Invalid action")))
9911 (if (or (< (upcase new) org-highest-priority)
9912 (> (upcase new) org-lowest-priority))
9913 (setq remove t))
9914 (setq news (format "%c" new))
9915 (if have
9916 (if remove
9917 (replace-match "" t t nil 1)
9918 (replace-match news t t nil 2))
9919 (if remove
9920 (error "No priority cookie found in line")
9921 (looking-at org-todo-line-regexp)
9922 (if (match-end 2)
9923 (progn
9924 (goto-char (match-end 2))
9925 (insert " [#" news "]"))
9926 (goto-char (match-beginning 3))
9927 (insert "[#" news "] ")))))
9928 (org-preserve-lc (org-set-tags nil 'align))
9929 (if remove
9930 (message "Priority removed")
9931 (message "Priority of current item set to %s" news))))
9934 (defun org-get-priority (s)
9935 "Find priority cookie and return priority."
9936 (save-match-data
9937 (if (not (string-match org-priority-regexp s))
9938 (* 1000 (- org-lowest-priority org-default-priority))
9939 (* 1000 (- org-lowest-priority
9940 (string-to-char (match-string 2 s)))))))
9942 ;;;; Tags
9944 (defvar org-agenda-archives-mode)
9945 (defvar org-scanner-tags nil
9946 "The current tag list while the tags scanner is running.")
9947 (defvar org-trust-scanner-tags nil
9948 "Should `org-get-tags-at' use the tags fro the scanner.
9949 This is for internal dynamical scoping only.
9950 When this is non-nil, the function `org-get-tags-at' will return the value
9951 of `org-scanner-tags' instead of building the list by itself. This
9952 can lead to large speed-ups when the tags scanner is used in a file with
9953 many entries, and when the list of tags is retrieved, for example to
9954 obtain a list of properties. Building the tags list for each entry in such
9955 a file becomes an N^2 operation - but with this variable set, it scales
9956 as N.")
9958 (defun org-scan-tags (action matcher &optional todo-only)
9959 "Scan headline tags with inheritance and produce output ACTION.
9961 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9962 or `agenda' to produce an entry list for an agenda view. It can also be
9963 a Lisp form or a function that should be called at each matched headline, in
9964 this case the return value is a list of all return values from these calls.
9966 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9967 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9968 only lines with a TODO keyword are included in the output."
9969 (require 'org-agenda)
9970 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9971 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9972 (org-re
9973 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9974 (props (list 'face 'default
9975 'done-face 'org-agenda-done
9976 'undone-face 'default
9977 'mouse-face 'highlight
9978 'org-not-done-regexp org-not-done-regexp
9979 'org-todo-regexp org-todo-regexp
9980 'keymap org-agenda-keymap
9981 'help-echo
9982 (format "mouse-2 or RET jump to org file %s"
9983 (abbreviate-file-name
9984 (or (buffer-file-name (buffer-base-buffer))
9985 (buffer-name (buffer-base-buffer)))))))
9986 (case-fold-search nil)
9987 lspos tags tags-list
9988 (tags-alist (list (cons 0 org-file-tags)))
9989 (llast 0) rtn rtn1 level category i txt
9990 todo marker entry priority)
9991 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9992 (setq action (list 'lambda nil action)))
9993 (save-excursion
9994 (goto-char (point-min))
9995 (when (eq action 'sparse-tree)
9996 (org-overview)
9997 (org-remove-occur-highlights))
9998 (while (re-search-forward re nil t)
9999 (catch :skip
10000 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10001 tags (if (match-end 4) (org-match-string-no-properties 4)))
10002 (goto-char (setq lspos (1+ (match-beginning 0))))
10003 (setq level (org-reduced-level (funcall outline-level))
10004 category (org-get-category))
10005 (setq i llast llast level)
10006 ;; remove tag lists from same and sublevels
10007 (while (>= i level)
10008 (when (setq entry (assoc i tags-alist))
10009 (setq tags-alist (delete entry tags-alist)))
10010 (setq i (1- i)))
10011 ;; add the next tags
10012 (when tags
10013 (setq tags (org-split-string tags ":")
10014 tags-alist
10015 (cons (cons level tags) tags-alist)))
10016 ;; compile tags for current headline
10017 (setq tags-list
10018 (if org-use-tag-inheritance
10019 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10020 tags)
10021 org-scanner-tags tags-list)
10022 (when org-use-tag-inheritance
10023 (setcdr (car tags-alist)
10024 (mapcar (lambda (x)
10025 (setq x (copy-sequence x))
10026 (org-add-prop-inherited x))
10027 (cdar tags-alist))))
10028 (when (and tags org-use-tag-inheritance
10029 (or (not (eq t org-use-tag-inheritance))
10030 org-tags-exclude-from-inheritance))
10031 ;; selective inheritance, remove uninherited ones
10032 (setcdr (car tags-alist)
10033 (org-remove-uniherited-tags (cdar tags-alist))))
10034 (when (and (or (not todo-only)
10035 (and (member todo org-not-done-keywords)
10036 (or (not org-agenda-tags-todo-honor-ignore-options)
10037 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10038 (let ((case-fold-search t)) (eval matcher))
10040 (not (member org-archive-tag tags-list))
10041 ;; we have an archive tag, should we use this anyway?
10042 (or (not org-agenda-skip-archived-trees)
10043 (and (eq action 'agenda) org-agenda-archives-mode))))
10044 (unless (eq action 'sparse-tree) (org-agenda-skip))
10046 ;; select this headline
10048 (cond
10049 ((eq action 'sparse-tree)
10050 (and org-highlight-sparse-tree-matches
10051 (org-get-heading) (match-end 0)
10052 (org-highlight-new-match
10053 (match-beginning 0) (match-beginning 1)))
10054 (org-show-context 'tags-tree))
10055 ((eq action 'agenda)
10056 (setq txt (org-format-agenda-item
10058 (concat
10059 (if (eq org-tags-match-list-sublevels 'indented)
10060 (make-string (1- level) ?.) "")
10061 (org-get-heading))
10062 category
10063 tags-list
10065 priority (org-get-priority txt))
10066 (goto-char lspos)
10067 (setq marker (org-agenda-new-marker))
10068 (org-add-props txt props
10069 'org-marker marker 'org-hd-marker marker 'org-category category
10070 'todo-state todo
10071 'priority priority 'type "tagsmatch")
10072 (push txt rtn))
10073 ((functionp action)
10074 (save-excursion
10075 (setq rtn1 (funcall action))
10076 (push rtn1 rtn))
10077 (goto-char (point-at-eol)))
10078 (t (error "Invalid action")))
10080 ;; if we are to skip sublevels, jump to end of subtree
10081 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
10082 (when (and (eq action 'sparse-tree)
10083 (not org-sparse-tree-open-archived-trees))
10084 (org-hide-archived-subtrees (point-min) (point-max)))
10085 (nreverse rtn)))
10087 (defun org-remove-uniherited-tags (tags)
10088 "Remove all tags that are not inherited from the list TAGS."
10089 (cond
10090 ((eq org-use-tag-inheritance t)
10091 (if org-tags-exclude-from-inheritance
10092 (org-delete-all org-tags-exclude-from-inheritance tags)
10093 tags))
10094 ((not org-use-tag-inheritance) nil)
10095 ((stringp org-use-tag-inheritance)
10096 (delq nil (mapcar
10097 (lambda (x)
10098 (if (and (string-match org-use-tag-inheritance x)
10099 (not (member x org-tags-exclude-from-inheritance)))
10100 x nil))
10101 tags)))
10102 ((listp org-use-tag-inheritance)
10103 (delq nil (mapcar
10104 (lambda (x)
10105 (if (member x org-use-tag-inheritance) x nil))
10106 tags)))))
10108 (defvar todo-only) ;; dynamically scoped
10110 (defun org-match-sparse-tree (&optional todo-only match)
10111 "Create a sparse tree according to tags string MATCH.
10112 MATCH can contain positive and negative selection of tags, like
10113 \"+WORK+URGENT-WITHBOSS\".
10114 If optional argument TODO-ONLY is non-nil, only select lines that are
10115 also TODO lines."
10116 (interactive "P")
10117 (org-prepare-agenda-buffers (list (current-buffer)))
10118 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10120 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10122 (defvar org-cached-props nil)
10123 (defun org-cached-entry-get (pom property)
10124 (if (or (eq t org-use-property-inheritance)
10125 (and (stringp org-use-property-inheritance)
10126 (string-match org-use-property-inheritance property))
10127 (and (listp org-use-property-inheritance)
10128 (member property org-use-property-inheritance)))
10129 ;; Caching is not possible, check it directly
10130 (org-entry-get pom property 'inherit)
10131 ;; Get all properties, so that we can do complicated checks easily
10132 (cdr (assoc property (or org-cached-props
10133 (setq org-cached-props
10134 (org-entry-properties pom)))))))
10136 (defun org-global-tags-completion-table (&optional files)
10137 "Return the list of all tags in all agenda buffer/files."
10138 (save-excursion
10139 (org-uniquify
10140 (delq nil
10141 (apply 'append
10142 (mapcar
10143 (lambda (file)
10144 (set-buffer (find-file-noselect file))
10145 (append (org-get-buffer-tags)
10146 (mapcar (lambda (x) (if (stringp (car-safe x))
10147 (list (car-safe x)) nil))
10148 org-tag-alist)))
10149 (if (and files (car files))
10150 files
10151 (org-agenda-files))))))))
10153 (defun org-make-tags-matcher (match)
10154 "Create the TAGS//TODO matcher form for the selection string MATCH."
10155 ;; todo-only is scoped dynamically into this function, and the function
10156 ;; may change it if the matcher asks for it.
10157 (unless match
10158 ;; Get a new match request, with completion
10159 (let ((org-last-tags-completion-table
10160 (org-global-tags-completion-table)))
10161 (setq match (org-completing-read-no-ido
10162 "Match: " 'org-tags-completion-function nil nil nil
10163 'org-tags-history))))
10165 ;; Parse the string and create a lisp form
10166 (let ((match0 match)
10167 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10168 minus tag mm
10169 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10170 orterms term orlist re-p str-p level-p level-op time-p
10171 prop-p pn pv po cat-p gv rest)
10172 (if (string-match "/+" match)
10173 ;; match contains also a todo-matching request
10174 (progn
10175 (setq tagsmatch (substring match 0 (match-beginning 0))
10176 todomatch (substring match (match-end 0)))
10177 (if (string-match "^!" todomatch)
10178 (setq todo-only t todomatch (substring todomatch 1)))
10179 (if (string-match "^\\s-*$" todomatch)
10180 (setq todomatch nil)))
10181 ;; only matching tags
10182 (setq tagsmatch match todomatch nil))
10184 ;; Make the tags matcher
10185 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10186 (setq tagsmatcher t)
10187 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10188 (while (setq term (pop orterms))
10189 (while (and (equal (substring term -1) "\\") orterms)
10190 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10191 (while (string-match re term)
10192 (setq rest (substring term (match-end 0))
10193 minus (and (match-end 1)
10194 (equal (match-string 1 term) "-"))
10195 tag (match-string 2 term)
10196 re-p (equal (string-to-char tag) ?{)
10197 level-p (match-end 4)
10198 prop-p (match-end 5)
10199 mm (cond
10200 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10201 (level-p
10202 (setq level-op (org-op-to-function (match-string 3 term)))
10203 `(,level-op level ,(string-to-number
10204 (match-string 4 term))))
10205 (prop-p
10206 (setq pn (match-string 5 term)
10207 po (match-string 6 term)
10208 pv (match-string 7 term)
10209 cat-p (equal pn "CATEGORY")
10210 re-p (equal (string-to-char pv) ?{)
10211 str-p (equal (string-to-char pv) ?\")
10212 time-p (save-match-data
10213 (string-match "^\"[[<].*[]>]\"$" pv))
10214 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10215 (if time-p (setq pv (org-matcher-time pv)))
10216 (setq po (org-op-to-function po (if time-p 'time str-p)))
10217 (cond
10218 ((equal pn "CATEGORY")
10219 (setq gv '(get-text-property (point) 'org-category)))
10220 ((equal pn "TODO")
10221 (setq gv 'todo))
10223 (setq gv `(org-cached-entry-get nil ,pn))))
10224 (if re-p
10225 (if (eq po 'org<>)
10226 `(not (string-match ,pv (or ,gv "")))
10227 `(string-match ,pv (or ,gv "")))
10228 (if str-p
10229 `(,po (or ,gv "") ,pv)
10230 `(,po (string-to-number (or ,gv ""))
10231 ,(string-to-number pv) ))))
10232 (t `(member ,tag tags-list)))
10233 mm (if minus (list 'not mm) mm)
10234 term rest)
10235 (push mm tagsmatcher))
10236 (push (if (> (length tagsmatcher) 1)
10237 (cons 'and tagsmatcher)
10238 (car tagsmatcher))
10239 orlist)
10240 (setq tagsmatcher nil))
10241 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10242 (setq tagsmatcher
10243 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10244 ;; Make the todo matcher
10245 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10246 (setq todomatcher t)
10247 (setq orterms (org-split-string todomatch "|") orlist nil)
10248 (while (setq term (pop orterms))
10249 (while (string-match re term)
10250 (setq minus (and (match-end 1)
10251 (equal (match-string 1 term) "-"))
10252 kwd (match-string 2 term)
10253 re-p (equal (string-to-char kwd) ?{)
10254 term (substring term (match-end 0))
10255 mm (if re-p
10256 `(string-match ,(substring kwd 1 -1) todo)
10257 (list 'equal 'todo kwd))
10258 mm (if minus (list 'not mm) mm))
10259 (push mm todomatcher))
10260 (push (if (> (length todomatcher) 1)
10261 (cons 'and todomatcher)
10262 (car todomatcher))
10263 orlist)
10264 (setq todomatcher nil))
10265 (setq todomatcher (if (> (length orlist) 1)
10266 (cons 'or orlist) (car orlist))))
10268 ;; Return the string and lisp forms of the matcher
10269 (setq matcher (if todomatcher
10270 (list 'and tagsmatcher todomatcher)
10271 tagsmatcher))
10272 (cons match0 matcher)))
10274 (defun org-op-to-function (op &optional stringp)
10275 "Turn an operator into the appropriate function."
10276 (setq op
10277 (cond
10278 ((equal op "<" ) '(< string< org-time<))
10279 ((equal op ">" ) '(> org-string> org-time>))
10280 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10281 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10282 ((member op '("=" "==")) '(= string= org-time=))
10283 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10284 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10286 (defun org<> (a b) (not (= a b)))
10287 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10288 (defun org-string>= (a b) (not (string< a b)))
10289 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10290 (defun org-string<> (a b) (not (string= a b)))
10291 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10292 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10293 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10294 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10295 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10296 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10297 (defun org-2ft (s)
10298 "Convert S to a floating point time.
10299 If S is already a number, just return it. If it is a string, parse
10300 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10301 (cond
10302 ((numberp s) s)
10303 ((stringp s)
10304 (condition-case nil
10305 (float-time (apply 'encode-time (org-parse-time-string s)))
10306 (error 0.)))
10307 (t 0.)))
10309 (defun org-time-today ()
10310 "Time in seconds today at 0:00.
10311 Returns the float number of seconds since the beginning of the
10312 epoch to the beginning of today (00:00)."
10313 (float-time (apply 'encode-time
10314 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10316 (defun org-matcher-time (s)
10317 "Interpret a time comparison value."
10318 (save-match-data
10319 (cond
10320 ((string= s "<now>") (float-time))
10321 ((string= s "<today>") (org-time-today))
10322 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10323 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10324 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10325 (+ (org-time-today)
10326 (* (string-to-number (match-string 1 s))
10327 (cdr (assoc (match-string 2 s)
10328 '(("d" . 86400.0) ("w" . 604800.0)
10329 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10330 (t (org-2ft s)))))
10332 (defun org-match-any-p (re list)
10333 "Does re match any element of list?"
10334 (setq list (mapcar (lambda (x) (string-match re x)) list))
10335 (delq nil list))
10337 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10338 (defvar org-tags-overlay (org-make-overlay 1 1))
10339 (org-detach-overlay org-tags-overlay)
10341 (defun org-get-local-tags-at (&optional pos)
10342 "Get a list of tags defined in the current headline."
10343 (org-get-tags-at pos 'local))
10345 (defun org-get-local-tags ()
10346 "Get a list of tags defined in the current headline."
10347 (org-get-tags-at nil 'local))
10349 (defun org-get-tags-at (&optional pos local)
10350 "Get a list of all headline tags applicable at POS.
10351 POS defaults to point. If tags are inherited, the list contains
10352 the targets in the same sequence as the headlines appear, i.e.
10353 the tags of the current headline come last.
10354 When LOCAL is non-nil, only return tags from the current headline,
10355 ignore inherited ones."
10356 (interactive)
10357 (if (and org-trust-scanner-tags
10358 (or (not pos) (equal pos (point)))
10359 (not local))
10360 org-scanner-tags
10361 (let (tags ltags lastpos parent)
10362 (save-excursion
10363 (save-restriction
10364 (widen)
10365 (goto-char (or pos (point)))
10366 (save-match-data
10367 (catch 'done
10368 (condition-case nil
10369 (progn
10370 (org-back-to-heading t)
10371 (while (not (equal lastpos (point)))
10372 (setq lastpos (point))
10373 (when (looking-at
10374 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10375 (setq ltags (org-split-string
10376 (org-match-string-no-properties 1) ":"))
10377 (when parent
10378 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10379 (setq tags (append
10380 (if parent
10381 (org-remove-uniherited-tags ltags)
10382 ltags)
10383 tags)))
10384 (or org-use-tag-inheritance (throw 'done t))
10385 (if local (throw 'done t))
10386 (org-up-heading-all 1)
10387 (setq parent t)))
10388 (error nil)))))
10389 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10391 (defun org-add-prop-inherited (s)
10392 (add-text-properties 0 (length s) '(inherited t) s)
10395 (defun org-toggle-tag (tag &optional onoff)
10396 "Toggle the tag TAG for the current line.
10397 If ONOFF is `on' or `off', don't toggle but set to this state."
10398 (let (res current)
10399 (save-excursion
10400 (org-back-to-heading t)
10401 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10402 (point-at-eol) t)
10403 (progn
10404 (setq current (match-string 1))
10405 (replace-match ""))
10406 (setq current ""))
10407 (setq current (nreverse (org-split-string current ":")))
10408 (cond
10409 ((eq onoff 'on)
10410 (setq res t)
10411 (or (member tag current) (push tag current)))
10412 ((eq onoff 'off)
10413 (or (not (member tag current)) (setq current (delete tag current))))
10414 (t (if (member tag current)
10415 (setq current (delete tag current))
10416 (setq res t)
10417 (push tag current))))
10418 (end-of-line 1)
10419 (if current
10420 (progn
10421 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10422 (org-set-tags nil t))
10423 (delete-horizontal-space))
10424 (run-hooks 'org-after-tags-change-hook))
10425 res))
10427 (defun org-align-tags-here (to-col)
10428 ;; Assumes that this is a headline
10429 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10430 (beginning-of-line 1)
10431 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10432 (< pos (match-beginning 2)))
10433 (progn
10434 (setq tags-l (- (match-end 2) (match-beginning 2)))
10435 (goto-char (match-beginning 1))
10436 (insert " ")
10437 (delete-region (point) (1+ (match-beginning 2)))
10438 (setq ncol (max (1+ (current-column))
10439 (1+ col)
10440 (if (> to-col 0)
10441 to-col
10442 (- (abs to-col) tags-l))))
10443 (setq p (point))
10444 (insert (make-string (- ncol (current-column)) ?\ ))
10445 (setq ncol (current-column))
10446 (when indent-tabs-mode (tabify p (point-at-eol)))
10447 (org-move-to-column (min ncol col) t))
10448 (goto-char pos))))
10450 (defun org-set-tags-command (&optional arg just-align)
10451 "Call the set-tags command for the current entry."
10452 (interactive "P")
10453 (if (org-on-heading-p)
10454 (org-set-tags arg just-align)
10455 (save-excursion
10456 (org-back-to-heading t)
10457 (org-set-tags arg just-align))))
10459 (defun org-set-tags (&optional arg just-align)
10460 "Set the tags for the current headline.
10461 With prefix ARG, realign all tags in headings in the current buffer."
10462 (interactive "P")
10463 (let* ((re (concat "^" outline-regexp))
10464 (current (org-get-tags-string))
10465 (col (current-column))
10466 (org-setting-tags t)
10467 table current-tags inherited-tags ; computed below when needed
10468 tags p0 c0 c1 rpl)
10469 (if arg
10470 (save-excursion
10471 (goto-char (point-min))
10472 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10473 (while (re-search-forward re nil t)
10474 (org-set-tags nil t)
10475 (end-of-line 1)))
10476 (message "All tags realigned to column %d" org-tags-column))
10477 (if just-align
10478 (setq tags current)
10479 ;; Get a new set of tags from the user
10480 (save-excursion
10481 (setq table (append org-tag-persistent-alist
10482 (or org-tag-alist (org-get-buffer-tags)))
10483 org-last-tags-completion-table table
10484 current-tags (org-split-string current ":")
10485 inherited-tags (nreverse
10486 (nthcdr (length current-tags)
10487 (nreverse (org-get-tags-at))))
10488 tags
10489 (if (or (eq t org-use-fast-tag-selection)
10490 (and org-use-fast-tag-selection
10491 (delq nil (mapcar 'cdr table))))
10492 (org-fast-tag-selection
10493 current-tags inherited-tags table
10494 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10495 (let ((org-add-colon-after-tag-completion t))
10496 (org-trim
10497 (org-without-partial-completion
10498 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10499 nil nil current 'org-tags-history)))))))
10500 (while (string-match "[-+&]+" tags)
10501 ;; No boolean logic, just a list
10502 (setq tags (replace-match ":" t t tags))))
10504 (if (string-match "\\`[\t ]*\\'" tags)
10505 (setq tags "")
10506 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10507 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10509 ;; Insert new tags at the correct column
10510 (beginning-of-line 1)
10511 (cond
10512 ((and (equal current "") (equal tags "")))
10513 ((re-search-forward
10514 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10515 (point-at-eol) t)
10516 (if (equal tags "")
10517 (setq rpl "")
10518 (goto-char (match-beginning 0))
10519 (setq c0 (current-column) p0 (point)
10520 c1 (max (1+ c0) (if (> org-tags-column 0)
10521 org-tags-column
10522 (- (- org-tags-column) (length tags))))
10523 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10524 (replace-match rpl t t)
10525 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10526 tags)
10527 (t (error "Tags alignment failed")))
10528 (org-move-to-column col)
10529 (unless just-align
10530 (run-hooks 'org-after-tags-change-hook)))))
10532 (defun org-change-tag-in-region (beg end tag off)
10533 "Add or remove TAG for each entry in the region.
10534 This works in the agenda, and also in an org-mode buffer."
10535 (interactive
10536 (list (region-beginning) (region-end)
10537 (let ((org-last-tags-completion-table
10538 (if (org-mode-p)
10539 (org-get-buffer-tags)
10540 (org-global-tags-completion-table))))
10541 (org-ido-completing-read
10542 "Tag: " 'org-tags-completion-function nil nil nil
10543 'org-tags-history))
10544 (progn
10545 (message "[s]et or [r]emove? ")
10546 (equal (read-char-exclusive) ?r))))
10547 (if (fboundp 'deactivate-mark) (deactivate-mark))
10548 (let ((agendap (equal major-mode 'org-agenda-mode))
10549 l1 l2 m buf pos newhead (cnt 0))
10550 (goto-char end)
10551 (setq l2 (1- (org-current-line)))
10552 (goto-char beg)
10553 (setq l1 (org-current-line))
10554 (loop for l from l1 to l2 do
10555 (goto-line l)
10556 (setq m (get-text-property (point) 'org-hd-marker))
10557 (when (or (and (org-mode-p) (org-on-heading-p))
10558 (and agendap m))
10559 (setq buf (if agendap (marker-buffer m) (current-buffer))
10560 pos (if agendap m (point)))
10561 (with-current-buffer buf
10562 (save-excursion
10563 (save-restriction
10564 (goto-char pos)
10565 (setq cnt (1+ cnt))
10566 (org-toggle-tag tag (if off 'off 'on))
10567 (setq newhead (org-get-heading)))))
10568 (and agendap (org-agenda-change-all-lines newhead m))))
10569 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10571 (defun org-tags-completion-function (string predicate &optional flag)
10572 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10573 (confirm (lambda (x) (stringp (car x)))))
10574 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10575 (setq s1 (match-string 1 string)
10576 s2 (match-string 2 string))
10577 (setq s1 "" s2 string))
10578 (cond
10579 ((eq flag nil)
10580 ;; try completion
10581 (setq rtn (try-completion s2 ctable confirm))
10582 (if (stringp rtn)
10583 (setq rtn
10584 (concat s1 s2 (substring rtn (length s2))
10585 (if (and org-add-colon-after-tag-completion
10586 (assoc rtn ctable))
10587 ":" ""))))
10588 rtn)
10589 ((eq flag t)
10590 ;; all-completions
10591 (all-completions s2 ctable confirm)
10593 ((eq flag 'lambda)
10594 ;; exact match?
10595 (assoc s2 ctable)))
10598 (defun org-fast-tag-insert (kwd tags face &optional end)
10599 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10600 (insert (format "%-12s" (concat kwd ":"))
10601 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10602 (or end "")))
10604 (defun org-fast-tag-show-exit (flag)
10605 (save-excursion
10606 (goto-line 3)
10607 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10608 (replace-match ""))
10609 (when flag
10610 (end-of-line 1)
10611 (org-move-to-column (- (window-width) 19) t)
10612 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10614 (defun org-set-current-tags-overlay (current prefix)
10615 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10616 (if (featurep 'xemacs)
10617 (org-overlay-display org-tags-overlay (concat prefix s)
10618 'secondary-selection)
10619 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10620 (org-overlay-display org-tags-overlay (concat prefix s)))))
10622 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10623 "Fast tag selection with single keys.
10624 CURRENT is the current list of tags in the headline, INHERITED is the
10625 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10626 possibly with grouping information. TODO-TABLE is a similar table with
10627 TODO keywords, should these have keys assigned to them.
10628 If the keys are nil, a-z are automatically assigned.
10629 Returns the new tags string, or nil to not change the current settings."
10630 (let* ((fulltable (append table todo-table))
10631 (maxlen (apply 'max (mapcar
10632 (lambda (x)
10633 (if (stringp (car x)) (string-width (car x)) 0))
10634 fulltable)))
10635 (buf (current-buffer))
10636 (expert (eq org-fast-tag-selection-single-key 'expert))
10637 (buffer-tags nil)
10638 (fwidth (+ maxlen 3 1 3))
10639 (ncol (/ (- (window-width) 4) fwidth))
10640 (i-face 'org-done)
10641 (c-face 'org-todo)
10642 tg cnt e c char c1 c2 ntable tbl rtn
10643 ov-start ov-end ov-prefix
10644 (exit-after-next org-fast-tag-selection-single-key)
10645 (done-keywords org-done-keywords)
10646 groups ingroup)
10647 (save-excursion
10648 (beginning-of-line 1)
10649 (if (looking-at
10650 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10651 (setq ov-start (match-beginning 1)
10652 ov-end (match-end 1)
10653 ov-prefix "")
10654 (setq ov-start (1- (point-at-eol))
10655 ov-end (1+ ov-start))
10656 (skip-chars-forward "^\n\r")
10657 (setq ov-prefix
10658 (concat
10659 (buffer-substring (1- (point)) (point))
10660 (if (> (current-column) org-tags-column)
10662 (make-string (- org-tags-column (current-column)) ?\ ))))))
10663 (org-move-overlay org-tags-overlay ov-start ov-end)
10664 (save-window-excursion
10665 (if expert
10666 (set-buffer (get-buffer-create " *Org tags*"))
10667 (delete-other-windows)
10668 (split-window-vertically)
10669 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10670 (erase-buffer)
10671 (org-set-local 'org-done-keywords done-keywords)
10672 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10673 (org-fast-tag-insert "Current" current c-face "\n\n")
10674 (org-fast-tag-show-exit exit-after-next)
10675 (org-set-current-tags-overlay current ov-prefix)
10676 (setq tbl fulltable char ?a cnt 0)
10677 (while (setq e (pop tbl))
10678 (cond
10679 ((equal e '(:startgroup))
10680 (push '() groups) (setq ingroup t)
10681 (when (not (= cnt 0))
10682 (setq cnt 0)
10683 (insert "\n"))
10684 (insert "{ "))
10685 ((equal e '(:endgroup))
10686 (setq ingroup nil cnt 0)
10687 (insert "}\n"))
10688 ((equal e '(:newline))
10689 (when (not (= cnt 0))
10690 (setq cnt 0)
10691 (insert "\n")
10692 (setq e (car tbl))
10693 (while (equal (car tbl) '(:newline))
10694 (insert "\n")
10695 (setq tbl (cdr tbl)))))
10697 (setq tg (car e) c2 nil)
10698 (if (cdr e)
10699 (setq c (cdr e))
10700 ;; automatically assign a character.
10701 (setq c1 (string-to-char
10702 (downcase (substring
10703 tg (if (= (string-to-char tg) ?@) 1 0)))))
10704 (if (or (rassoc c1 ntable) (rassoc c1 table))
10705 (while (or (rassoc char ntable) (rassoc char table))
10706 (setq char (1+ char)))
10707 (setq c2 c1))
10708 (setq c (or c2 char)))
10709 (if ingroup (push tg (car groups)))
10710 (setq tg (org-add-props tg nil 'face
10711 (cond
10712 ((not (assoc tg table))
10713 (org-get-todo-face tg))
10714 ((member tg current) c-face)
10715 ((member tg inherited) i-face)
10716 (t nil))))
10717 (if (and (= cnt 0) (not ingroup)) (insert " "))
10718 (insert "[" c "] " tg (make-string
10719 (- fwidth 4 (length tg)) ?\ ))
10720 (push (cons tg c) ntable)
10721 (when (= (setq cnt (1+ cnt)) ncol)
10722 (insert "\n")
10723 (if ingroup (insert " "))
10724 (setq cnt 0)))))
10725 (setq ntable (nreverse ntable))
10726 (insert "\n")
10727 (goto-char (point-min))
10728 (if (not expert) (org-fit-window-to-buffer))
10729 (setq rtn
10730 (catch 'exit
10731 (while t
10732 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10733 (if groups " [!] no groups" " [!]groups")
10734 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10735 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10736 (cond
10737 ((= c ?\r) (throw 'exit t))
10738 ((= c ?!)
10739 (setq groups (not groups))
10740 (goto-char (point-min))
10741 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10742 ((= c ?\C-c)
10743 (if (not expert)
10744 (org-fast-tag-show-exit
10745 (setq exit-after-next (not exit-after-next)))
10746 (setq expert nil)
10747 (delete-other-windows)
10748 (split-window-vertically)
10749 (org-switch-to-buffer-other-window " *Org tags*")
10750 (org-fit-window-to-buffer)))
10751 ((or (= c ?\C-g)
10752 (and (= c ?q) (not (rassoc c ntable))))
10753 (org-detach-overlay org-tags-overlay)
10754 (setq quit-flag t))
10755 ((= c ?\ )
10756 (setq current nil)
10757 (if exit-after-next (setq exit-after-next 'now)))
10758 ((= c ?\t)
10759 (condition-case nil
10760 (setq tg (org-ido-completing-read
10761 "Tag: "
10762 (or buffer-tags
10763 (with-current-buffer buf
10764 (org-get-buffer-tags)))))
10765 (quit (setq tg "")))
10766 (when (string-match "\\S-" tg)
10767 (add-to-list 'buffer-tags (list tg))
10768 (if (member tg current)
10769 (setq current (delete tg current))
10770 (push tg current)))
10771 (if exit-after-next (setq exit-after-next 'now)))
10772 ((setq e (rassoc c todo-table) tg (car e))
10773 (with-current-buffer buf
10774 (save-excursion (org-todo tg)))
10775 (if exit-after-next (setq exit-after-next 'now)))
10776 ((setq e (rassoc c ntable) tg (car e))
10777 (if (member tg current)
10778 (setq current (delete tg current))
10779 (loop for g in groups do
10780 (if (member tg g)
10781 (mapc (lambda (x)
10782 (setq current (delete x current)))
10783 g)))
10784 (push tg current))
10785 (if exit-after-next (setq exit-after-next 'now))))
10787 ;; Create a sorted list
10788 (setq current
10789 (sort current
10790 (lambda (a b)
10791 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10792 (if (eq exit-after-next 'now) (throw 'exit t))
10793 (goto-char (point-min))
10794 (beginning-of-line 2)
10795 (delete-region (point) (point-at-eol))
10796 (org-fast-tag-insert "Current" current c-face)
10797 (org-set-current-tags-overlay current ov-prefix)
10798 (while (re-search-forward
10799 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10800 (setq tg (match-string 1))
10801 (add-text-properties
10802 (match-beginning 1) (match-end 1)
10803 (list 'face
10804 (cond
10805 ((member tg current) c-face)
10806 ((member tg inherited) i-face)
10807 (t (get-text-property (match-beginning 1) 'face))))))
10808 (goto-char (point-min)))))
10809 (org-detach-overlay org-tags-overlay)
10810 (if rtn
10811 (mapconcat 'identity current ":")
10812 nil))))
10814 (defun org-get-tags-string ()
10815 "Get the TAGS string in the current headline."
10816 (unless (org-on-heading-p t)
10817 (error "Not on a heading"))
10818 (save-excursion
10819 (beginning-of-line 1)
10820 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10821 (org-match-string-no-properties 1)
10822 "")))
10824 (defun org-get-tags ()
10825 "Get the list of tags specified in the current headline."
10826 (org-split-string (org-get-tags-string) ":"))
10828 (defun org-get-buffer-tags ()
10829 "Get a table of all tags used in the buffer, for completion."
10830 (let (tags)
10831 (save-excursion
10832 (goto-char (point-min))
10833 (while (re-search-forward
10834 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10835 (when (equal (char-after (point-at-bol 0)) ?*)
10836 (mapc (lambda (x) (add-to-list 'tags x))
10837 (org-split-string (org-match-string-no-properties 1) ":")))))
10838 (mapcar 'list tags)))
10840 ;;;; The mapping API
10842 ;;;###autoload
10843 (defun org-map-entries (func &optional match scope &rest skip)
10844 "Call FUNC at each headline selected by MATCH in SCOPE.
10846 FUNC is a function or a lisp form. The function will be called without
10847 arguments, with the cursor positioned at the beginning of the headline.
10848 The return values of all calls to the function will be collected and
10849 returned as a list.
10851 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10852 Only headlines that are matched by this query will be considered during
10853 the iteration. When MATCH is nil or t, all headlines will be
10854 visited by the iteration.
10856 SCOPE determines the scope of this command. It can be any of:
10858 nil The current buffer, respecting the restriction if any
10859 tree The subtree started with the entry at point
10860 file The current buffer, without restriction
10861 file-with-archives
10862 The current buffer, and any archives associated with it
10863 agenda All agenda files
10864 agenda-with-archives
10865 All agenda files with any archive files associated with them
10866 \(file1 file2 ...)
10867 If this is a list, all files in the list will be scanned
10869 The remaining args are treated as settings for the skipping facilities of
10870 the scanner. The following items can be given here:
10872 archive skip trees with the archive tag.
10873 comment skip trees with the COMMENT keyword
10874 function or Emacs Lisp form:
10875 will be used as value for `org-agenda-skip-function', so whenever
10876 the the function returns t, FUNC will not be called for that
10877 entry and search will continue from the point where the
10878 function leaves it.
10880 If your function needs to retrieve the tags including inherited tags
10881 at the *current* entry, you can use the value of the variable
10882 `org-scanner-tags' which will be much faster than getting the value
10883 with `org-get-tags-at'. If your function gets properties with
10884 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
10885 to t around the call to `org-entry-properties' to get the same speedup.
10886 Note that if your function moves around to retrieve tags and properties at
10887 a *different* entry, you cannot use these techniques."
10888 (let* ((org-agenda-archives-mode nil) ; just to make sure
10889 (org-agenda-skip-archived-trees (memq 'archive skip))
10890 (org-agenda-skip-comment-trees (memq 'comment skip))
10891 (org-agenda-skip-function
10892 (car (org-delete-all '(comment archive) skip)))
10893 (org-tags-match-list-sublevels t)
10894 matcher file res
10895 org-todo-keywords-for-agenda
10896 org-done-keywords-for-agenda
10897 org-todo-keyword-alist-for-agenda
10898 org-tag-alist-for-agenda)
10900 (cond
10901 ((eq match t) (setq matcher t))
10902 ((eq match nil) (setq matcher t))
10903 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10905 (save-excursion
10906 (save-restriction
10907 (when (eq scope 'tree)
10908 (org-back-to-heading t)
10909 (org-narrow-to-subtree)
10910 (setq scope nil))
10912 (if (not scope)
10913 (progn
10914 (org-prepare-agenda-buffers
10915 (list (buffer-file-name (current-buffer))))
10916 (setq res (org-scan-tags func matcher)))
10917 ;; Get the right scope
10918 (cond
10919 ((and scope (listp scope) (symbolp (car scope)))
10920 (setq scope (eval scope)))
10921 ((eq scope 'agenda)
10922 (setq scope (org-agenda-files t)))
10923 ((eq scope 'agenda-with-archives)
10924 (setq scope (org-agenda-files t))
10925 (setq scope (org-add-archive-files scope)))
10926 ((eq scope 'file)
10927 (setq scope (list (buffer-file-name))))
10928 ((eq scope 'file-with-archives)
10929 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10930 (org-prepare-agenda-buffers scope)
10931 (while (setq file (pop scope))
10932 (with-current-buffer (org-find-base-buffer-visiting file)
10933 (save-excursion
10934 (save-restriction
10935 (widen)
10936 (goto-char (point-min))
10937 (setq res (append res (org-scan-tags func matcher))))))))))
10938 res))
10940 ;;;; Properties
10942 ;;; Setting and retrieving properties
10944 (defconst org-special-properties
10945 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10946 "TIMESTAMP" "TIMESTAMP_IA")
10947 "The special properties valid in Org-mode.
10949 These are properties that are not defined in the property drawer,
10950 but in some other way.")
10952 (defconst org-default-properties
10953 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10954 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10955 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10956 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10957 "Some properties that are used by Org-mode for various purposes.
10958 Being in this list makes sure that they are offered for completion.")
10960 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10961 "Regular expression matching the first line of a property drawer.")
10963 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10964 "Regular expression matching the first line of a property drawer.")
10966 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10967 "Regular expression matching the first line of a property drawer.")
10969 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10970 "Regular expression matching the first line of a property drawer.")
10972 (defconst org-property-drawer-re
10973 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10974 org-property-end-re "\\)\n?")
10975 "Matches an entire property drawer.")
10977 (defconst org-clock-drawer-re
10978 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10979 org-property-end-re "\\)\n?")
10980 "Matches an entire clock drawer.")
10982 (defun org-property-action ()
10983 "Do an action on properties."
10984 (interactive)
10985 (let (c)
10986 (org-at-property-p)
10987 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10988 (setq c (read-char-exclusive))
10989 (cond
10990 ((equal c ?s)
10991 (call-interactively 'org-set-property))
10992 ((equal c ?d)
10993 (call-interactively 'org-delete-property))
10994 ((equal c ?D)
10995 (call-interactively 'org-delete-property-globally))
10996 ((equal c ?c)
10997 (call-interactively 'org-compute-property-at-point))
10998 (t (error "No such property action %c" c)))))
11000 (defun org-at-property-p ()
11001 "Is the cursor in a property line?"
11002 ;; FIXME: Does not check if we are actually in the drawer.
11003 ;; FIXME: also returns true on any drawers.....
11004 ;; This is used by C-c C-c for property action.
11005 (save-excursion
11006 (beginning-of-line 1)
11007 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11009 (defun org-get-property-block (&optional beg end force)
11010 "Return the (beg . end) range of the body of the property drawer.
11011 BEG and END can be beginning and end of subtree, if not given
11012 they will be found.
11013 If the drawer does not exist and FORCE is non-nil, create the drawer."
11014 (catch 'exit
11015 (save-excursion
11016 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11017 (end (or end (progn (outline-next-heading) (point)))))
11018 (goto-char beg)
11019 (if (re-search-forward org-property-start-re end t)
11020 (setq beg (1+ (match-end 0)))
11021 (if force
11022 (save-excursion
11023 (org-insert-property-drawer)
11024 (setq end (progn (outline-next-heading) (point))))
11025 (throw 'exit nil))
11026 (goto-char beg)
11027 (if (re-search-forward org-property-start-re end t)
11028 (setq beg (1+ (match-end 0)))))
11029 (if (re-search-forward org-property-end-re end t)
11030 (setq end (match-beginning 0))
11031 (or force (throw 'exit nil))
11032 (goto-char beg)
11033 (setq end beg)
11034 (org-indent-line-function)
11035 (insert ":END:\n"))
11036 (cons beg end)))))
11038 (defun org-entry-properties (&optional pom which)
11039 "Get all properties of the entry at point-or-marker POM.
11040 This includes the TODO keyword, the tags, time strings for deadline,
11041 scheduled, and clocking, and any additional properties defined in the
11042 entry. The return value is an alist, keys may occur multiple times
11043 if the property key was used several times.
11044 POM may also be nil, in which case the current entry is used.
11045 If WHICH is nil or `all', get all properties. If WHICH is
11046 `special' or `standard', only get that subclass."
11047 (setq which (or which 'all))
11048 (org-with-point-at pom
11049 (let ((clockstr (substring org-clock-string 0 -1))
11050 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11051 beg end range props sum-props key value string clocksum)
11052 (save-excursion
11053 (when (condition-case nil
11054 (and (org-mode-p) (org-back-to-heading t))
11055 (error nil))
11056 (setq beg (point))
11057 (setq sum-props (get-text-property (point) 'org-summaries))
11058 (setq clocksum (get-text-property (point) :org-clock-minutes))
11059 (outline-next-heading)
11060 (setq end (point))
11061 (when (memq which '(all special))
11062 ;; Get the special properties, like TODO and tags
11063 (goto-char beg)
11064 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11065 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11066 (when (looking-at org-priority-regexp)
11067 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11068 (when (and (setq value (org-get-tags-string))
11069 (string-match "\\S-" value))
11070 (push (cons "TAGS" value) props))
11071 (when (setq value (org-get-tags-at))
11072 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11073 props))
11074 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11075 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11076 string (if (equal key clockstr)
11077 (org-no-properties
11078 (org-trim
11079 (buffer-substring
11080 (match-beginning 3) (goto-char (point-at-eol)))))
11081 (substring (org-match-string-no-properties 3) 1 -1)))
11082 (unless key
11083 (if (= (char-after (match-beginning 3)) ?\[)
11084 (setq key "TIMESTAMP_IA")
11085 (setq key "TIMESTAMP")))
11086 (when (or (equal key clockstr) (not (assoc key props)))
11087 (push (cons key string) props)))
11091 (when (memq which '(all standard))
11092 ;; Get the standard properties, like :PROP: ...
11093 (setq range (org-get-property-block beg end))
11094 (when range
11095 (goto-char (car range))
11096 (while (re-search-forward
11097 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11098 (cdr range) t)
11099 (setq key (org-match-string-no-properties 1)
11100 value (org-trim (or (org-match-string-no-properties 2) "")))
11101 (unless (member key excluded)
11102 (push (cons key (or value "")) props)))))
11103 (if clocksum
11104 (push (cons "CLOCKSUM"
11105 (org-columns-number-to-string (/ (float clocksum) 60.)
11106 'add_times))
11107 props))
11108 (unless (assoc "CATEGORY" props)
11109 (setq value (or (org-get-category)
11110 (progn (org-refresh-category-properties)
11111 (org-get-category))))
11112 (push (cons "CATEGORY" value) props))
11113 (append sum-props (nreverse props)))))))
11115 (defun org-entry-get (pom property &optional inherit)
11116 "Get value of PROPERTY for entry at point-or-marker POM.
11117 If INHERIT is non-nil and the entry does not have the property,
11118 then also check higher levels of the hierarchy.
11119 If INHERIT is the symbol `selective', use inheritance only if the setting
11120 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11121 If the property is present but empty, the return value is the empty string.
11122 If the property is not present at all, nil is returned."
11123 (org-with-point-at pom
11124 (if (and inherit (if (eq inherit 'selective)
11125 (org-property-inherit-p property)
11127 (org-entry-get-with-inheritance property)
11128 (if (member property org-special-properties)
11129 ;; We need a special property. Use brute force, get all properties.
11130 (cdr (assoc property (org-entry-properties nil 'special)))
11131 (let ((range (org-get-property-block)))
11132 (if (and range
11133 (goto-char (car range))
11134 (re-search-forward
11135 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11136 (cdr range) t))
11137 ;; Found the property, return it.
11138 (if (match-end 1)
11139 (org-match-string-no-properties 1)
11140 "")))))))
11142 (defun org-property-or-variable-value (var &optional inherit)
11143 "Check if there is a property fixing the value of VAR.
11144 If yes, return this value. If not, return the current value of the variable."
11145 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11146 (if (and prop (stringp prop) (string-match "\\S-" prop))
11147 (read prop)
11148 (symbol-value var))))
11150 (defun org-entry-delete (pom property)
11151 "Delete the property PROPERTY from entry at point-or-marker POM."
11152 (org-with-point-at pom
11153 (if (member property org-special-properties)
11154 nil ; cannot delete these properties.
11155 (let ((range (org-get-property-block)))
11156 (if (and range
11157 (goto-char (car range))
11158 (re-search-forward
11159 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11160 (cdr range) t))
11161 (progn
11162 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11164 nil)))))
11166 ;; Multi-values properties are properties that contain multiple values
11167 ;; These values are assumed to be single words, separated by whitespace.
11168 (defun org-entry-add-to-multivalued-property (pom property value)
11169 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11170 (let* ((old (org-entry-get pom property))
11171 (values (and old (org-split-string old "[ \t]"))))
11172 (setq value (org-entry-protect-space value))
11173 (unless (member value values)
11174 (setq values (cons value values))
11175 (org-entry-put pom property
11176 (mapconcat 'identity values " ")))))
11178 (defun org-entry-remove-from-multivalued-property (pom property value)
11179 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11180 (let* ((old (org-entry-get pom property))
11181 (values (and old (org-split-string old "[ \t]"))))
11182 (setq value (org-entry-protect-space value))
11183 (when (member value values)
11184 (setq values (delete value values))
11185 (org-entry-put pom property
11186 (mapconcat 'identity values " ")))))
11188 (defun org-entry-member-in-multivalued-property (pom property value)
11189 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11190 (let* ((old (org-entry-get pom property))
11191 (values (and old (org-split-string old "[ \t]"))))
11192 (setq value (org-entry-protect-space value))
11193 (member value values)))
11195 (defun org-entry-get-multivalued-property (pom property)
11196 "Return a list of values in a multivalued property."
11197 (let* ((value (org-entry-get pom property))
11198 (values (and value (org-split-string value "[ \t]"))))
11199 (mapcar 'org-entry-restore-space values)))
11201 (defun org-entry-put-multivalued-property (pom property &rest values)
11202 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11203 VALUES should be a list of strings. Spaces will be protected."
11204 (org-entry-put pom property
11205 (mapconcat 'org-entry-protect-space values " "))
11206 (let* ((value (org-entry-get pom property))
11207 (values (and value (org-split-string value "[ \t]"))))
11208 (mapcar 'org-entry-restore-space values)))
11210 (defun org-entry-protect-space (s)
11211 "Protect spaces and newline in string S."
11212 (while (string-match " " s)
11213 (setq s (replace-match "%20" t t s)))
11214 (while (string-match "\n" s)
11215 (setq s (replace-match "%0A" t t s)))
11218 (defun org-entry-restore-space (s)
11219 "Restore spaces and newline in string S."
11220 (while (string-match "%20" s)
11221 (setq s (replace-match " " t t s)))
11222 (while (string-match "%0A" s)
11223 (setq s (replace-match "\n" t t s)))
11226 (defvar org-entry-property-inherited-from (make-marker)
11227 "Marker pointing to the entry from where a property was inherited.
11228 Each call to `org-entry-get-with-inheritance' will set this marker to the
11229 location of the entry where the inheritance search matched. If there was
11230 no match, the marker will point nowhere.
11231 Note that also `org-entry-get' calls this function, if the INHERIT flag
11232 is set.")
11234 (defun org-entry-get-with-inheritance (property)
11235 "Get entry property, and search higher levels if not present."
11236 (move-marker org-entry-property-inherited-from nil)
11237 (let (tmp)
11238 (save-excursion
11239 (save-restriction
11240 (widen)
11241 (catch 'ex
11242 (while t
11243 (when (setq tmp (org-entry-get nil property))
11244 (org-back-to-heading t)
11245 (move-marker org-entry-property-inherited-from (point))
11246 (throw 'ex tmp))
11247 (or (org-up-heading-safe) (throw 'ex nil)))))
11248 (or tmp
11249 (cdr (assoc property org-file-properties))
11250 (cdr (assoc property org-global-properties))
11251 (cdr (assoc property org-global-properties-fixed))))))
11253 (defun org-entry-put (pom property value)
11254 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11255 (org-with-point-at pom
11256 (org-back-to-heading t)
11257 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11258 range)
11259 (cond
11260 ((equal property "TODO")
11261 (when (and (stringp value) (string-match "\\S-" value)
11262 (not (member value org-todo-keywords-1)))
11263 (error "\"%s\" is not a valid TODO state" value))
11264 (if (or (not value)
11265 (not (string-match "\\S-" value)))
11266 (setq value 'none))
11267 (org-todo value)
11268 (org-set-tags nil 'align))
11269 ((equal property "PRIORITY")
11270 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11271 (string-to-char value) ?\ ))
11272 (org-set-tags nil 'align))
11273 ((equal property "SCHEDULED")
11274 (if (re-search-forward org-scheduled-time-regexp end t)
11275 (cond
11276 ((eq value 'earlier) (org-timestamp-change -1 'day))
11277 ((eq value 'later) (org-timestamp-change 1 'day))
11278 (t (call-interactively 'org-schedule)))
11279 (call-interactively 'org-schedule)))
11280 ((equal property "DEADLINE")
11281 (if (re-search-forward org-deadline-time-regexp end t)
11282 (cond
11283 ((eq value 'earlier) (org-timestamp-change -1 'day))
11284 ((eq value 'later) (org-timestamp-change 1 'day))
11285 (t (call-interactively 'org-deadline)))
11286 (call-interactively 'org-deadline)))
11287 ((member property org-special-properties)
11288 (error "The %s property can not yet be set with `org-entry-put'"
11289 property))
11290 (t ; a non-special property
11291 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11292 (setq range (org-get-property-block beg end 'force))
11293 (goto-char (car range))
11294 (if (re-search-forward
11295 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11296 (progn
11297 (delete-region (match-beginning 1) (match-end 1))
11298 (goto-char (match-beginning 1)))
11299 (goto-char (cdr range))
11300 (insert "\n")
11301 (backward-char 1)
11302 (org-indent-line-function)
11303 (insert ":" property ":"))
11304 (and value (insert " " value))
11305 (org-indent-line-function)))))))
11307 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11308 "Get all property keys in the current buffer.
11309 With INCLUDE-SPECIALS, also list the special properties that reflect things
11310 like tags and TODO state.
11311 With INCLUDE-DEFAULTS, also include properties that has special meaning
11312 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11313 With INCLUDE-COLUMNS, also include property names given in COLUMN
11314 formats in the current buffer."
11315 (let (rtn range cfmt s p)
11316 (save-excursion
11317 (save-restriction
11318 (widen)
11319 (goto-char (point-min))
11320 (while (re-search-forward org-property-start-re nil t)
11321 (setq range (org-get-property-block))
11322 (goto-char (car range))
11323 (while (re-search-forward
11324 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11325 (cdr range) t)
11326 (add-to-list 'rtn (org-match-string-no-properties 1)))
11327 (outline-next-heading))))
11329 (when include-specials
11330 (setq rtn (append org-special-properties rtn)))
11332 (when include-defaults
11333 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11335 (when include-columns
11336 (save-excursion
11337 (save-restriction
11338 (widen)
11339 (goto-char (point-min))
11340 (while (re-search-forward
11341 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11342 nil t)
11343 (setq cfmt (match-string 2) s 0)
11344 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11345 cfmt s)
11346 (setq s (match-end 0)
11347 p (match-string 1 cfmt))
11348 (unless (or (equal p "ITEM")
11349 (member p org-special-properties))
11350 (add-to-list 'rtn (match-string 1 cfmt))))))))
11352 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11354 (defun org-property-values (key)
11355 "Return a list of all values of property KEY."
11356 (save-excursion
11357 (save-restriction
11358 (widen)
11359 (goto-char (point-min))
11360 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11361 values)
11362 (while (re-search-forward re nil t)
11363 (add-to-list 'values (org-trim (match-string 1))))
11364 (delete "" values)))))
11366 (defun org-insert-property-drawer ()
11367 "Insert a property drawer into the current entry."
11368 (interactive)
11369 (org-back-to-heading t)
11370 (looking-at outline-regexp)
11371 (let ((indent (- (match-end 0)(match-beginning 0)))
11372 (beg (point))
11373 (re (concat "^[ \t]*" org-keyword-time-regexp))
11374 end hiddenp)
11375 (outline-next-heading)
11376 (setq end (point))
11377 (goto-char beg)
11378 (while (re-search-forward re end t))
11379 (setq hiddenp (org-invisible-p))
11380 (end-of-line 1)
11381 (and (equal (char-after) ?\n) (forward-char 1))
11382 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11383 (if (member (match-string 1) '("CLOCK:" ":END:"))
11384 ;; just skip this line
11385 (beginning-of-line 2)
11386 ;; Drawer start, find the end
11387 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11388 (beginning-of-line 1)))
11389 (org-skip-over-state-notes)
11390 (skip-chars-backward " \t\n\r")
11391 (if (eq (char-before) ?*) (forward-char 1))
11392 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11393 (beginning-of-line 0)
11394 (org-indent-to-column indent)
11395 (beginning-of-line 2)
11396 (org-indent-to-column indent)
11397 (beginning-of-line 0)
11398 (if hiddenp
11399 (save-excursion
11400 (org-back-to-heading t)
11401 (hide-entry))
11402 (org-flag-drawer t))))
11404 (defun org-set-property (property value)
11405 "In the current entry, set PROPERTY to VALUE.
11406 When called interactively, this will prompt for a property name, offering
11407 completion on existing and default properties. And then it will prompt
11408 for a value, offering completion either on allowed values (via an inherited
11409 xxx_ALL property) or on existing values in other instances of this property
11410 in the current file."
11411 (interactive
11412 (let* ((completion-ignore-case t)
11413 (keys (org-buffer-property-keys nil t t))
11414 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11415 (prop (if (member prop0 keys)
11416 prop0
11417 (or (cdr (assoc (downcase prop0)
11418 (mapcar (lambda (x) (cons (downcase x) x))
11419 keys)))
11420 prop0)))
11421 (cur (org-entry-get nil prop))
11422 (allowed (org-property-get-allowed-values nil prop 'table))
11423 (existing (mapcar 'list (org-property-values prop)))
11424 (val (if allowed
11425 (org-completing-read "Value: " allowed nil 'req-match)
11426 (let (org-completion-use-ido)
11427 (org-completing-read
11428 (concat "Value" (if (and cur (string-match "\\S-" cur))
11429 (concat "[" cur "]") "")
11430 ": ")
11431 existing nil nil "" nil cur)))))
11432 (list prop (if (equal val "") cur val))))
11433 (unless (equal (org-entry-get nil property) value)
11434 (org-entry-put nil property value)))
11436 (defun org-delete-property (property)
11437 "In the current entry, delete PROPERTY."
11438 (interactive
11439 (let* ((completion-ignore-case t)
11440 (prop (org-ido-completing-read
11441 "Property: " (org-entry-properties nil 'standard))))
11442 (list prop)))
11443 (message "Property %s %s" property
11444 (if (org-entry-delete nil property)
11445 "deleted"
11446 "was not present in the entry")))
11448 (defun org-delete-property-globally (property)
11449 "Remove PROPERTY globally, from all entries."
11450 (interactive
11451 (let* ((completion-ignore-case t)
11452 (prop (org-ido-completing-read
11453 "Globally remove property: "
11454 (mapcar 'list (org-buffer-property-keys)))))
11455 (list prop)))
11456 (save-excursion
11457 (save-restriction
11458 (widen)
11459 (goto-char (point-min))
11460 (let ((cnt 0))
11461 (while (re-search-forward
11462 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11463 nil t)
11464 (setq cnt (1+ cnt))
11465 (replace-match ""))
11466 (message "Property \"%s\" removed from %d entries" property cnt)))))
11468 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11470 (defun org-compute-property-at-point ()
11471 "Compute the property at point.
11472 This looks for an enclosing column format, extracts the operator and
11473 then applies it to the property in the column format's scope."
11474 (interactive)
11475 (unless (org-at-property-p)
11476 (error "Not at a property"))
11477 (let ((prop (org-match-string-no-properties 2)))
11478 (org-columns-get-format-and-top-level)
11479 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11480 (error "No operator defined for property %s" prop))
11481 (org-columns-compute prop)))
11483 (defun org-property-get-allowed-values (pom property &optional table)
11484 "Get allowed values for the property PROPERTY.
11485 When TABLE is non-nil, return an alist that can directly be used for
11486 completion."
11487 (let (vals)
11488 (cond
11489 ((equal property "TODO")
11490 (setq vals (org-with-point-at pom
11491 (append org-todo-keywords-1 '("")))))
11492 ((equal property "PRIORITY")
11493 (let ((n org-lowest-priority))
11494 (while (>= n org-highest-priority)
11495 (push (char-to-string n) vals)
11496 (setq n (1- n)))))
11497 ((member property org-special-properties))
11499 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11501 (when (and vals (string-match "\\S-" vals))
11502 (setq vals (car (read-from-string (concat "(" vals ")"))))
11503 (setq vals (mapcar (lambda (x)
11504 (cond ((stringp x) x)
11505 ((numberp x) (number-to-string x))
11506 ((symbolp x) (symbol-name x))
11507 (t "???")))
11508 vals)))))
11509 (if table (mapcar 'list vals) vals)))
11511 (defun org-property-previous-allowed-value (&optional previous)
11512 "Switch to the next allowed value for this property."
11513 (interactive)
11514 (org-property-next-allowed-value t))
11516 (defun org-property-next-allowed-value (&optional previous)
11517 "Switch to the next allowed value for this property."
11518 (interactive)
11519 (unless (org-at-property-p)
11520 (error "Not at a property"))
11521 (let* ((key (match-string 2))
11522 (value (match-string 3))
11523 (allowed (or (org-property-get-allowed-values (point) key)
11524 (and (member value '("[ ]" "[-]" "[X]"))
11525 '("[ ]" "[X]"))))
11526 nval)
11527 (unless allowed
11528 (error "Allowed values for this property have not been defined"))
11529 (if previous (setq allowed (reverse allowed)))
11530 (if (member value allowed)
11531 (setq nval (car (cdr (member value allowed)))))
11532 (setq nval (or nval (car allowed)))
11533 (if (equal nval value)
11534 (error "Only one allowed value for this property"))
11535 (org-at-property-p)
11536 (replace-match (concat " :" key ": " nval) t t)
11537 (org-indent-line-function)
11538 (beginning-of-line 1)
11539 (skip-chars-forward " \t")))
11541 (defun org-find-entry-with-id (ident)
11542 "Locate the entry that contains the ID property with exact value IDENT.
11543 IDENT can be a string, a symbol or a number, this function will search for
11544 the string representation of it.
11545 Return the position where this entry starts, or nil if there is no such entry."
11546 (interactive "sID: ")
11547 (let ((id (cond
11548 ((stringp ident) ident)
11549 ((symbol-name ident) (symbol-name ident))
11550 ((numberp ident) (number-to-string ident))
11551 (t (error "IDENT %s must be a string, symbol or number" ident))))
11552 (case-fold-search nil))
11553 (save-excursion
11554 (save-restriction
11555 (widen)
11556 (goto-char (point-min))
11557 (when (re-search-forward
11558 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11559 nil t)
11560 (org-back-to-heading)
11561 (point))))))
11563 ;;;; Timestamps
11565 (defvar org-last-changed-timestamp nil)
11566 (defvar org-last-inserted-timestamp nil
11567 "The last time stamp inserted with `org-insert-time-stamp'.")
11568 (defvar org-time-was-given) ; dynamically scoped parameter
11569 (defvar org-end-time-was-given) ; dynamically scoped parameter
11570 (defvar org-ts-what) ; dynamically scoped parameter
11572 (defun org-time-stamp (arg &optional inactive)
11573 "Prompt for a date/time and insert a time stamp.
11574 If the user specifies a time like HH:MM, or if this command is called
11575 with a prefix argument, the time stamp will contain date and time.
11576 Otherwise, only the date will be included. All parts of a date not
11577 specified by the user will be filled in from the current date/time.
11578 So if you press just return without typing anything, the time stamp
11579 will represent the current date/time. If there is already a timestamp
11580 at the cursor, it will be modified."
11581 (interactive "P")
11582 (let* ((ts nil)
11583 (default-time
11584 ;; Default time is either today, or, when entering a range,
11585 ;; the range start.
11586 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11587 (save-excursion
11588 (re-search-backward
11589 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11590 (- (point) 20) t)))
11591 (apply 'encode-time (org-parse-time-string (match-string 1)))
11592 (current-time)))
11593 (default-input (and ts (org-get-compact-tod ts)))
11594 org-time-was-given org-end-time-was-given time)
11595 (cond
11596 ((and (org-at-timestamp-p t)
11597 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11598 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11599 (insert "--")
11600 (setq time (let ((this-command this-command))
11601 (org-read-date arg 'totime nil nil
11602 default-time default-input)))
11603 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11604 ((org-at-timestamp-p t)
11605 (setq time (let ((this-command this-command))
11606 (org-read-date arg 'totime nil nil default-time default-input)))
11607 (when (org-at-timestamp-p t) ; just to get the match data
11608 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11609 (replace-match "")
11610 (setq org-last-changed-timestamp
11611 (org-insert-time-stamp
11612 time (or org-time-was-given arg)
11613 inactive nil nil (list org-end-time-was-given))))
11614 (message "Timestamp updated"))
11616 (setq time (let ((this-command this-command))
11617 (org-read-date arg 'totime nil nil default-time default-input)))
11618 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11619 nil nil (list org-end-time-was-given))))))
11621 ;; FIXME: can we use this for something else, like computing time differences?
11622 (defun org-get-compact-tod (s)
11623 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11624 (let* ((t1 (match-string 1 s))
11625 (h1 (string-to-number (match-string 2 s)))
11626 (m1 (string-to-number (match-string 3 s)))
11627 (t2 (and (match-end 4) (match-string 5 s)))
11628 (h2 (and t2 (string-to-number (match-string 6 s))))
11629 (m2 (and t2 (string-to-number (match-string 7 s))))
11630 dh dm)
11631 (if (not t2)
11633 (setq dh (- h2 h1) dm (- m2 m1))
11634 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11635 (concat t1 "+" (number-to-string dh)
11636 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11638 (defun org-time-stamp-inactive (&optional arg)
11639 "Insert an inactive time stamp.
11640 An inactive time stamp is enclosed in square brackets instead of angle
11641 brackets. It is inactive in the sense that it does not trigger agenda entries,
11642 does not link to the calendar and cannot be changed with the S-cursor keys.
11643 So these are more for recording a certain time/date."
11644 (interactive "P")
11645 (org-time-stamp arg 'inactive))
11647 (defvar org-date-ovl (org-make-overlay 1 1))
11648 (org-overlay-put org-date-ovl 'face 'org-warning)
11649 (org-detach-overlay org-date-ovl)
11651 (defvar org-ans1) ; dynamically scoped parameter
11652 (defvar org-ans2) ; dynamically scoped parameter
11654 (defvar org-plain-time-of-day-regexp) ; defined below
11656 (defvar org-overriding-default-time nil) ; dynamically scoped
11657 (defvar org-read-date-overlay nil)
11658 (defvar org-dcst nil) ; dynamically scoped
11659 (defvar org-read-date-history nil)
11661 (defun org-read-date (&optional with-time to-time from-string prompt
11662 default-time default-input)
11663 "Read a date, possibly a time, and make things smooth for the user.
11664 The prompt will suggest to enter an ISO date, but you can also enter anything
11665 which will at least partially be understood by `parse-time-string'.
11666 Unrecognized parts of the date will default to the current day, month, year,
11667 hour and minute. If this command is called to replace a timestamp at point,
11668 of to enter the second timestamp of a range, the default time is taken from the
11669 existing stamp. For example,
11670 3-2-5 --> 2003-02-05
11671 feb 15 --> currentyear-02-15
11672 sep 12 9 --> 2009-09-12
11673 12:45 --> today 12:45
11674 22 sept 0:34 --> currentyear-09-22 0:34
11675 12 --> currentyear-currentmonth-12
11676 Fri --> nearest Friday (today or later)
11677 etc.
11679 Furthermore you can specify a relative date by giving, as the *first* thing
11680 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11681 change in days weeks, months, years.
11682 With a single plus or minus, the date is relative to today. With a double
11683 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11684 +4d --> four days from today
11685 +4 --> same as above
11686 +2w --> two weeks from today
11687 ++5 --> five days from default date
11689 The function understands only English month and weekday abbreviations,
11690 but this can be configured with the variables `parse-time-months' and
11691 `parse-time-weekdays'.
11693 While prompting, a calendar is popped up - you can also select the
11694 date with the mouse (button 1). The calendar shows a period of three
11695 months. To scroll it to other months, use the keys `>' and `<'.
11696 If you don't like the calendar, turn it off with
11697 \(setq org-read-date-popup-calendar nil)
11699 With optional argument TO-TIME, the date will immediately be converted
11700 to an internal time.
11701 With an optional argument WITH-TIME, the prompt will suggest to also
11702 insert a time. Note that when WITH-TIME is not set, you can still
11703 enter a time, and this function will inform the calling routine about
11704 this change. The calling routine may then choose to change the format
11705 used to insert the time stamp into the buffer to include the time.
11706 With optional argument FROM-STRING, read from this string instead from
11707 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11708 the time/date that is used for everything that is not specified by the
11709 user."
11710 (require 'parse-time)
11711 (let* ((org-time-stamp-rounding-minutes
11712 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11713 (org-dcst org-display-custom-times)
11714 (ct (org-current-time))
11715 (def (or org-overriding-default-time default-time ct))
11716 (defdecode (decode-time def))
11717 (dummy (progn
11718 (when (< (nth 2 defdecode) org-extend-today-until)
11719 (setcar (nthcdr 2 defdecode) -1)
11720 (setcar (nthcdr 1 defdecode) 59)
11721 (setq def (apply 'encode-time defdecode)
11722 defdecode (decode-time def)))))
11723 (calendar-move-hook nil)
11724 (calendar-view-diary-initially-flag nil)
11725 (view-diary-entries-initially nil)
11726 (calendar-view-holidays-initially-flag nil)
11727 (view-calendar-holidays-initially nil)
11728 (timestr (format-time-string
11729 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11730 (prompt (concat (if prompt (concat prompt " ") "")
11731 (format "Date+time [%s]: " timestr)))
11732 ans (org-ans0 "") org-ans1 org-ans2 final)
11734 (cond
11735 (from-string (setq ans from-string))
11736 (org-read-date-popup-calendar
11737 (save-excursion
11738 (save-window-excursion
11739 (calendar)
11740 (calendar-forward-day (- (time-to-days def)
11741 (calendar-absolute-from-gregorian
11742 (calendar-current-date))))
11743 (org-eval-in-calendar nil t)
11744 (let* ((old-map (current-local-map))
11745 (map (copy-keymap calendar-mode-map))
11746 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11747 (org-defkey map (kbd "RET") 'org-calendar-select)
11748 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11749 'org-calendar-select-mouse)
11750 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11751 'org-calendar-select-mouse)
11752 (org-defkey minibuffer-local-map [(meta shift left)]
11753 (lambda () (interactive)
11754 (org-eval-in-calendar '(calendar-backward-month 1))))
11755 (org-defkey minibuffer-local-map [(meta shift right)]
11756 (lambda () (interactive)
11757 (org-eval-in-calendar '(calendar-forward-month 1))))
11758 (org-defkey minibuffer-local-map [(meta shift up)]
11759 (lambda () (interactive)
11760 (org-eval-in-calendar '(calendar-backward-year 1))))
11761 (org-defkey minibuffer-local-map [(meta shift down)]
11762 (lambda () (interactive)
11763 (org-eval-in-calendar '(calendar-forward-year 1))))
11764 (org-defkey minibuffer-local-map [(shift up)]
11765 (lambda () (interactive)
11766 (org-eval-in-calendar '(calendar-backward-week 1))))
11767 (org-defkey minibuffer-local-map [(shift down)]
11768 (lambda () (interactive)
11769 (org-eval-in-calendar '(calendar-forward-week 1))))
11770 (org-defkey minibuffer-local-map [(shift left)]
11771 (lambda () (interactive)
11772 (org-eval-in-calendar '(calendar-backward-day 1))))
11773 (org-defkey minibuffer-local-map [(shift right)]
11774 (lambda () (interactive)
11775 (org-eval-in-calendar '(calendar-forward-day 1))))
11776 (org-defkey minibuffer-local-map ">"
11777 (lambda () (interactive)
11778 (org-eval-in-calendar '(scroll-calendar-left 1))))
11779 (org-defkey minibuffer-local-map "<"
11780 (lambda () (interactive)
11781 (org-eval-in-calendar '(scroll-calendar-right 1))))
11782 (run-hooks 'org-read-date-minibuffer-setup-hook)
11783 (unwind-protect
11784 (progn
11785 (use-local-map map)
11786 (add-hook 'post-command-hook 'org-read-date-display)
11787 (setq org-ans0 (read-string prompt default-input
11788 'org-read-date-history nil))
11789 ;; org-ans0: from prompt
11790 ;; org-ans1: from mouse click
11791 ;; org-ans2: from calendar motion
11792 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11793 (remove-hook 'post-command-hook 'org-read-date-display)
11794 (use-local-map old-map)
11795 (when org-read-date-overlay
11796 (org-delete-overlay org-read-date-overlay)
11797 (setq org-read-date-overlay nil)))))))
11799 (t ; Naked prompt only
11800 (unwind-protect
11801 (setq ans (read-string prompt default-input
11802 'org-read-date-history timestr))
11803 (when org-read-date-overlay
11804 (org-delete-overlay org-read-date-overlay)
11805 (setq org-read-date-overlay nil)))))
11807 (setq final (org-read-date-analyze ans def defdecode))
11809 (if to-time
11810 (apply 'encode-time final)
11811 (if (and (boundp 'org-time-was-given) org-time-was-given)
11812 (format "%04d-%02d-%02d %02d:%02d"
11813 (nth 5 final) (nth 4 final) (nth 3 final)
11814 (nth 2 final) (nth 1 final))
11815 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11816 (defvar def)
11817 (defvar defdecode)
11818 (defvar with-time)
11819 (defun org-read-date-display ()
11820 "Display the current date prompt interpretation in the minibuffer."
11821 (when org-read-date-display-live
11822 (when org-read-date-overlay
11823 (org-delete-overlay org-read-date-overlay))
11824 (let ((p (point)))
11825 (end-of-line 1)
11826 (while (not (equal (buffer-substring
11827 (max (point-min) (- (point) 4)) (point))
11828 " "))
11829 (insert " "))
11830 (goto-char p))
11831 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11832 " " (or org-ans1 org-ans2)))
11833 (org-end-time-was-given nil)
11834 (f (org-read-date-analyze ans def defdecode))
11835 (fmts (if org-dcst
11836 org-time-stamp-custom-formats
11837 org-time-stamp-formats))
11838 (fmt (if (or with-time
11839 (and (boundp 'org-time-was-given) org-time-was-given))
11840 (cdr fmts)
11841 (car fmts)))
11842 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11843 (when (and org-end-time-was-given
11844 (string-match org-plain-time-of-day-regexp txt))
11845 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11846 org-end-time-was-given
11847 (substring txt (match-end 0)))))
11848 (setq org-read-date-overlay
11849 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11850 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11852 (defun org-read-date-analyze (ans def defdecode)
11853 "Analyse the combined answer of the date prompt."
11854 ;; FIXME: cleanup and comment
11855 (let (delta deltan deltaw deltadef year month day
11856 hour minute second wday pm h2 m2 tl wday1
11857 iso-year iso-weekday iso-week iso-year iso-date)
11859 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11860 (setq ans "+0"))
11862 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11863 (setq ans (replace-match "" t t ans)
11864 deltan (car delta)
11865 deltaw (nth 1 delta)
11866 deltadef (nth 2 delta)))
11868 ;; Check if there is an iso week date in there
11869 ;; If yes, sore the info and postpone interpreting it until the rest
11870 ;; of the parsing is done
11871 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11872 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11873 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11874 iso-week (string-to-number (match-string 2 ans)))
11875 (setq ans (replace-match "" t t ans)))
11877 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11878 (when (string-match
11879 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11880 (setq year (if (match-end 2)
11881 (string-to-number (match-string 2 ans))
11882 (string-to-number (format-time-string "%Y")))
11883 month (string-to-number (match-string 3 ans))
11884 day (string-to-number (match-string 4 ans)))
11885 (if (< year 100) (setq year (+ 2000 year)))
11886 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11887 t nil ans)))
11888 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11889 ;; If there is a time with am/pm, and *no* time without it, we convert
11890 ;; so that matching will be successful.
11891 (loop for i from 1 to 2 do ; twice, for end time as well
11892 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11893 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11894 (setq hour (string-to-number (match-string 1 ans))
11895 minute (if (match-end 3)
11896 (string-to-number (match-string 3 ans))
11898 pm (equal ?p
11899 (string-to-char (downcase (match-string 4 ans)))))
11900 (if (and (= hour 12) (not pm))
11901 (setq hour 0)
11902 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11903 (setq ans (replace-match (format "%02d:%02d" hour minute)
11904 t t ans))))
11906 ;; Check if a time range is given as a duration
11907 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11908 (setq hour (string-to-number (match-string 1 ans))
11909 h2 (+ hour (string-to-number (match-string 3 ans)))
11910 minute (string-to-number (match-string 2 ans))
11911 m2 (+ minute (if (match-end 5) (string-to-number
11912 (match-string 5 ans))0)))
11913 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11914 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11915 t t ans)))
11917 ;; Check if there is a time range
11918 (when (boundp 'org-end-time-was-given)
11919 (setq org-time-was-given nil)
11920 (when (and (string-match org-plain-time-of-day-regexp ans)
11921 (match-end 8))
11922 (setq org-end-time-was-given (match-string 8 ans))
11923 (setq ans (concat (substring ans 0 (match-beginning 7))
11924 (substring ans (match-end 7))))))
11926 (setq tl (parse-time-string ans)
11927 day (or (nth 3 tl) (nth 3 defdecode))
11928 month (or (nth 4 tl)
11929 (if (and org-read-date-prefer-future
11930 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11931 (1+ (nth 4 defdecode))
11932 (nth 4 defdecode)))
11933 year (or (nth 5 tl)
11934 (if (and org-read-date-prefer-future
11935 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11936 (1+ (nth 5 defdecode))
11937 (nth 5 defdecode)))
11938 hour (or (nth 2 tl) (nth 2 defdecode))
11939 minute (or (nth 1 tl) (nth 1 defdecode))
11940 second (or (nth 0 tl) 0)
11941 wday (nth 6 tl))
11943 ;; Special date definitions below
11944 (cond
11945 (iso-week
11946 ;; There was an iso week
11947 (setq year (or iso-year year)
11948 day (or iso-weekday wday 1)
11949 wday nil ; to make sure that the trigger below does not match
11950 iso-date (calendar-gregorian-from-absolute
11951 (calendar-absolute-from-iso
11952 (list iso-week day year))))
11953 ; FIXME: Should we also push ISO weeks into the future?
11954 ; (when (and org-read-date-prefer-future
11955 ; (not iso-year)
11956 ; (< (calendar-absolute-from-gregorian iso-date)
11957 ; (time-to-days (current-time))))
11958 ; (setq year (1+ year)
11959 ; iso-date (calendar-gregorian-from-absolute
11960 ; (calendar-absolute-from-iso
11961 ; (list iso-week day year)))))
11962 (setq month (car iso-date)
11963 year (nth 2 iso-date)
11964 day (nth 1 iso-date)))
11965 (deltan
11966 (unless deltadef
11967 (let ((now (decode-time (current-time))))
11968 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11969 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11970 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11971 ((equal deltaw "m") (setq month (+ month deltan)))
11972 ((equal deltaw "y") (setq year (+ year deltan)))))
11973 ((and wday (not (nth 3 tl)))
11974 ;; Weekday was given, but no day, so pick that day in the week
11975 ;; on or after the derived date.
11976 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11977 (unless (equal wday wday1)
11978 (setq day (+ day (% (- wday wday1 -7) 7))))))
11979 (if (and (boundp 'org-time-was-given)
11980 (nth 2 tl))
11981 (setq org-time-was-given t))
11982 (if (< year 100) (setq year (+ 2000 year)))
11983 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11984 (list second minute hour day month year)))
11986 (defvar parse-time-weekdays)
11988 (defun org-read-date-get-relative (s today default)
11989 "Check string S for special relative date string.
11990 TODAY and DEFAULT are internal times, for today and for a default.
11991 Return shift list (N what def-flag)
11992 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11993 N is the number of WHATs to shift.
11994 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11995 the DEFAULT date rather than TODAY."
11996 (when (and
11997 (string-match
11998 (concat
11999 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12000 "\\([0-9]+\\)?"
12001 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12002 "\\([ \t]\\|$\\)") s)
12003 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12004 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12005 (string-to-char (substring (match-string 1 s) -1))
12006 ?+))
12007 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12008 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12009 (what (if (match-end 3) (match-string 3 s) "d"))
12010 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12011 (date (if rel default today))
12012 (wday (nth 6 (decode-time date)))
12013 delta)
12014 (if wday1
12015 (progn
12016 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12017 (if (= dir ?-) (setq delta (- delta 7)))
12018 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12019 (list delta "d" rel))
12020 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12022 (defun org-eval-in-calendar (form &optional keepdate)
12023 "Eval FORM in the calendar window and return to current window.
12024 Also, store the cursor date in variable org-ans2."
12025 (let ((sw (selected-window)))
12026 (select-window (get-buffer-window "*Calendar*"))
12027 (eval form)
12028 (when (and (not keepdate) (calendar-cursor-to-date))
12029 (let* ((date (calendar-cursor-to-date))
12030 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12031 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12032 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12033 (select-window sw)))
12035 (defun org-calendar-select ()
12036 "Return to `org-read-date' with the date currently selected.
12037 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12038 (interactive)
12039 (when (calendar-cursor-to-date)
12040 (let* ((date (calendar-cursor-to-date))
12041 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12042 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12043 (if (active-minibuffer-window) (exit-minibuffer))))
12045 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12046 "Insert a date stamp for the date given by the internal TIME.
12047 WITH-HM means, use the stamp format that includes the time of the day.
12048 INACTIVE means use square brackets instead of angular ones, so that the
12049 stamp will not contribute to the agenda.
12050 PRE and POST are optional strings to be inserted before and after the
12051 stamp.
12052 The command returns the inserted time stamp."
12053 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12054 stamp)
12055 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12056 (insert-before-markers (or pre ""))
12057 (insert-before-markers (setq stamp (format-time-string fmt time)))
12058 (when (listp extra)
12059 (setq extra (car extra))
12060 (if (and (stringp extra)
12061 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12062 (setq extra (format "-%02d:%02d"
12063 (string-to-number (match-string 1 extra))
12064 (string-to-number (match-string 2 extra))))
12065 (setq extra nil)))
12066 (when extra
12067 (backward-char 1)
12068 (insert-before-markers extra)
12069 (forward-char 1))
12070 (insert-before-markers (or post ""))
12071 (setq org-last-inserted-timestamp stamp)))
12073 (defun org-toggle-time-stamp-overlays ()
12074 "Toggle the use of custom time stamp formats."
12075 (interactive)
12076 (setq org-display-custom-times (not org-display-custom-times))
12077 (unless org-display-custom-times
12078 (let ((p (point-min)) (bmp (buffer-modified-p)))
12079 (while (setq p (next-single-property-change p 'display))
12080 (if (and (get-text-property p 'display)
12081 (eq (get-text-property p 'face) 'org-date))
12082 (remove-text-properties
12083 p (setq p (next-single-property-change p 'display))
12084 '(display t))))
12085 (set-buffer-modified-p bmp)))
12086 (if (featurep 'xemacs)
12087 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12088 (org-restart-font-lock)
12089 (setq org-table-may-need-update t)
12090 (if org-display-custom-times
12091 (message "Time stamps are overlayed with custom format")
12092 (message "Time stamp overlays removed")))
12094 (defun org-display-custom-time (beg end)
12095 "Overlay modified time stamp format over timestamp between BEG and END."
12096 (let* ((ts (buffer-substring beg end))
12097 t1 w1 with-hm tf time str w2 (off 0))
12098 (save-match-data
12099 (setq t1 (org-parse-time-string ts t))
12100 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12101 (setq off (- (match-end 0) (match-beginning 0)))))
12102 (setq end (- end off))
12103 (setq w1 (- end beg)
12104 with-hm (and (nth 1 t1) (nth 2 t1))
12105 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12106 time (org-fix-decoded-time t1)
12107 str (org-add-props
12108 (format-time-string
12109 (substring tf 1 -1) (apply 'encode-time time))
12110 nil 'mouse-face 'highlight)
12111 w2 (length str))
12112 (if (not (= w2 w1))
12113 (add-text-properties (1+ beg) (+ 2 beg)
12114 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12115 (if (featurep 'xemacs)
12116 (progn
12117 (put-text-property beg end 'invisible t)
12118 (put-text-property beg end 'end-glyph (make-glyph str)))
12119 (put-text-property beg end 'display str))))
12121 (defun org-translate-time (string)
12122 "Translate all timestamps in STRING to custom format.
12123 But do this only if the variable `org-display-custom-times' is set."
12124 (when org-display-custom-times
12125 (save-match-data
12126 (let* ((start 0)
12127 (re org-ts-regexp-both)
12128 t1 with-hm inactive tf time str beg end)
12129 (while (setq start (string-match re string start))
12130 (setq beg (match-beginning 0)
12131 end (match-end 0)
12132 t1 (save-match-data
12133 (org-parse-time-string (substring string beg end) t))
12134 with-hm (and (nth 1 t1) (nth 2 t1))
12135 inactive (equal (substring string beg (1+ beg)) "[")
12136 tf (funcall (if with-hm 'cdr 'car)
12137 org-time-stamp-custom-formats)
12138 time (org-fix-decoded-time t1)
12139 str (format-time-string
12140 (concat
12141 (if inactive "[" "<") (substring tf 1 -1)
12142 (if inactive "]" ">"))
12143 (apply 'encode-time time))
12144 string (replace-match str t t string)
12145 start (+ start (length str)))))))
12146 string)
12148 (defun org-fix-decoded-time (time)
12149 "Set 0 instead of nil for the first 6 elements of time.
12150 Don't touch the rest."
12151 (let ((n 0))
12152 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12154 (defun org-days-to-time (timestamp-string)
12155 "Difference between TIMESTAMP-STRING and now in days."
12156 (- (time-to-days (org-time-string-to-time timestamp-string))
12157 (time-to-days (current-time))))
12159 (defun org-deadline-close (timestamp-string &optional ndays)
12160 "Is the time in TIMESTAMP-STRING close to the current date?"
12161 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12162 (and (< (org-days-to-time timestamp-string) ndays)
12163 (not (org-entry-is-done-p))))
12165 (defun org-get-wdays (ts)
12166 "Get the deadline lead time appropriate for timestring TS."
12167 (cond
12168 ((<= org-deadline-warning-days 0)
12169 ;; 0 or negative, enforce this value no matter what
12170 (- org-deadline-warning-days))
12171 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12172 ;; lead time is specified.
12173 (floor (* (string-to-number (match-string 1 ts))
12174 (cdr (assoc (match-string 2 ts)
12175 '(("d" . 1) ("w" . 7)
12176 ("m" . 30.4) ("y" . 365.25)))))))
12177 ;; go for the default.
12178 (t org-deadline-warning-days)))
12180 (defun org-calendar-select-mouse (ev)
12181 "Return to `org-read-date' with the date currently selected.
12182 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12183 (interactive "e")
12184 (mouse-set-point ev)
12185 (when (calendar-cursor-to-date)
12186 (let* ((date (calendar-cursor-to-date))
12187 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12188 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12189 (if (active-minibuffer-window) (exit-minibuffer))))
12191 (defun org-check-deadlines (ndays)
12192 "Check if there are any deadlines due or past due.
12193 A deadline is considered due if it happens within `org-deadline-warning-days'
12194 days from today's date. If the deadline appears in an entry marked DONE,
12195 it is not shown. The prefix arg NDAYS can be used to test that many
12196 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12197 (interactive "P")
12198 (let* ((org-warn-days
12199 (cond
12200 ((equal ndays '(4)) 100000)
12201 (ndays (prefix-numeric-value ndays))
12202 (t (abs org-deadline-warning-days))))
12203 (case-fold-search nil)
12204 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12205 (callback
12206 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12208 (message "%d deadlines past-due or due within %d days"
12209 (org-occur regexp nil callback)
12210 org-warn-days)))
12212 (defun org-check-before-date (date)
12213 "Check if there are deadlines or scheduled entries before DATE."
12214 (interactive (list (org-read-date)))
12215 (let ((case-fold-search nil)
12216 (regexp (concat "\\<\\(" org-deadline-string
12217 "\\|" org-scheduled-string
12218 "\\) *<\\([^>]+\\)>"))
12219 (callback
12220 (lambda () (time-less-p
12221 (org-time-string-to-time (match-string 2))
12222 (org-time-string-to-time date)))))
12223 (message "%d entries before %s"
12224 (org-occur regexp nil callback) date)))
12226 (defun org-check-after-date (date)
12227 "Check if there are deadlines or scheduled entries after DATE."
12228 (interactive (list (org-read-date)))
12229 (let ((case-fold-search nil)
12230 (regexp (concat "\\<\\(" org-deadline-string
12231 "\\|" org-scheduled-string
12232 "\\) *<\\([^>]+\\)>"))
12233 (callback
12234 (lambda () (not
12235 (time-less-p
12236 (org-time-string-to-time (match-string 2))
12237 (org-time-string-to-time date))))))
12238 (message "%d entries after %s"
12239 (org-occur regexp nil callback) date)))
12241 (defun org-evaluate-time-range (&optional to-buffer)
12242 "Evaluate a time range by computing the difference between start and end.
12243 Normally the result is just printed in the echo area, but with prefix arg
12244 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12245 If the time range is actually in a table, the result is inserted into the
12246 next column.
12247 For time difference computation, a year is assumed to be exactly 365
12248 days in order to avoid rounding problems."
12249 (interactive "P")
12251 (org-clock-update-time-maybe)
12252 (save-excursion
12253 (unless (org-at-date-range-p t)
12254 (goto-char (point-at-bol))
12255 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12256 (if (not (org-at-date-range-p t))
12257 (error "Not at a time-stamp range, and none found in current line")))
12258 (let* ((ts1 (match-string 1))
12259 (ts2 (match-string 2))
12260 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12261 (match-end (match-end 0))
12262 (time1 (org-time-string-to-time ts1))
12263 (time2 (org-time-string-to-time ts2))
12264 (t1 (time-to-seconds time1))
12265 (t2 (time-to-seconds time2))
12266 (diff (abs (- t2 t1)))
12267 (negative (< (- t2 t1) 0))
12268 ;; (ys (floor (* 365 24 60 60)))
12269 (ds (* 24 60 60))
12270 (hs (* 60 60))
12271 (fy "%dy %dd %02d:%02d")
12272 (fy1 "%dy %dd")
12273 (fd "%dd %02d:%02d")
12274 (fd1 "%dd")
12275 (fh "%02d:%02d")
12276 y d h m align)
12277 (if havetime
12278 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12280 d (floor (/ diff ds)) diff (mod diff ds)
12281 h (floor (/ diff hs)) diff (mod diff hs)
12282 m (floor (/ diff 60)))
12283 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12285 d (floor (+ (/ diff ds) 0.5))
12286 h 0 m 0))
12287 (if (not to-buffer)
12288 (message "%s" (org-make-tdiff-string y d h m))
12289 (if (org-at-table-p)
12290 (progn
12291 (goto-char match-end)
12292 (setq align t)
12293 (and (looking-at " *|") (goto-char (match-end 0))))
12294 (goto-char match-end))
12295 (if (looking-at
12296 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12297 (replace-match ""))
12298 (if negative (insert " -"))
12299 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12300 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12301 (insert " " (format fh h m))))
12302 (if align (org-table-align))
12303 (message "Time difference inserted")))))
12305 (defun org-make-tdiff-string (y d h m)
12306 (let ((fmt "")
12307 (l nil))
12308 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12309 l (push y l)))
12310 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12311 l (push d l)))
12312 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12313 l (push h l)))
12314 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12315 l (push m l)))
12316 (apply 'format fmt (nreverse l))))
12318 (defun org-time-string-to-time (s)
12319 (apply 'encode-time (org-parse-time-string s)))
12321 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12322 "Convert a time stamp to an absolute day number.
12323 If there is a specifyer for a cyclic time stamp, get the closest date to
12324 DAYNR.
12325 PREFER and SHOW-ALL are passed through to `org-closest-date'."
12326 (cond
12327 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12328 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12329 daynr
12330 (+ daynr 1000)))
12331 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12332 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12333 (time-to-days (current-time))) (match-string 0 s)
12334 prefer show-all))
12335 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12337 (defun org-days-to-iso-week (days)
12338 "Return the iso week number."
12339 (require 'cal-iso)
12340 (car (calendar-iso-from-absolute days)))
12342 (defun org-small-year-to-year (year)
12343 "Convert 2-digit years into 4-digit years.
12344 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12345 The year 2000 cannot be abbreviated. Any year larger than 99
12346 is returned unchanged."
12347 (if (< year 38)
12348 (setq year (+ 2000 year))
12349 (if (< year 100)
12350 (setq year (+ 1900 year))))
12351 year)
12353 (defun org-time-from-absolute (d)
12354 "Return the time corresponding to date D.
12355 D may be an absolute day number, or a calendar-type list (month day year)."
12356 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12357 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12359 (defun org-calendar-holiday ()
12360 "List of holidays, for Diary display in Org-mode."
12361 (require 'holidays)
12362 (let ((hl (funcall
12363 (if (fboundp 'calendar-check-holidays)
12364 'calendar-check-holidays 'check-calendar-holidays) date)))
12365 (if hl (mapconcat 'identity hl "; "))))
12367 (defun org-diary-sexp-entry (sexp entry date)
12368 "Process a SEXP diary ENTRY for DATE."
12369 (require 'diary-lib)
12370 (let ((result (if calendar-debug-sexp
12371 (let ((stack-trace-on-error t))
12372 (eval (car (read-from-string sexp))))
12373 (condition-case nil
12374 (eval (car (read-from-string sexp)))
12375 (error
12376 (beep)
12377 (message "Bad sexp at line %d in %s: %s"
12378 (org-current-line)
12379 (buffer-file-name) sexp)
12380 (sleep-for 2))))))
12381 (cond ((stringp result) result)
12382 ((and (consp result)
12383 (stringp (cdr result))) (cdr result))
12384 (result entry)
12385 (t nil))))
12387 (defun org-diary-to-ical-string (frombuf)
12388 "Get iCalendar entries from diary entries in buffer FROMBUF.
12389 This uses the icalendar.el library."
12390 (let* ((tmpdir (if (featurep 'xemacs)
12391 (temp-directory)
12392 temporary-file-directory))
12393 (tmpfile (make-temp-name
12394 (expand-file-name "orgics" tmpdir)))
12395 buf rtn b e)
12396 (save-excursion
12397 (set-buffer frombuf)
12398 (icalendar-export-region (point-min) (point-max) tmpfile)
12399 (setq buf (find-buffer-visiting tmpfile))
12400 (set-buffer buf)
12401 (goto-char (point-min))
12402 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12403 (setq b (match-beginning 0)))
12404 (goto-char (point-max))
12405 (if (re-search-backward "^END:VEVENT" nil t)
12406 (setq e (match-end 0)))
12407 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12408 (kill-buffer buf)
12409 (delete-file tmpfile)
12410 rtn))
12412 (defun org-closest-date (start current change prefer show-all)
12413 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12414 When PREFER is `past' return a date that is either CURRENT or past.
12415 When PREFER is `future', return a date that is either CURRENT or future.
12416 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12417 ;; Make the proper lists from the dates
12418 (catch 'exit
12419 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12420 dn dw sday cday n1 n2 n0
12421 d m y y1 y2 date1 date2 nmonths nm ny m2)
12423 (setq start (org-date-to-gregorian start)
12424 current (org-date-to-gregorian
12425 (if show-all
12426 current
12427 (time-to-days (current-time))))
12428 sday (calendar-absolute-from-gregorian start)
12429 cday (calendar-absolute-from-gregorian current))
12431 (if (<= cday sday) (throw 'exit sday))
12433 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12434 (setq dn (string-to-number (match-string 1 change))
12435 dw (cdr (assoc (match-string 2 change) a1)))
12436 (error "Invalid change specifyer: %s" change))
12437 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12438 (cond
12439 ((eq dw 'day)
12440 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12441 n2 (+ n1 dn)))
12442 ((eq dw 'year)
12443 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12444 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12445 (setq date1 (list m d y1)
12446 n1 (calendar-absolute-from-gregorian date1)
12447 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12448 n2 (calendar-absolute-from-gregorian date2)))
12449 ((eq dw 'month)
12450 ;; approx number of month between the two dates
12451 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12452 ;; How often does dn fit in there?
12453 (setq d (nth 1 start) m (car start) y (nth 2 start)
12454 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12455 m (+ m nm)
12456 ny (floor (/ m 12))
12457 y (+ y ny)
12458 m (- m (* ny 12)))
12459 (while (> m 12) (setq m (- m 12) y (1+ y)))
12460 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12461 (setq m2 (+ m dn) y2 y)
12462 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12463 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12464 (while (<= n2 cday)
12465 (setq n1 n2 m m2 y y2)
12466 (setq m2 (+ m dn) y2 y)
12467 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12468 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12469 ;; Make sure n1 is the earlier date
12470 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12471 (if show-all
12472 (cond
12473 ((eq prefer 'past) n1)
12474 ((eq prefer 'future) (if (= cday n1) n1 n2))
12475 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12476 (cond
12477 ((eq prefer 'past) n1)
12478 ((eq prefer 'future) (if (= cday n1) n1 n2))
12479 (t (if (= cday n1) n1 n2)))))))
12481 (defun org-date-to-gregorian (date)
12482 "Turn any specification of DATE into a gregorian date for the calendar."
12483 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12484 ((and (listp date) (= (length date) 3)) date)
12485 ((stringp date)
12486 (setq date (org-parse-time-string date))
12487 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12488 ((listp date)
12489 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12491 (defun org-parse-time-string (s &optional nodefault)
12492 "Parse the standard Org-mode time string.
12493 This should be a lot faster than the normal `parse-time-string'.
12494 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12495 hour and minute fields will be nil if not given."
12496 (if (string-match org-ts-regexp0 s)
12497 (list 0
12498 (if (or (match-beginning 8) (not nodefault))
12499 (string-to-number (or (match-string 8 s) "0")))
12500 (if (or (match-beginning 7) (not nodefault))
12501 (string-to-number (or (match-string 7 s) "0")))
12502 (string-to-number (match-string 4 s))
12503 (string-to-number (match-string 3 s))
12504 (string-to-number (match-string 2 s))
12505 nil nil nil)
12506 (make-list 9 0)))
12508 (defun org-timestamp-up (&optional arg)
12509 "Increase the date item at the cursor by one.
12510 If the cursor is on the year, change the year. If it is on the month or
12511 the day, change that.
12512 With prefix ARG, change by that many units."
12513 (interactive "p")
12514 (org-timestamp-change (prefix-numeric-value arg)))
12516 (defun org-timestamp-down (&optional arg)
12517 "Decrease the date item at the cursor by one.
12518 If the cursor is on the year, change the year. If it is on the month or
12519 the day, change that.
12520 With prefix ARG, change by that many units."
12521 (interactive "p")
12522 (org-timestamp-change (- (prefix-numeric-value arg))))
12524 (defun org-timestamp-up-day (&optional arg)
12525 "Increase the date in the time stamp by one day.
12526 With prefix ARG, change that many days."
12527 (interactive "p")
12528 (if (and (not (org-at-timestamp-p t))
12529 (org-on-heading-p))
12530 (org-todo 'up)
12531 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12533 (defun org-timestamp-down-day (&optional arg)
12534 "Decrease the date in the time stamp by one day.
12535 With prefix ARG, change that many days."
12536 (interactive "p")
12537 (if (and (not (org-at-timestamp-p t))
12538 (org-on-heading-p))
12539 (org-todo 'down)
12540 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12542 (defun org-at-timestamp-p (&optional inactive-ok)
12543 "Determine if the cursor is in or at a timestamp."
12544 (interactive)
12545 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12546 (pos (point))
12547 (ans (or (looking-at tsr)
12548 (save-excursion
12549 (skip-chars-backward "^[<\n\r\t")
12550 (if (> (point) (point-min)) (backward-char 1))
12551 (and (looking-at tsr)
12552 (> (- (match-end 0) pos) -1))))))
12553 (and ans
12554 (boundp 'org-ts-what)
12555 (setq org-ts-what
12556 (cond
12557 ((= pos (match-beginning 0)) 'bracket)
12558 ((= pos (1- (match-end 0))) 'bracket)
12559 ((org-pos-in-match-range pos 2) 'year)
12560 ((org-pos-in-match-range pos 3) 'month)
12561 ((org-pos-in-match-range pos 7) 'hour)
12562 ((org-pos-in-match-range pos 8) 'minute)
12563 ((or (org-pos-in-match-range pos 4)
12564 (org-pos-in-match-range pos 5)) 'day)
12565 ((and (> pos (or (match-end 8) (match-end 5)))
12566 (< pos (match-end 0)))
12567 (- pos (or (match-end 8) (match-end 5))))
12568 (t 'day))))
12569 ans))
12571 (defun org-toggle-timestamp-type ()
12572 "Toggle the type (<active> or [inactive]) of a time stamp."
12573 (interactive)
12574 (when (org-at-timestamp-p t)
12575 (let ((beg (match-beginning 0)) (end (match-end 0))
12576 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12577 (save-excursion
12578 (goto-char beg)
12579 (while (re-search-forward "[][<>]" end t)
12580 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12581 t t)))
12582 (message "Timestamp is now %sactive"
12583 (if (equal (char-after beg) ?<) "" "in")))))
12585 (defun org-timestamp-change (n &optional what)
12586 "Change the date in the time stamp at point.
12587 The date will be changed by N times WHAT. WHAT can be `day', `month',
12588 `year', `minute', `second'. If WHAT is not given, the cursor position
12589 in the timestamp determines what will be changed."
12590 (let ((pos (point))
12591 with-hm inactive
12592 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12593 org-ts-what
12594 extra rem
12595 ts time time0)
12596 (if (not (org-at-timestamp-p t))
12597 (error "Not at a timestamp"))
12598 (if (and (not what) (eq org-ts-what 'bracket))
12599 (org-toggle-timestamp-type)
12600 (if (and (not what) (not (eq org-ts-what 'day))
12601 org-display-custom-times
12602 (get-text-property (point) 'display)
12603 (not (get-text-property (1- (point)) 'display)))
12604 (setq org-ts-what 'day))
12605 (setq org-ts-what (or what org-ts-what)
12606 inactive (= (char-after (match-beginning 0)) ?\[)
12607 ts (match-string 0))
12608 (replace-match "")
12609 (if (string-match
12610 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12612 (setq extra (match-string 1 ts)))
12613 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12614 (setq with-hm t))
12615 (setq time0 (org-parse-time-string ts))
12616 (when (and (eq org-ts-what 'minute)
12617 (eq current-prefix-arg nil))
12618 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12619 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12620 (setcar (cdr time0) (+ (nth 1 time0)
12621 (if (> n 0) (- rem) (- dm rem))))))
12622 (setq time
12623 (encode-time (or (car time0) 0)
12624 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12625 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12626 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12627 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12628 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12629 (nthcdr 6 time0)))
12630 (when (and (member org-ts-what '(hour minute))
12631 extra
12632 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
12633 (setq extra (org-modify-ts-extra
12634 extra
12635 (if (eq org-ts-what 'hour) 2 5)
12636 n dm)))
12637 (when (integerp org-ts-what)
12638 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12639 (if (eq what 'calendar)
12640 (let ((cal-date (org-get-date-from-calendar)))
12641 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12642 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12643 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12644 (setcar time0 (or (car time0) 0))
12645 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12646 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12647 (setq time (apply 'encode-time time0))))
12648 (setq org-last-changed-timestamp
12649 (org-insert-time-stamp time with-hm inactive nil nil extra))
12650 (org-clock-update-time-maybe)
12651 (goto-char pos)
12652 ;; Try to recenter the calendar window, if any
12653 (if (and org-calendar-follow-timestamp-change
12654 (get-buffer-window "*Calendar*" t)
12655 (memq org-ts-what '(day month year)))
12656 (org-recenter-calendar (time-to-days time))))))
12658 (defun org-modify-ts-extra (s pos n dm)
12659 "Change the different parts of the lead-time and repeat fields in timestamp."
12660 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12661 ng h m new rem)
12662 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12663 (cond
12664 ((or (org-pos-in-match-range pos 2)
12665 (org-pos-in-match-range pos 3))
12666 (setq m (string-to-number (match-string 3 s))
12667 h (string-to-number (match-string 2 s)))
12668 (if (org-pos-in-match-range pos 2)
12669 (setq h (+ h n))
12670 (setq n (* dm (org-no-warnings (signum n))))
12671 (when (not (= 0 (setq rem (% m dm))))
12672 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12673 (setq m (+ m n)))
12674 (if (< m 0) (setq m (+ m 60) h (1- h)))
12675 (if (> m 59) (setq m (- m 60) h (1+ h)))
12676 (setq h (min 24 (max 0 h)))
12677 (setq ng 1 new (format "-%02d:%02d" h m)))
12678 ((org-pos-in-match-range pos 6)
12679 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12680 ((org-pos-in-match-range pos 5)
12681 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12683 ((org-pos-in-match-range pos 9)
12684 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12685 ((org-pos-in-match-range pos 8)
12686 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12688 (when ng
12689 (setq s (concat
12690 (substring s 0 (match-beginning ng))
12692 (substring s (match-end ng))))))
12695 (defun org-recenter-calendar (date)
12696 "If the calendar is visible, recenter it to DATE."
12697 (let* ((win (selected-window))
12698 (cwin (get-buffer-window "*Calendar*" t))
12699 (calendar-move-hook nil))
12700 (when cwin
12701 (select-window cwin)
12702 (calendar-goto-date (if (listp date) date
12703 (calendar-gregorian-from-absolute date)))
12704 (select-window win))))
12706 (defun org-goto-calendar (&optional arg)
12707 "Go to the Emacs calendar at the current date.
12708 If there is a time stamp in the current line, go to that date.
12709 A prefix ARG can be used to force the current date."
12710 (interactive "P")
12711 (let ((tsr org-ts-regexp) diff
12712 (calendar-move-hook nil)
12713 (calendar-view-holidays-initially-flag nil)
12714 (view-calendar-holidays-initially nil)
12715 (calendar-view-diary-initially-flag nil)
12716 (view-diary-entries-initially nil))
12717 (if (or (org-at-timestamp-p)
12718 (save-excursion
12719 (beginning-of-line 1)
12720 (looking-at (concat ".*" tsr))))
12721 (let ((d1 (time-to-days (current-time)))
12722 (d2 (time-to-days
12723 (org-time-string-to-time (match-string 1)))))
12724 (setq diff (- d2 d1))))
12725 (calendar)
12726 (calendar-goto-today)
12727 (if (and diff (not arg)) (calendar-forward-day diff))))
12729 (defun org-get-date-from-calendar ()
12730 "Return a list (month day year) of date at point in calendar."
12731 (with-current-buffer "*Calendar*"
12732 (save-match-data
12733 (calendar-cursor-to-date))))
12735 (defun org-date-from-calendar ()
12736 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12737 If there is already a time stamp at the cursor position, update it."
12738 (interactive)
12739 (if (org-at-timestamp-p t)
12740 (org-timestamp-change 0 'calendar)
12741 (let ((cal-date (org-get-date-from-calendar)))
12742 (org-insert-time-stamp
12743 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12745 (defun org-minutes-to-hh:mm-string (m)
12746 "Compute H:MM from a number of minutes."
12747 (let ((h (/ m 60)))
12748 (setq m (- m (* 60 h)))
12749 (format org-time-clocksum-format h m)))
12751 (defun org-hh:mm-string-to-minutes (s)
12752 "Convert a string H:MM to a number of minutes."
12753 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12754 (+ (* (string-to-number (match-string 1 s)) 60)
12755 (string-to-number (match-string 2 s)))
12758 ;;;; Files
12760 (defun org-save-all-org-buffers ()
12761 "Save all Org-mode buffers without user confirmation."
12762 (interactive)
12763 (message "Saving all Org-mode buffers...")
12764 (save-some-buffers t 'org-mode-p)
12765 (when (featurep 'org-id) (org-id-locations-save))
12766 (message "Saving all Org-mode buffers... done"))
12768 (defun org-revert-all-org-buffers ()
12769 "Revert all Org-mode buffers.
12770 Prompt for confirmation when there are unsaved changes.
12771 Be sure you know what you are doing before letting this function
12772 overwrite your changes.
12774 This function is useful in a setup where one tracks org files
12775 with a version control system, to revert on one machine after pulling
12776 changes from another. I believe the procedure must be like this:
12778 1. M-x org-save-all-org-buffers
12779 2. Pull changes from the other machine, resolve conflicts
12780 3. M-x org-revert-all-org-buffers"
12781 (interactive)
12782 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
12783 (error "Abort"))
12784 (save-excursion
12785 (save-window-excursion
12786 (mapc
12787 (lambda (b)
12788 (when (and (with-current-buffer b (org-mode-p))
12789 (with-current-buffer b buffer-file-name))
12790 (switch-to-buffer b)
12791 (revert-buffer t 'no-confirm)))
12792 (buffer-list))
12793 (when (and (featurep 'org-id) org-id-track-globally)
12794 (org-id-locations-load)))))
12796 ;;;; Agenda files
12798 ;;;###autoload
12799 (defun org-iswitchb (&optional arg)
12800 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12801 With a prefix argument, restrict available to files.
12802 With two prefix arguments, restrict available buffers to agenda files.
12804 Due to some yet unresolved reason, the global function
12805 `iswitchb-mode' needs to be active for this function to work."
12806 (interactive "P")
12807 (require 'iswitchb)
12808 (let ((enabled iswitchb-mode) blist)
12809 (or enabled (iswitchb-mode 1))
12810 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12811 ((equal arg '(16)) (org-buffer-list 'agenda))
12812 (t (org-buffer-list))))
12813 (unwind-protect
12814 (let ((iswitchb-make-buflist-hook
12815 (lambda ()
12816 (setq iswitchb-temp-buflist
12817 (mapcar 'buffer-name blist)))))
12818 (switch-to-buffer
12819 (iswitchb-read-buffer
12820 "Switch-to: " nil t))
12821 (or enabled (iswitchb-mode -1))))))
12823 ;;;###autoload
12824 (defun org-ido-switchb (&optional arg)
12825 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12826 With a prefix argument, restrict available to files.
12827 With two prefix arguments, restrict available buffers to agenda files."
12828 (interactive "P")
12829 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12830 ((equal arg '(16)) (org-buffer-list 'agenda))
12831 (t (org-buffer-list)))))
12832 (switch-to-buffer
12833 (org-ido-completing-read "Org buffer: "
12834 (mapcar 'list (mapcar 'buffer-name blist))
12835 nil t))))
12837 (defun org-buffer-list (&optional predicate exclude-tmp)
12838 "Return a list of Org buffers.
12839 PREDICATE can be `export', `files' or `agenda'.
12841 export restrict the list to Export buffers.
12842 files restrict the list to buffers visiting Org files.
12843 agenda restrict the list to buffers visiting agenda files.
12845 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12846 (let* ((bfn nil)
12847 (agenda-files (and (eq predicate 'agenda)
12848 (mapcar 'file-truename (org-agenda-files t))))
12849 (filter
12850 (cond
12851 ((eq predicate 'files)
12852 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12853 ((eq predicate 'export)
12854 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12855 ((eq predicate 'agenda)
12856 (lambda (b)
12857 (with-current-buffer b
12858 (and (eq major-mode 'org-mode)
12859 (setq bfn (buffer-file-name b))
12860 (member (file-truename bfn) agenda-files)))))
12861 (t (lambda (b) (with-current-buffer b
12862 (or (eq major-mode 'org-mode)
12863 (string-match "\*Org .*Export"
12864 (buffer-name b)))))))))
12865 (delq nil
12866 (mapcar
12867 (lambda(b)
12868 (if (and (funcall filter b)
12869 (or (not exclude-tmp)
12870 (not (string-match "tmp" (buffer-name b)))))
12872 nil))
12873 (buffer-list)))))
12875 (defun org-agenda-files (&optional unrestricted archives)
12876 "Get the list of agenda files.
12877 Optional UNRESTRICTED means return the full list even if a restriction
12878 is currently in place.
12879 When ARCHIVES is t, include all archive files hat are really being
12880 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12881 `org-agenda-archives-mode' is t."
12882 (let ((files
12883 (cond
12884 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12885 ((stringp org-agenda-files) (org-read-agenda-file-list))
12886 ((listp org-agenda-files) org-agenda-files)
12887 (t (error "Invalid value of `org-agenda-files'")))))
12888 (setq files (apply 'append
12889 (mapcar (lambda (f)
12890 (if (file-directory-p f)
12891 (directory-files
12892 f t org-agenda-file-regexp)
12893 (list f)))
12894 files)))
12895 (when org-agenda-skip-unavailable-files
12896 (setq files (delq nil
12897 (mapcar (function
12898 (lambda (file)
12899 (and (file-readable-p file) file)))
12900 files))))
12901 (when (or (eq archives t)
12902 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12903 (setq files (org-add-archive-files files)))
12904 files))
12906 (defun org-edit-agenda-file-list ()
12907 "Edit the list of agenda files.
12908 Depending on setup, this either uses customize to edit the variable
12909 `org-agenda-files', or it visits the file that is holding the list. In the
12910 latter case, the buffer is set up in a way that saving it automatically kills
12911 the buffer and restores the previous window configuration."
12912 (interactive)
12913 (if (stringp org-agenda-files)
12914 (let ((cw (current-window-configuration)))
12915 (find-file org-agenda-files)
12916 (org-set-local 'org-window-configuration cw)
12917 (org-add-hook 'after-save-hook
12918 (lambda ()
12919 (set-window-configuration
12920 (prog1 org-window-configuration
12921 (kill-buffer (current-buffer))))
12922 (org-install-agenda-files-menu)
12923 (message "New agenda file list installed"))
12924 nil 'local)
12925 (message "%s" (substitute-command-keys
12926 "Edit list and finish with \\[save-buffer]")))
12927 (customize-variable 'org-agenda-files)))
12929 (defun org-store-new-agenda-file-list (list)
12930 "Set new value for the agenda file list and save it correctly."
12931 (if (stringp org-agenda-files)
12932 (let ((f org-agenda-files) b)
12933 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12934 (with-temp-file f
12935 (insert (mapconcat 'identity list "\n") "\n")))
12936 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12937 (setq org-agenda-files list)
12938 (customize-save-variable 'org-agenda-files org-agenda-files))))
12940 (defun org-read-agenda-file-list ()
12941 "Read the list of agenda files from a file."
12942 (when (file-directory-p org-agenda-files)
12943 (error "`org-agenda-files' cannot be a single directory"))
12944 (when (stringp org-agenda-files)
12945 (with-temp-buffer
12946 (insert-file-contents org-agenda-files)
12947 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12950 ;;;###autoload
12951 (defun org-cycle-agenda-files ()
12952 "Cycle through the files in `org-agenda-files'.
12953 If the current buffer visits an agenda file, find the next one in the list.
12954 If the current buffer does not, find the first agenda file."
12955 (interactive)
12956 (let* ((fs (org-agenda-files t))
12957 (files (append fs (list (car fs))))
12958 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12959 file)
12960 (unless files (error "No agenda files"))
12961 (catch 'exit
12962 (while (setq file (pop files))
12963 (if (equal (file-truename file) tcf)
12964 (when (car files)
12965 (find-file (car files))
12966 (throw 'exit t))))
12967 (find-file (car fs)))
12968 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12970 (defun org-agenda-file-to-front (&optional to-end)
12971 "Move/add the current file to the top of the agenda file list.
12972 If the file is not present in the list, it is added to the front. If it is
12973 present, it is moved there. With optional argument TO-END, add/move to the
12974 end of the list."
12975 (interactive "P")
12976 (let ((org-agenda-skip-unavailable-files nil)
12977 (file-alist (mapcar (lambda (x)
12978 (cons (file-truename x) x))
12979 (org-agenda-files t)))
12980 (ctf (file-truename buffer-file-name))
12981 x had)
12982 (setq x (assoc ctf file-alist) had x)
12984 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12985 (if to-end
12986 (setq file-alist (append (delq x file-alist) (list x)))
12987 (setq file-alist (cons x (delq x file-alist))))
12988 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12989 (org-install-agenda-files-menu)
12990 (message "File %s to %s of agenda file list"
12991 (if had "moved" "added") (if to-end "end" "front"))))
12993 (defun org-remove-file (&optional file)
12994 "Remove current file from the list of files in variable `org-agenda-files'.
12995 These are the files which are being checked for agenda entries.
12996 Optional argument FILE means, use this file instead of the current."
12997 (interactive)
12998 (let* ((org-agenda-skip-unavailable-files nil)
12999 (file (or file buffer-file-name))
13000 (true-file (file-truename file))
13001 (afile (abbreviate-file-name file))
13002 (files (delq nil (mapcar
13003 (lambda (x)
13004 (if (equal true-file
13005 (file-truename x))
13006 nil x))
13007 (org-agenda-files t)))))
13008 (if (not (= (length files) (length (org-agenda-files t))))
13009 (progn
13010 (org-store-new-agenda-file-list files)
13011 (org-install-agenda-files-menu)
13012 (message "Removed file: %s" afile))
13013 (message "File was not in list: %s (not removed)" afile))))
13015 (defun org-file-menu-entry (file)
13016 (vector file (list 'find-file file) t))
13018 (defun org-check-agenda-file (file)
13019 "Make sure FILE exists. If not, ask user what to do."
13020 (when (not (file-exists-p file))
13021 (message "non-existent file %s. [R]emove from list or [A]bort?"
13022 (abbreviate-file-name file))
13023 (let ((r (downcase (read-char-exclusive))))
13024 (cond
13025 ((equal r ?r)
13026 (org-remove-file file)
13027 (throw 'nextfile t))
13028 (t (error "Abort"))))))
13030 (defun org-get-agenda-file-buffer (file)
13031 "Get a buffer visiting FILE. If the buffer needs to be created, add
13032 it to the list of buffers which might be released later."
13033 (let ((buf (org-find-base-buffer-visiting file)))
13034 (if buf
13035 buf ; just return it
13036 ;; Make a new buffer and remember it
13037 (setq buf (find-file-noselect file))
13038 (if buf (push buf org-agenda-new-buffers))
13039 buf)))
13041 (defun org-release-buffers (blist)
13042 "Release all buffers in list, asking the user for confirmation when needed.
13043 When a buffer is unmodified, it is just killed. When modified, it is saved
13044 \(if the user agrees) and then killed."
13045 (let (buf file)
13046 (while (setq buf (pop blist))
13047 (setq file (buffer-file-name buf))
13048 (when (and (buffer-modified-p buf)
13049 file
13050 (y-or-n-p (format "Save file %s? " file)))
13051 (with-current-buffer buf (save-buffer)))
13052 (kill-buffer buf))))
13054 (defun org-prepare-agenda-buffers (files)
13055 "Create buffers for all agenda files, protect archived trees and comments."
13056 (interactive)
13057 (let ((pa '(:org-archived t))
13058 (pc '(:org-comment t))
13059 (pall '(:org-archived t :org-comment t))
13060 (inhibit-read-only t)
13061 (rea (concat ":" org-archive-tag ":"))
13062 bmp file re)
13063 (save-excursion
13064 (save-restriction
13065 (while (setq file (pop files))
13066 (if (bufferp file)
13067 (set-buffer file)
13068 (org-check-agenda-file file)
13069 (set-buffer (org-get-agenda-file-buffer file)))
13070 (widen)
13071 (setq bmp (buffer-modified-p))
13072 (org-refresh-category-properties)
13073 (setq org-todo-keywords-for-agenda
13074 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13075 (setq org-done-keywords-for-agenda
13076 (append org-done-keywords-for-agenda org-done-keywords))
13077 (setq org-todo-keyword-alist-for-agenda
13078 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13079 (setq org-tag-alist-for-agenda
13080 (append org-tag-alist-for-agenda org-tag-alist))
13082 (save-excursion
13083 (remove-text-properties (point-min) (point-max) pall)
13084 (when org-agenda-skip-archived-trees
13085 (goto-char (point-min))
13086 (while (re-search-forward rea nil t)
13087 (if (org-on-heading-p t)
13088 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13089 (goto-char (point-min))
13090 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13091 (while (re-search-forward re nil t)
13092 (add-text-properties
13093 (match-beginning 0) (org-end-of-subtree t) pc)))
13094 (set-buffer-modified-p bmp))))
13095 (setq org-todo-keyword-alist-for-agenda
13096 (org-uniquify org-todo-keyword-alist-for-agenda)
13097 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13099 ;;;; Embedded LaTeX
13101 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13102 "Keymap for the minor `org-cdlatex-mode'.")
13104 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13105 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13106 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13107 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13108 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13110 (defvar org-cdlatex-texmathp-advice-is-done nil
13111 "Flag remembering if we have applied the advice to texmathp already.")
13113 (define-minor-mode org-cdlatex-mode
13114 "Toggle the minor `org-cdlatex-mode'.
13115 This mode supports entering LaTeX environment and math in LaTeX fragments
13116 in Org-mode.
13117 \\{org-cdlatex-mode-map}"
13118 nil " OCDL" nil
13119 (when org-cdlatex-mode (require 'cdlatex))
13120 (unless org-cdlatex-texmathp-advice-is-done
13121 (setq org-cdlatex-texmathp-advice-is-done t)
13122 (defadvice texmathp (around org-math-always-on activate)
13123 "Always return t in org-mode buffers.
13124 This is because we want to insert math symbols without dollars even outside
13125 the LaTeX math segments. If Orgmode thinks that point is actually inside
13126 an embedded LaTeX fragment, let texmathp do its job.
13127 \\[org-cdlatex-mode-map]"
13128 (interactive)
13129 (let (p)
13130 (cond
13131 ((not (org-mode-p)) ad-do-it)
13132 ((eq this-command 'cdlatex-math-symbol)
13133 (setq ad-return-value t
13134 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13136 (let ((p (org-inside-LaTeX-fragment-p)))
13137 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13138 (setq ad-return-value t
13139 texmathp-why '("Org-mode embedded math" . 0))
13140 (if p ad-do-it)))))))))
13142 (defun turn-on-org-cdlatex ()
13143 "Unconditionally turn on `org-cdlatex-mode'."
13144 (org-cdlatex-mode 1))
13146 (defun org-inside-LaTeX-fragment-p ()
13147 "Test if point is inside a LaTeX fragment.
13148 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13149 sequence appearing also before point.
13150 Even though the matchers for math are configurable, this function assumes
13151 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13152 delimiters are skipped when they have been removed by customization.
13153 The return value is nil, or a cons cell with the delimiter and
13154 and the position of this delimiter.
13156 This function does a reasonably good job, but can locally be fooled by
13157 for example currency specifications. For example it will assume being in
13158 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13159 fragments that are properly closed, but during editing, we have to live
13160 with the uncertainty caused by missing closing delimiters. This function
13161 looks only before point, not after."
13162 (catch 'exit
13163 (let ((pos (point))
13164 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13165 (lim (progn
13166 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13167 (point)))
13168 dd-on str (start 0) m re)
13169 (goto-char pos)
13170 (when dodollar
13171 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13172 re (nth 1 (assoc "$" org-latex-regexps)))
13173 (while (string-match re str start)
13174 (cond
13175 ((= (match-end 0) (length str))
13176 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13177 ((= (match-end 0) (- (length str) 5))
13178 (throw 'exit nil))
13179 (t (setq start (match-end 0))))))
13180 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13181 (goto-char pos)
13182 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13183 (and (match-beginning 2) (throw 'exit nil))
13184 ;; count $$
13185 (while (re-search-backward "\\$\\$" lim t)
13186 (setq dd-on (not dd-on)))
13187 (goto-char pos)
13188 (if dd-on (cons "$$" m))))))
13191 (defun org-try-cdlatex-tab ()
13192 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13193 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13194 - inside a LaTeX fragment, or
13195 - after the first word in a line, where an abbreviation expansion could
13196 insert a LaTeX environment."
13197 (when org-cdlatex-mode
13198 (cond
13199 ((save-excursion
13200 (skip-chars-backward "a-zA-Z0-9*")
13201 (skip-chars-backward " \t")
13202 (bolp))
13203 (cdlatex-tab) t)
13204 ((org-inside-LaTeX-fragment-p)
13205 (cdlatex-tab) t)
13206 (t nil))))
13208 (defun org-cdlatex-underscore-caret (&optional arg)
13209 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13210 Revert to the normal definition outside of these fragments."
13211 (interactive "P")
13212 (if (org-inside-LaTeX-fragment-p)
13213 (call-interactively 'cdlatex-sub-superscript)
13214 (let (org-cdlatex-mode)
13215 (call-interactively (key-binding (vector last-input-event))))))
13217 (defun org-cdlatex-math-modify (&optional arg)
13218 "Execute `cdlatex-math-modify' in LaTeX fragments.
13219 Revert to the normal definition outside of these fragments."
13220 (interactive "P")
13221 (if (org-inside-LaTeX-fragment-p)
13222 (call-interactively 'cdlatex-math-modify)
13223 (let (org-cdlatex-mode)
13224 (call-interactively (key-binding (vector last-input-event))))))
13226 (defvar org-latex-fragment-image-overlays nil
13227 "List of overlays carrying the images of latex fragments.")
13228 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13230 (defun org-remove-latex-fragment-image-overlays ()
13231 "Remove all overlays with LaTeX fragment images in current buffer."
13232 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13233 (setq org-latex-fragment-image-overlays nil))
13235 (defun org-preview-latex-fragment (&optional subtree)
13236 "Preview the LaTeX fragment at point, or all locally or globally.
13237 If the cursor is in a LaTeX fragment, create the image and overlay
13238 it over the source code. If there is no fragment at point, display
13239 all fragments in the current text, from one headline to the next. With
13240 prefix SUBTREE, display all fragments in the current subtree. With a
13241 double prefix `C-u C-u', or when the cursor is before the first headline,
13242 display all fragments in the buffer.
13243 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13244 (interactive "P")
13245 (org-remove-latex-fragment-image-overlays)
13246 (save-excursion
13247 (save-restriction
13248 (let (beg end at msg)
13249 (cond
13250 ((or (equal subtree '(16))
13251 (not (save-excursion
13252 (re-search-backward (concat "^" outline-regexp) nil t))))
13253 (setq beg (point-min) end (point-max)
13254 msg "Creating images for buffer...%s"))
13255 ((equal subtree '(4))
13256 (org-back-to-heading)
13257 (setq beg (point) end (org-end-of-subtree t)
13258 msg "Creating images for subtree...%s"))
13260 (if (setq at (org-inside-LaTeX-fragment-p))
13261 (goto-char (max (point-min) (- (cdr at) 2)))
13262 (org-back-to-heading))
13263 (setq beg (point) end (progn (outline-next-heading) (point))
13264 msg (if at "Creating image...%s"
13265 "Creating images for entry...%s"))))
13266 (message msg "")
13267 (narrow-to-region beg end)
13268 (goto-char beg)
13269 (org-format-latex
13270 (concat "ltxpng/" (file-name-sans-extension
13271 (file-name-nondirectory
13272 buffer-file-name)))
13273 default-directory 'overlays msg at 'forbuffer)
13274 (message msg "done. Use `C-c C-c' to remove images.")))))
13276 (defvar org-latex-regexps
13277 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13278 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13279 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13280 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13281 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13282 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13283 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13284 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13285 "Regular expressions for matching embedded LaTeX.")
13287 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13288 "Replace LaTeX fragments with links to an image, and produce images."
13289 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13290 (let* ((prefixnodir (file-name-nondirectory prefix))
13291 (absprefix (expand-file-name prefix dir))
13292 (todir (file-name-directory absprefix))
13293 (opt org-format-latex-options)
13294 (matchers (plist-get opt :matchers))
13295 (re-list org-latex-regexps)
13296 (cnt 0) txt link beg end re e checkdir
13297 m n block linkfile movefile ov)
13298 ;; Check if there are old images files with this prefix, and remove them
13299 (when (file-directory-p todir)
13300 (mapc 'delete-file
13301 (directory-files
13302 todir 'full
13303 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13304 ;; Check the different regular expressions
13305 (while (setq e (pop re-list))
13306 (setq m (car e) re (nth 1 e) n (nth 2 e)
13307 block (if (nth 3 e) "\n\n" ""))
13308 (when (member m matchers)
13309 (goto-char (point-min))
13310 (while (re-search-forward re nil t)
13311 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13312 (not (get-text-property (match-beginning n)
13313 'org-protected)))
13314 (setq txt (match-string n)
13315 beg (match-beginning n) end (match-end n)
13316 cnt (1+ cnt)
13317 linkfile (format "%s_%04d.png" prefix cnt)
13318 movefile (format "%s_%04d.png" absprefix cnt)
13319 link (concat block "[[file:" linkfile "]]" block))
13320 (if msg (message msg cnt))
13321 (goto-char beg)
13322 (unless checkdir ; make sure the directory exists
13323 (setq checkdir t)
13324 (or (file-directory-p todir) (make-directory todir)))
13325 (org-create-formula-image
13326 txt movefile opt forbuffer)
13327 (if overlays
13328 (progn
13329 (setq ov (org-make-overlay beg end))
13330 (if (featurep 'xemacs)
13331 (progn
13332 (org-overlay-put ov 'invisible t)
13333 (org-overlay-put
13334 ov 'end-glyph
13335 (make-glyph (vector 'png :file movefile))))
13336 (org-overlay-put
13337 ov 'display
13338 (list 'image :type 'png :file movefile :ascent 'center)))
13339 (push ov org-latex-fragment-image-overlays)
13340 (goto-char end))
13341 (delete-region beg end)
13342 (insert link))))))))
13344 ;; This function borrows from Ganesh Swami's latex2png.el
13345 (defun org-create-formula-image (string tofile options buffer)
13346 (let* ((tmpdir (if (featurep 'xemacs)
13347 (temp-directory)
13348 temporary-file-directory))
13349 (texfilebase (make-temp-name
13350 (expand-file-name "orgtex" tmpdir)))
13351 (texfile (concat texfilebase ".tex"))
13352 (dvifile (concat texfilebase ".dvi"))
13353 (pngfile (concat texfilebase ".png"))
13354 (fnh (if (featurep 'xemacs)
13355 (font-height (get-face-font 'default))
13356 (face-attribute 'default :height nil)))
13357 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13358 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13359 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13360 "Black"))
13361 (bg (or (plist-get options (if buffer :background :html-background))
13362 "Transparent")))
13363 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13364 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13365 (with-temp-file texfile
13366 (insert org-format-latex-header
13367 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13368 (let ((dir default-directory))
13369 (condition-case nil
13370 (progn
13371 (cd tmpdir)
13372 (call-process "latex" nil nil nil texfile))
13373 (error nil))
13374 (cd dir))
13375 (if (not (file-exists-p dvifile))
13376 (progn (message "Failed to create dvi file from %s" texfile) nil)
13377 (condition-case nil
13378 (call-process "dvipng" nil nil nil
13379 "-E" "-fg" fg "-bg" bg
13380 "-D" dpi
13381 ;;"-x" scale "-y" scale
13382 "-T" "tight"
13383 "-o" pngfile
13384 dvifile)
13385 (error nil))
13386 (if (not (file-exists-p pngfile))
13387 (progn (message "Failed to create png file from %s" texfile) nil)
13388 ;; Use the requested file name and clean up
13389 (copy-file pngfile tofile 'replace)
13390 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13391 (delete-file (concat texfilebase e)))
13392 pngfile))))
13394 (defun org-dvipng-color (attr)
13395 "Return an rgb color specification for dvipng."
13396 (apply 'format "rgb %s %s %s"
13397 (mapcar 'org-normalize-color
13398 (color-values (face-attribute 'default attr nil)))))
13400 (defun org-normalize-color (value)
13401 "Return string to be used as color value for an RGB component."
13402 (format "%g" (/ value 65535.0)))
13404 ;;;; Key bindings
13406 ;; Make `C-c C-x' a prefix key
13407 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13409 ;; TAB key with modifiers
13410 (org-defkey org-mode-map "\C-i" 'org-cycle)
13411 (org-defkey org-mode-map [(tab)] 'org-cycle)
13412 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13413 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13414 (org-defkey org-mode-map "\M-\t" 'org-complete)
13415 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13416 ;; The following line is necessary under Suse GNU/Linux
13417 (unless (featurep 'xemacs)
13418 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13419 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13420 (define-key org-mode-map [backtab] 'org-shifttab)
13422 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13423 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13424 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13426 ;; Cursor keys with modifiers
13427 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13428 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13429 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13430 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13432 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13433 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13434 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13435 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13437 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13438 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13439 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13440 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13442 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13443 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13445 ;;; Extra keys for tty access.
13446 ;; We only set them when really needed because otherwise the
13447 ;; menus don't show the simple keys
13449 (when (or org-use-extra-keys
13450 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13451 (not window-system))
13452 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13453 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13454 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13455 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13456 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13457 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13458 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13459 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13460 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13461 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13462 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13463 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13464 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13465 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13466 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13467 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13468 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13469 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13470 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13471 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13472 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13473 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13475 ;; All the other keys
13477 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13478 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13479 (if (boundp 'narrow-map)
13480 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13481 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13482 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13483 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13484 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13485 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13486 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13487 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13488 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13489 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13490 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13491 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13492 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13493 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13494 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13495 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13496 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13497 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13498 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13499 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13500 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13501 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13502 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13503 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13504 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13505 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13506 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13507 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13508 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13509 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13510 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13511 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13512 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13513 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13514 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13515 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13516 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13517 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13518 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13519 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13520 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13521 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13522 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13523 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13524 (org-defkey org-mode-map "\C-c^" 'org-sort)
13525 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13526 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13527 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13528 (org-defkey org-mode-map "\C-m" 'org-return)
13529 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13530 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13531 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13532 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13533 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13534 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13535 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13536 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13537 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13538 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13539 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13540 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13541 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13542 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13543 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13544 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13545 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13547 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13548 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13549 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13550 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13552 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13553 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13554 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13555 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13556 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13557 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13558 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13559 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13560 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13561 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13562 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13563 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13564 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13566 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13567 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13568 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13569 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13571 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13573 (define-key org-mode-map "\C-c\C-xr" 'org-reload)
13575 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
13576 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
13578 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
13581 (when (featurep 'xemacs)
13582 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13585 (defvar org-self-insert-command-undo-counter 0)
13587 (defvar org-table-auto-blank-field) ; defined in org-table.el
13588 (defun org-self-insert-command (N)
13589 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13590 If the cursor is in a table looking at whitespace, the whitespace is
13591 overwritten, and the table is not marked as requiring realignment."
13592 (interactive "p")
13593 (if (and
13594 (org-table-p)
13595 (progn
13596 ;; check if we blank the field, and if that triggers align
13597 (and (featurep 'org-table) org-table-auto-blank-field
13598 (member last-command
13599 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13600 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13601 ;; got extra space, this field does not determine column width
13602 (let (org-table-may-need-update) (org-table-blank-field))
13603 ;; no extra space, this field may determine column width
13604 (org-table-blank-field)))
13606 (eq N 1)
13607 (looking-at "[^|\n]* |"))
13608 (let (org-table-may-need-update)
13609 (goto-char (1- (match-end 0)))
13610 (delete-backward-char 1)
13611 (goto-char (match-beginning 0))
13612 (self-insert-command N))
13613 (setq org-table-may-need-update t)
13614 (self-insert-command N)
13615 (org-fix-tags-on-the-fly)
13616 (if org-self-insert-cluster-for-undo
13617 (if (not (eq last-command 'org-self-insert-command))
13618 (setq org-self-insert-command-undo-counter 1)
13619 (if (>= org-self-insert-command-undo-counter 20)
13620 (setq org-self-insert-command-undo-counter 1)
13621 (and (> org-self-insert-command-undo-counter 0)
13622 buffer-undo-list
13623 (not (cadr buffer-undo-list)) ; remove nil entry
13624 (setcdr buffer-undo-list (cddr buffer-undo-list)))
13625 (setq org-self-insert-command-undo-counter
13626 (1+ org-self-insert-command-undo-counter)))))))
13628 (defun org-fix-tags-on-the-fly ()
13629 (when (and (equal (char-after (point-at-bol)) ?*)
13630 (org-on-heading-p))
13631 (org-align-tags-here org-tags-column)))
13633 (defun org-delete-backward-char (N)
13634 "Like `delete-backward-char', insert whitespace at field end in tables.
13635 When deleting backwards, in tables this function will insert whitespace in
13636 front of the next \"|\" separator, to keep the table aligned. The table will
13637 still be marked for re-alignment if the field did fill the entire column,
13638 because, in this case the deletion might narrow the column."
13639 (interactive "p")
13640 (if (and (org-table-p)
13641 (eq N 1)
13642 (string-match "|" (buffer-substring (point-at-bol) (point)))
13643 (looking-at ".*?|"))
13644 (let ((pos (point))
13645 (noalign (looking-at "[^|\n\r]* |"))
13646 (c org-table-may-need-update))
13647 (backward-delete-char N)
13648 (skip-chars-forward "^|")
13649 (insert " ")
13650 (goto-char (1- pos))
13651 ;; noalign: if there were two spaces at the end, this field
13652 ;; does not determine the width of the column.
13653 (if noalign (setq org-table-may-need-update c)))
13654 (backward-delete-char N)
13655 (org-fix-tags-on-the-fly)))
13657 (defun org-delete-char (N)
13658 "Like `delete-char', but insert whitespace at field end in tables.
13659 When deleting characters, in tables this function will insert whitespace in
13660 front of the next \"|\" separator, to keep the table aligned. The table will
13661 still be marked for re-alignment if the field did fill the entire column,
13662 because, in this case the deletion might narrow the column."
13663 (interactive "p")
13664 (if (and (org-table-p)
13665 (not (bolp))
13666 (not (= (char-after) ?|))
13667 (eq N 1))
13668 (if (looking-at ".*?|")
13669 (let ((pos (point))
13670 (noalign (looking-at "[^|\n\r]* |"))
13671 (c org-table-may-need-update))
13672 (replace-match (concat
13673 (substring (match-string 0) 1 -1)
13674 " |"))
13675 (goto-char pos)
13676 ;; noalign: if there were two spaces at the end, this field
13677 ;; does not determine the width of the column.
13678 (if noalign (setq org-table-may-need-update c)))
13679 (delete-char N))
13680 (delete-char N)
13681 (org-fix-tags-on-the-fly)))
13683 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13684 (put 'org-self-insert-command 'delete-selection t)
13685 (put 'orgtbl-self-insert-command 'delete-selection t)
13686 (put 'org-delete-char 'delete-selection 'supersede)
13687 (put 'org-delete-backward-char 'delete-selection 'supersede)
13688 (put 'org-yank 'delete-selection 'yank)
13690 ;; Make `flyspell-mode' delay after some commands
13691 (put 'org-self-insert-command 'flyspell-delayed t)
13692 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13693 (put 'org-delete-char 'flyspell-delayed t)
13694 (put 'org-delete-backward-char 'flyspell-delayed t)
13696 ;; Make pabbrev-mode expand after org-mode commands
13697 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13698 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13700 ;; How to do this: Measure non-white length of current string
13701 ;; If equal to column width, we should realign.
13703 (defun org-remap (map &rest commands)
13704 "In MAP, remap the functions given in COMMANDS.
13705 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13706 (let (new old)
13707 (while commands
13708 (setq old (pop commands) new (pop commands))
13709 (if (fboundp 'command-remapping)
13710 (org-defkey map (vector 'remap old) new)
13711 (substitute-key-definition old new map global-map)))))
13713 (when (eq org-enable-table-editor 'optimized)
13714 ;; If the user wants maximum table support, we need to hijack
13715 ;; some standard editing functions
13716 (org-remap org-mode-map
13717 'self-insert-command 'org-self-insert-command
13718 'delete-char 'org-delete-char
13719 'delete-backward-char 'org-delete-backward-char)
13720 (org-defkey org-mode-map "|" 'org-force-self-insert))
13722 (defvar org-ctrl-c-ctrl-c-hook nil
13723 "Hook for functions attaching themselves to `C-c C-c'.
13724 This can be used to add additional functionality to the C-c C-c key which
13725 executes context-dependent commands.
13726 Each function will be called with no arguments. The function must check
13727 if the context is appropriate for it to act. If yes, it should do its
13728 thing and then return a non-nil value. If the context is wrong,
13729 just do nothing.")
13731 (defvar org-metaleft-hook nil
13732 "Hook for functions attaching themselves to `M-left'.
13733 See `org-ctrl-c-ctrl-c-hook' for more information.")
13734 (defvar org-metaright-hook nil
13735 "Hook for functions attaching themselves to `M-right'.
13736 See `org-ctrl-c-ctrl-c-hook' for more information.")
13737 (defvar org-metaup-hook nil
13738 "Hook for functions attaching themselves to `M-up'.
13739 See `org-ctrl-c-ctrl-c-hook' for more information.")
13740 (defvar org-metadown-hook nil
13741 "Hook for functions attaching themselves to `M-down'.
13742 See `org-ctrl-c-ctrl-c-hook' for more information.")
13743 (defvar org-shiftmetaleft-hook nil
13744 "Hook for functions attaching themselves to `M-S-left'.
13745 See `org-ctrl-c-ctrl-c-hook' for more information.")
13746 (defvar org-shiftmetaright-hook nil
13747 "Hook for functions attaching themselves to `M-S-right'.
13748 See `org-ctrl-c-ctrl-c-hook' for more information.")
13749 (defvar org-shiftmetaup-hook nil
13750 "Hook for functions attaching themselves to `M-S-up'.
13751 See `org-ctrl-c-ctrl-c-hook' for more information.")
13752 (defvar org-shiftmetadown-hook nil
13753 "Hook for functions attaching themselves to `M-S-down'.
13754 See `org-ctrl-c-ctrl-c-hook' for more information.")
13755 (defvar org-metareturn-hook nil
13756 "Hook for functions attaching themselves to `M-RET'.
13757 See `org-ctrl-c-ctrl-c-hook' for more information.")
13759 (defun org-modifier-cursor-error ()
13760 "Throw an error, a modified cursor command was applied in wrong context."
13761 (error "This command is active in special context like tables, headlines or items"))
13763 (defun org-shiftselect-error ()
13764 "Throw an error because Shift-Cursor command was applied in wrong context."
13765 (if (and (boundp 'shift-select-mode) shift-select-mode)
13766 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13767 (error "This command works only in special context like headlines or timestamps.")))
13769 (defun org-call-for-shift-select (cmd)
13770 (let ((this-command-keys-shift-translated t))
13771 (call-interactively cmd)))
13773 (defun org-shifttab (&optional arg)
13774 "Global visibility cycling or move to previous table field.
13775 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13776 on context.
13777 See the individual commands for more information."
13778 (interactive "P")
13779 (cond
13780 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13781 ((integerp arg)
13782 (message "Content view to level: %d" arg)
13783 (org-content (prefix-numeric-value arg))
13784 (setq org-cycle-global-status 'overview))
13785 (t (call-interactively 'org-global-cycle))))
13787 (defun org-shiftmetaleft ()
13788 "Promote subtree or delete table column.
13789 Calls `org-promote-subtree', `org-outdent-item',
13790 or `org-table-delete-column', depending on context.
13791 See the individual commands for more information."
13792 (interactive)
13793 (cond
13794 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
13795 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13796 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13797 ((org-at-item-p) (call-interactively 'org-outdent-item))
13798 (t (org-modifier-cursor-error))))
13800 (defun org-shiftmetaright ()
13801 "Demote subtree or insert table column.
13802 Calls `org-demote-subtree', `org-indent-item',
13803 or `org-table-insert-column', depending on context.
13804 See the individual commands for more information."
13805 (interactive)
13806 (cond
13807 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
13808 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13809 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13810 ((org-at-item-p) (call-interactively 'org-indent-item))
13811 (t (org-modifier-cursor-error))))
13813 (defun org-shiftmetaup (&optional arg)
13814 "Move subtree up or kill table row.
13815 Calls `org-move-subtree-up' or `org-table-kill-row' or
13816 `org-move-item-up' depending on context. See the individual commands
13817 for more information."
13818 (interactive "P")
13819 (cond
13820 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
13821 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13822 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13823 ((org-at-item-p) (call-interactively 'org-move-item-up))
13824 (t (org-modifier-cursor-error))))
13826 (defun org-shiftmetadown (&optional arg)
13827 "Move subtree down or insert table row.
13828 Calls `org-move-subtree-down' or `org-table-insert-row' or
13829 `org-move-item-down', depending on context. See the individual
13830 commands for more information."
13831 (interactive "P")
13832 (cond
13833 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
13834 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13835 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13836 ((org-at-item-p) (call-interactively 'org-move-item-down))
13837 (t (org-modifier-cursor-error))))
13839 (defun org-metaleft (&optional arg)
13840 "Promote heading or move table column to left.
13841 Calls `org-do-promote' or `org-table-move-column', depending on context.
13842 With no specific context, calls the Emacs default `backward-word'.
13843 See the individual commands for more information."
13844 (interactive "P")
13845 (cond
13846 ((run-hook-with-args-until-success 'org-metaleft-hook))
13847 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13848 ((or (org-on-heading-p)
13849 (and (org-region-active-p)
13850 (save-excursion
13851 (goto-char (region-beginning))
13852 (org-on-heading-p))))
13853 (call-interactively 'org-do-promote))
13854 ((or (org-at-item-p)
13855 (and (org-region-active-p)
13856 (save-excursion
13857 (goto-char (region-beginning))
13858 (org-at-item-p))))
13859 (call-interactively 'org-outdent-item))
13860 (t (call-interactively 'backward-word))))
13862 (defun org-metaright (&optional arg)
13863 "Demote subtree or move table column to right.
13864 Calls `org-do-demote' or `org-table-move-column', depending on context.
13865 With no specific context, calls the Emacs default `forward-word'.
13866 See the individual commands for more information."
13867 (interactive "P")
13868 (cond
13869 ((run-hook-with-args-until-success 'org-metaright-hook))
13870 ((org-at-table-p) (call-interactively 'org-table-move-column))
13871 ((or (org-on-heading-p)
13872 (and (org-region-active-p)
13873 (save-excursion
13874 (goto-char (region-beginning))
13875 (org-on-heading-p))))
13876 (call-interactively 'org-do-demote))
13877 ((or (org-at-item-p)
13878 (and (org-region-active-p)
13879 (save-excursion
13880 (goto-char (region-beginning))
13881 (org-at-item-p))))
13882 (call-interactively 'org-indent-item))
13883 (t (call-interactively 'forward-word))))
13885 (defun org-metaup (&optional arg)
13886 "Move subtree up or move table row up.
13887 Calls `org-move-subtree-up' or `org-table-move-row' or
13888 `org-move-item-up', depending on context. See the individual commands
13889 for more information."
13890 (interactive "P")
13891 (cond
13892 ((run-hook-with-args-until-success 'org-metaup-hook))
13893 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13894 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13895 ((org-at-item-p) (call-interactively 'org-move-item-up))
13896 (t (transpose-lines 1) (beginning-of-line -1))))
13898 (defun org-metadown (&optional arg)
13899 "Move subtree down or move table row down.
13900 Calls `org-move-subtree-down' or `org-table-move-row' or
13901 `org-move-item-down', depending on context. See the individual
13902 commands for more information."
13903 (interactive "P")
13904 (cond
13905 ((run-hook-with-args-until-success 'org-metadown-hook))
13906 ((org-at-table-p) (call-interactively 'org-table-move-row))
13907 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13908 ((org-at-item-p) (call-interactively 'org-move-item-down))
13909 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13911 (defun org-shiftup (&optional arg)
13912 "Increase item in timestamp or increase priority of current headline.
13913 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13914 depending on context. See the individual commands for more information."
13915 (interactive "P")
13916 (cond
13917 ((and org-support-shift-select (org-region-active-p))
13918 (org-call-for-shift-select 'previous-line))
13919 ((org-at-timestamp-p t)
13920 (call-interactively (if org-edit-timestamp-down-means-later
13921 'org-timestamp-down 'org-timestamp-up)))
13922 ((and (not (eq org-support-shift-select 'always))
13923 (org-on-heading-p))
13924 (call-interactively 'org-priority-up))
13925 ((and (not org-support-shift-select) (org-at-item-p))
13926 (call-interactively 'org-previous-item))
13927 ((org-clocktable-try-shift 'up arg))
13928 (org-support-shift-select
13929 (org-call-for-shift-select 'previous-line))
13930 (t (org-shiftselect-error))))
13932 (defun org-shiftdown (&optional arg)
13933 "Decrease item in timestamp or decrease priority of current headline.
13934 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13935 depending on context. See the individual commands for more information."
13936 (interactive "P")
13937 (cond
13938 ((and org-support-shift-select (org-region-active-p))
13939 (org-call-for-shift-select 'next-line))
13940 ((org-at-timestamp-p t)
13941 (call-interactively (if org-edit-timestamp-down-means-later
13942 'org-timestamp-up 'org-timestamp-down)))
13943 ((and (not (eq org-support-shift-select 'always))
13944 (org-on-heading-p))
13945 (call-interactively 'org-priority-down))
13946 ((and (not org-support-shift-select) (org-at-item-p))
13947 (call-interactively 'org-next-item))
13948 ((org-clocktable-try-shift 'down arg))
13949 (org-support-shift-select
13950 (org-call-for-shift-select 'next-line))
13951 (t (org-shiftselect-error))))
13953 (defun org-shiftright (&optional arg)
13954 "Cycle the thing at point or in the current line, depending on context.
13955 Depending on context, this does one of the following:
13957 - switch a timestamp at point one day into the future
13958 - on a headline, switch to the next TODO keyword.
13959 - on an item, switch entire list to the next bullet type
13960 - on a property line, switch to the next allowed value
13961 - on a clocktable definition line, move time block into the future"
13962 (interactive "P")
13963 (cond
13964 ((and org-support-shift-select (org-region-active-p))
13965 (org-call-for-shift-select 'forward-char))
13966 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13967 ((and (not (eq org-support-shift-select 'always))
13968 (org-on-heading-p))
13969 (org-call-with-arg 'org-todo 'right))
13970 ((or (and org-support-shift-select
13971 (not (eq org-support-shift-select 'always))
13972 (org-at-item-bullet-p))
13973 (and (not org-support-shift-select) (org-at-item-p)))
13974 (org-call-with-arg 'org-cycle-list-bullet nil))
13975 ((and (not (eq org-support-shift-select 'always))
13976 (org-at-property-p))
13977 (call-interactively 'org-property-next-allowed-value))
13978 ((org-clocktable-try-shift 'right arg))
13979 (org-support-shift-select
13980 (org-call-for-shift-select 'forward-char))
13981 (t (org-shiftselect-error))))
13983 (defun org-shiftleft (&optional arg)
13984 "Cycle the thing at point or in the current line, depending on context.
13985 Depending on context, this does one of the following:
13987 - switch a timestamp at point one day into the past
13988 - on a headline, switch to the previous TODO keyword.
13989 - on an item, switch entire list to the previous bullet type
13990 - on a property line, switch to the previous allowed value
13991 - on a clocktable definition line, move time block into the past"
13992 (interactive "P")
13993 (cond
13994 ((and org-support-shift-select (org-region-active-p))
13995 (org-call-for-shift-select 'backward-char))
13996 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13997 ((and (not (eq org-support-shift-select 'always))
13998 (org-on-heading-p))
13999 (org-call-with-arg 'org-todo 'left))
14000 ((or (and org-support-shift-select
14001 (not (eq org-support-shift-select 'always))
14002 (org-at-item-bullet-p))
14003 (and (not org-support-shift-select) (org-at-item-p)))
14004 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14005 ((and (not (eq org-support-shift-select 'always))
14006 (org-at-property-p))
14007 (call-interactively 'org-property-previous-allowed-value))
14008 ((org-clocktable-try-shift 'left arg))
14009 (org-support-shift-select
14010 (org-call-for-shift-select 'backward-char))
14011 (t (org-shiftselect-error))))
14013 (defun org-shiftcontrolright ()
14014 "Switch to next TODO set."
14015 (interactive)
14016 (cond
14017 ((and org-support-shift-select (org-region-active-p))
14018 (org-call-for-shift-select 'forward-word))
14019 ((and (not (eq org-support-shift-select 'always))
14020 (org-on-heading-p))
14021 (org-call-with-arg 'org-todo 'nextset))
14022 (org-support-shift-select
14023 (org-call-for-shift-select 'forward-word))
14024 (t (org-shiftselect-error))))
14026 (defun org-shiftcontrolleft ()
14027 "Switch to previous TODO set."
14028 (interactive)
14029 (cond
14030 ((and org-support-shift-select (org-region-active-p))
14031 (org-call-for-shift-select 'backward-word))
14032 ((and (not (eq org-support-shift-select 'always))
14033 (org-on-heading-p))
14034 (org-call-with-arg 'org-todo 'previousset))
14035 (org-support-shift-select
14036 (org-call-for-shift-select 'backward-word))
14037 (t (org-shiftselect-error))))
14039 (defun org-ctrl-c-ret ()
14040 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14041 (interactive)
14042 (cond
14043 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14044 (t (call-interactively 'org-insert-heading))))
14046 (defun org-copy-special ()
14047 "Copy region in table or copy current subtree.
14048 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14049 See the individual commands for more information."
14050 (interactive)
14051 (call-interactively
14052 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14054 (defun org-cut-special ()
14055 "Cut region in table or cut current subtree.
14056 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14057 See the individual commands for more information."
14058 (interactive)
14059 (call-interactively
14060 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14062 (defun org-paste-special (arg)
14063 "Paste rectangular region into table, or past subtree relative to level.
14064 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14065 See the individual commands for more information."
14066 (interactive "P")
14067 (if (org-at-table-p)
14068 (org-table-paste-rectangle)
14069 (org-paste-subtree arg)))
14071 (defun org-edit-special ()
14072 "Call a special editor for the stuff at point.
14073 When at a table, call the formula editor with `org-table-edit-formulas'.
14074 When at the first line of an src example, call `org-edit-src-code'.
14075 When in an #+include line, visit the include file. Otherwise call
14076 `ffap' to visit the file at point."
14077 (interactive)
14078 (cond
14079 ((org-at-table-p)
14080 (call-interactively 'org-table-edit-formulas))
14081 ((save-excursion
14082 (beginning-of-line 1)
14083 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14084 (find-file (org-trim (match-string 1))))
14085 ((org-edit-src-code))
14086 ((org-edit-fixed-width-region))
14087 (t (call-interactively 'ffap))))
14090 (defun org-ctrl-c-ctrl-c (&optional arg)
14091 "Set tags in headline, or update according to changed information at point.
14093 This command does many different things, depending on context:
14095 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14096 this is what we do.
14098 - If the cursor is in a headline, prompt for tags and insert them
14099 into the current line, aligned to `org-tags-column'. When called
14100 with prefix arg, realign all tags in the current buffer.
14102 - If the cursor is in one of the special #+KEYWORD lines, this
14103 triggers scanning the buffer for these lines and updating the
14104 information.
14106 - If the cursor is inside a table, realign the table. This command
14107 works even if the automatic table editor has been turned off.
14109 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14110 the entire table.
14112 - If the cursor is at a footnote reference or definition, jump to
14113 the corresponding definition or references, respectively.
14115 - If the cursor is a the beginning of a dynamic block, update it.
14117 - If the cursor is inside a table created by the table.el package,
14118 activate that table.
14120 - If the current buffer is a remember buffer, close note and file
14121 it. A prefix argument of 1 files to the default location
14122 without further interaction. A prefix argument of 2 files to
14123 the currently clocking task.
14125 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14126 links in this buffer.
14128 - If the cursor is on a numbered item in a plain list, renumber the
14129 ordered list.
14131 - If the cursor is on a checkbox, toggle it."
14132 (interactive "P")
14133 (let ((org-enable-table-editor t))
14134 (cond
14135 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14136 org-occur-highlights
14137 org-latex-fragment-image-overlays)
14138 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14139 (org-remove-occur-highlights)
14140 (org-remove-latex-fragment-image-overlays)
14141 (message "Temporary highlights/overlays removed from current buffer"))
14142 ((and (local-variable-p 'org-finish-function (current-buffer))
14143 (fboundp org-finish-function))
14144 (funcall org-finish-function))
14145 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14146 ((org-at-property-p)
14147 (call-interactively 'org-property-action))
14148 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14149 ((org-on-heading-p) (call-interactively 'org-set-tags))
14150 ((org-at-table.el-p)
14151 (require 'table)
14152 (beginning-of-line 1)
14153 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14154 (call-interactively 'table-recognize-table))
14155 ((org-at-table-p)
14156 (org-table-maybe-eval-formula)
14157 (if arg
14158 (call-interactively 'org-table-recalculate)
14159 (org-table-maybe-recalculate-line))
14160 (call-interactively 'org-table-align))
14161 ((or (org-footnote-at-reference-p)
14162 (org-footnote-at-definition-p))
14163 (call-interactively 'org-footnote-action))
14164 ((org-at-item-checkbox-p)
14165 (call-interactively 'org-toggle-checkbox))
14166 ((org-at-item-p)
14167 (if arg
14168 (call-interactively 'org-toggle-checkbox)
14169 (call-interactively 'org-maybe-renumber-ordered-list)))
14170 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14171 ;; Dynamic block
14172 (beginning-of-line 1)
14173 (save-excursion (org-update-dblock)))
14174 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14175 (cond
14176 ((equal (match-string 1) "TBLFM")
14177 ;; Recalculate the table before this line
14178 (save-excursion
14179 (beginning-of-line 1)
14180 (skip-chars-backward " \r\n\t")
14181 (if (org-at-table-p)
14182 (org-call-with-arg 'org-table-recalculate t))))
14184 ; (org-set-regexps-and-options)
14185 ; (org-restart-font-lock)
14186 (let ((org-inhibit-startup t)) (org-mode-restart))
14187 (message "Local setup has been refreshed"))))
14188 (t (error "C-c C-c can do nothing useful at this location.")))))
14190 (defun org-mode-restart ()
14191 "Restart Org-mode, to scan again for special lines.
14192 Also updates the keyword regular expressions."
14193 (interactive)
14194 (org-mode)
14195 (message "Org-mode restarted"))
14197 (defun org-kill-note-or-show-branches ()
14198 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14199 (interactive)
14200 (if (not org-finish-function)
14201 (call-interactively 'show-branches)
14202 (let ((org-note-abort t))
14203 (funcall org-finish-function))))
14205 (defun org-return (&optional indent)
14206 "Goto next table row or insert a newline.
14207 Calls `org-table-next-row' or `newline', depending on context.
14208 See the individual commands for more information."
14209 (interactive)
14210 (cond
14211 ((bobp) (if indent (newline-and-indent) (newline)))
14212 ((org-at-table-p)
14213 (org-table-justify-field-maybe)
14214 (call-interactively 'org-table-next-row))
14215 ((and org-return-follows-link
14216 (eq (get-text-property (point) 'face) 'org-link))
14217 (call-interactively 'org-open-at-point))
14218 ((and (org-at-heading-p)
14219 (looking-at
14220 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14221 (org-show-entry)
14222 (end-of-line 1)
14223 (newline))
14224 (t (if indent (newline-and-indent) (newline)))))
14226 (defun org-return-indent ()
14227 "Goto next table row or insert a newline and indent.
14228 Calls `org-table-next-row' or `newline-and-indent', depending on
14229 context. See the individual commands for more information."
14230 (interactive)
14231 (org-return t))
14233 (defun org-ctrl-c-star ()
14234 "Compute table, or change heading status of lines.
14235 Calls `org-table-recalculate' or `org-toggle-heading',
14236 depending on context."
14237 (interactive)
14238 (cond
14239 ((org-at-table-p)
14240 (call-interactively 'org-table-recalculate))
14242 ;; Convert all lines in region to list items
14243 (call-interactively 'org-toggle-heading))))
14245 (defun org-ctrl-c-minus ()
14246 "Insert separator line in table or modify bullet status of line.
14247 Also turns a plain line or a region of lines into list items.
14248 Calls `org-table-insert-hline', `org-toggle-item', or
14249 `org-cycle-list-bullet', depending on context."
14250 (interactive)
14251 (cond
14252 ((org-at-table-p)
14253 (call-interactively 'org-table-insert-hline))
14254 ((org-region-active-p)
14255 (call-interactively 'org-toggle-item))
14256 ((org-in-item-p)
14257 (call-interactively 'org-cycle-list-bullet))
14259 (call-interactively 'org-toggle-item))))
14261 (defun org-toggle-item ()
14262 "Convert headings or normal lines to items, items to normal lines.
14263 If there is no active region, only the current line is considered.
14265 If the first line in the region is a headline, convert all headlines to items.
14267 If the first line in the region is an item, convert all items to normal lines.
14269 If the first line is normal text, add an item bullet to each line."
14270 (interactive)
14271 (let (l2 l beg end)
14272 (if (org-region-active-p)
14273 (setq beg (region-beginning) end (region-end))
14274 (setq beg (point-at-bol)
14275 end (min (1+ (point-at-eol)) (point-max))))
14276 (save-excursion
14277 (goto-char end)
14278 (setq l2 (org-current-line))
14279 (goto-char beg)
14280 (beginning-of-line 1)
14281 (setq l (1- (org-current-line)))
14282 (if (org-at-item-p)
14283 ;; We already have items, de-itemize
14284 (while (< (setq l (1+ l)) l2)
14285 (when (org-at-item-p)
14286 (goto-char (match-beginning 2))
14287 (delete-region (match-beginning 2) (match-end 2))
14288 (and (looking-at "[ \t]+") (replace-match "")))
14289 (beginning-of-line 2))
14290 (if (org-on-heading-p)
14291 ;; Headings, convert to items
14292 (while (< (setq l (1+ l)) l2)
14293 (if (looking-at org-outline-regexp)
14294 (replace-match "- " t t))
14295 (beginning-of-line 2))
14296 ;; normal lines, turn them into items
14297 (while (< (setq l (1+ l)) l2)
14298 (unless (org-at-item-p)
14299 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14300 (replace-match "\\1- \\2")))
14301 (beginning-of-line 2)))))))
14303 (defun org-toggle-heading (&optional nstars)
14304 "Convert headings to normal text, or items or text to headings.
14305 If there is no active region, only the current line is considered.
14307 If the first line is a heading, remove the stars from all headlines
14308 in the region.
14310 If the first line is a plain list item, turn all plain list items into
14311 headings.
14313 If the first line is a normal line, turn each and every line in the region
14314 into a heading.
14316 When converting a line into a heading, the number of stars is chosen
14317 such that the lines become children of the current entry. However, when
14318 a prefix argument is given, its value determines the number of stars to add."
14319 (interactive "P")
14320 (let (l2 l itemp beg end)
14321 (if (org-region-active-p)
14322 (setq beg (region-beginning) end (region-end))
14323 (setq beg (point-at-bol)
14324 end (min (1+ (point-at-eol)) (point-max))))
14325 (save-excursion
14326 (goto-char end)
14327 (setq l2 (org-current-line))
14328 (goto-char beg)
14329 (beginning-of-line 1)
14330 (setq l (1- (org-current-line)))
14331 (if (org-on-heading-p)
14332 ;; We already have headlines, de-star them
14333 (while (< (setq l (1+ l)) l2)
14334 (when (org-on-heading-p t)
14335 (and (looking-at outline-regexp) (replace-match "")))
14336 (beginning-of-line 2))
14337 (setq itemp (org-at-item-p))
14338 (let* ((stars
14339 (if nstars
14340 (make-string (prefix-numeric-value current-prefix-arg)
14342 (save-excursion
14343 (re-search-backward org-complex-heading-regexp nil t)
14344 (or (match-string 1) ""))))
14345 (add-stars (cond (nstars "")
14346 ((equal stars "") "*")
14347 (org-odd-levels-only "**")
14348 (t "*")))
14349 (rpl (concat stars add-stars " ")))
14350 (while (< (setq l (1+ l)) l2)
14351 (if itemp
14352 (and (org-at-item-p) (replace-match rpl t t))
14353 (unless (org-on-heading-p)
14354 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14355 (replace-match (concat rpl (match-string 2))))))
14356 (beginning-of-line 2)))))))
14358 (defun org-meta-return (&optional arg)
14359 "Insert a new heading or wrap a region in a table.
14360 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14361 See the individual commands for more information."
14362 (interactive "P")
14363 (cond
14364 ((run-hook-with-args-until-success 'org-metareturn-hook))
14365 ((org-at-table-p)
14366 (call-interactively 'org-table-wrap-region))
14367 (t (call-interactively 'org-insert-heading))))
14369 ;;; Menu entries
14371 ;; Define the Org-mode menus
14372 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14373 '("Tbl"
14374 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14375 ["Next Field" org-cycle (org-at-table-p)]
14376 ["Previous Field" org-shifttab (org-at-table-p)]
14377 ["Next Row" org-return (org-at-table-p)]
14378 "--"
14379 ["Blank Field" org-table-blank-field (org-at-table-p)]
14380 ["Edit Field" org-table-edit-field (org-at-table-p)]
14381 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14382 "--"
14383 ("Column"
14384 ["Move Column Left" org-metaleft (org-at-table-p)]
14385 ["Move Column Right" org-metaright (org-at-table-p)]
14386 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14387 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14388 ("Row"
14389 ["Move Row Up" org-metaup (org-at-table-p)]
14390 ["Move Row Down" org-metadown (org-at-table-p)]
14391 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14392 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14393 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14394 "--"
14395 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14396 ("Rectangle"
14397 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14398 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14399 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14400 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14401 "--"
14402 ("Calculate"
14403 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14404 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14405 ["Edit Formulas" org-edit-special (org-at-table-p)]
14406 "--"
14407 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14408 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14409 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14410 "--"
14411 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14412 "--"
14413 ["Sum Column/Rectangle" org-table-sum
14414 (or (org-at-table-p) (org-region-active-p))]
14415 ["Which Column?" org-table-current-column (org-at-table-p)])
14416 ["Debug Formulas"
14417 org-table-toggle-formula-debugger
14418 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14419 ["Show Col/Row Numbers"
14420 org-table-toggle-coordinate-overlays
14421 :style toggle
14422 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14423 "--"
14424 ["Create" org-table-create (and (not (org-at-table-p))
14425 org-enable-table-editor)]
14426 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14427 ["Import from File" org-table-import (not (org-at-table-p))]
14428 ["Export to File" org-table-export (org-at-table-p)]
14429 "--"
14430 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14432 (easy-menu-define org-org-menu org-mode-map "Org menu"
14433 '("Org"
14434 ("Show/Hide"
14435 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14436 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14437 ["Sparse Tree..." org-sparse-tree t]
14438 ["Reveal Context" org-reveal t]
14439 ["Show All" show-all t]
14440 "--"
14441 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14442 "--"
14443 ["New Heading" org-insert-heading t]
14444 ("Navigate Headings"
14445 ["Up" outline-up-heading t]
14446 ["Next" outline-next-visible-heading t]
14447 ["Previous" outline-previous-visible-heading t]
14448 ["Next Same Level" outline-forward-same-level t]
14449 ["Previous Same Level" outline-backward-same-level t]
14450 "--"
14451 ["Jump" org-goto t])
14452 ("Edit Structure"
14453 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14454 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14455 "--"
14456 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14457 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14458 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14459 "--"
14460 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14461 "--"
14462 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14463 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14464 ["Demote Heading" org-metaright (not (org-at-table-p))]
14465 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14466 "--"
14467 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14468 "--"
14469 ["Convert to odd levels" org-convert-to-odd-levels t]
14470 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14471 ("Editing"
14472 ["Emphasis..." org-emphasize t]
14473 ["Edit Source Example" org-edit-special t]
14474 "--"
14475 ["Footnote new/jump" org-footnote-action t]
14476 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14477 ("Archive"
14478 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14479 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14480 ; :active t :keys "C-u C-c C-x C-a"]
14481 ["Sparse trees open ARCHIVE trees"
14482 (setq org-sparse-tree-open-archived-trees
14483 (not org-sparse-tree-open-archived-trees))
14484 :style toggle :selected org-sparse-tree-open-archived-trees]
14485 ["Cycling opens ARCHIVE trees"
14486 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14487 :style toggle :selected org-cycle-open-archived-trees]
14488 "--"
14489 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14490 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14491 ; ["Check and Move Children" (org-archive-subtree '(4))
14492 ; :active t :keys "C-u C-c C-x C-s"]
14494 "--"
14495 ("Hyperlinks"
14496 ["Store Link (Global)" org-store-link t]
14497 ["Insert Link" org-insert-link t]
14498 ["Follow Link" org-open-at-point t]
14499 "--"
14500 ["Next link" org-next-link t]
14501 ["Previous link" org-previous-link t]
14502 "--"
14503 ["Descriptive Links"
14504 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14505 :style radio
14506 :selected (member '(org-link) buffer-invisibility-spec)]
14507 ["Literal Links"
14508 (progn
14509 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14510 :style radio
14511 :selected (not (member '(org-link) buffer-invisibility-spec))])
14512 "--"
14513 ("TODO Lists"
14514 ["TODO/DONE/-" org-todo t]
14515 ("Select keyword"
14516 ["Next keyword" org-shiftright (org-on-heading-p)]
14517 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14518 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14519 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14520 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14521 ["Show TODO Tree" org-show-todo-tree t]
14522 ["Global TODO list" org-todo-list t]
14523 "--"
14524 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14525 :selected org-enforce-todo-dependencies :style toggle :active t]
14526 "Settings for tree at point"
14527 ["Do Children sequentially" org-toggle-ordered-property :style radio
14528 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14529 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14530 ["Do Children parallel" org-toggle-ordered-property :style radio
14531 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14532 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14533 "--"
14534 ["Set Priority" org-priority t]
14535 ["Priority Up" org-shiftup t]
14536 ["Priority Down" org-shiftdown t]
14537 "--"
14538 ["Get news from all feeds" org-feed-update-all t]
14539 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
14540 ["Customize feeds" (customize-variable 'org-feed-alist) t])
14541 ("TAGS and Properties"
14542 ["Set Tags" org-set-tags-command t]
14543 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14544 "--"
14545 ["Set property" org-set-property t]
14546 ["Column view of properties" org-columns t]
14547 ["Insert Column View DBlock" org-insert-columns-dblock t])
14548 ("Dates and Scheduling"
14549 ["Timestamp" org-time-stamp t]
14550 ["Timestamp (inactive)" org-time-stamp-inactive t]
14551 ("Change Date"
14552 ["1 Day Later" org-shiftright t]
14553 ["1 Day Earlier" org-shiftleft t]
14554 ["1 ... Later" org-shiftup t]
14555 ["1 ... Earlier" org-shiftdown t])
14556 ["Compute Time Range" org-evaluate-time-range t]
14557 ["Schedule Item" org-schedule t]
14558 ["Deadline" org-deadline t]
14559 "--"
14560 ["Custom time format" org-toggle-time-stamp-overlays
14561 :style radio :selected org-display-custom-times]
14562 "--"
14563 ["Goto Calendar" org-goto-calendar t]
14564 ["Date from Calendar" org-date-from-calendar t]
14565 "--"
14566 ["Start/Restart Timer" org-timer-start t]
14567 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14568 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14569 ["Insert Timer String" org-timer t]
14570 ["Insert Timer Item" org-timer-item t])
14571 ("Logging work"
14572 ["Clock in" org-clock-in t]
14573 ["Clock out" org-clock-out t]
14574 ["Clock cancel" org-clock-cancel t]
14575 ["Goto running clock" org-clock-goto t]
14576 ["Display times" org-clock-display t]
14577 ["Create clock table" org-clock-report t]
14578 "--"
14579 ["Record DONE time"
14580 (progn (setq org-log-done (not org-log-done))
14581 (message "Switching to %s will %s record a timestamp"
14582 (car org-done-keywords)
14583 (if org-log-done "automatically" "not")))
14584 :style toggle :selected org-log-done])
14585 "--"
14586 ["Agenda Command..." org-agenda t]
14587 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14588 ("File List for Agenda")
14589 ("Special views current file"
14590 ["TODO Tree" org-show-todo-tree t]
14591 ["Check Deadlines" org-check-deadlines t]
14592 ["Timeline" org-timeline t]
14593 ["Tags/Property tree" org-match-sparse-tree t])
14594 "--"
14595 ["Export/Publish..." org-export t]
14596 ("LaTeX"
14597 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14598 :selected org-cdlatex-mode]
14599 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14600 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14601 ["Modify math symbol" org-cdlatex-math-modify
14602 (org-inside-LaTeX-fragment-p)]
14603 ["Insert citation" org-reftex-citation t]
14604 "--"
14605 ["Export LaTeX fragments as images"
14606 (if (featurep 'org-exp)
14607 (setq org-export-with-LaTeX-fragments
14608 (not org-export-with-LaTeX-fragments))
14609 (require 'org-exp))
14610 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14611 org-export-with-LaTeX-fragments)])
14612 "--"
14613 ("Documentation"
14614 ["Show Version" org-version t]
14615 ["Info Documentation" org-info t])
14616 ("Customize"
14617 ["Browse Org Group" org-customize t]
14618 "--"
14619 ["Expand This Menu" org-create-customize-menu
14620 (fboundp 'customize-menu-create)])
14621 "--"
14622 ("Refresh/Reload"
14623 ["Refresh setup current buffer" org-mode-restart t]
14624 ["Reload Org (after update)" org-reload t]
14625 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
14628 (defun org-info (&optional node)
14629 "Read documentation for Org-mode in the info system.
14630 With optional NODE, go directly to that node."
14631 (interactive)
14632 (info (format "(org)%s" (or node ""))))
14634 (defun org-install-agenda-files-menu ()
14635 (let ((bl (buffer-list)))
14636 (save-excursion
14637 (while bl
14638 (set-buffer (pop bl))
14639 (if (org-mode-p) (setq bl nil)))
14640 (when (org-mode-p)
14641 (easy-menu-change
14642 '("Org") "File List for Agenda"
14643 (append
14644 (list
14645 ["Edit File List" (org-edit-agenda-file-list) t]
14646 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14647 ["Remove Current File from List" org-remove-file t]
14648 ["Cycle through agenda files" org-cycle-agenda-files t]
14649 ["Occur in all agenda files" org-occur-in-agenda-files t]
14650 "--")
14651 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14653 ;;;; Documentation
14655 ;;;###autoload
14656 (defun org-require-autoloaded-modules ()
14657 (interactive)
14658 (mapc 'require
14659 '(org-agenda org-archive org-attach org-clock org-colview
14660 org-exp org-id org-export-latex org-docbook
14661 org-publish org-remember org-table org-timer)))
14663 ;;;###autoload
14664 (defun org-reload (&optional uncompiled)
14665 "Reload all org lisp files.
14666 With prefix arg UNCOMPILED, load the uncompiled versions."
14667 (interactive "P")
14668 (require 'find-func)
14669 (let* ((dir (file-name-directory (find-library-name "org")))
14670 (files (directory-files dir t "\\.el\\'"))
14671 (remove-re (concat (if (featurep 'xemacs)
14672 "org-colview" "org-colview-xemacs")
14673 "\\'")))
14674 (setq files (mapcar 'file-name-sans-extension files))
14675 (setq files (mapcar
14676 (lambda (x) (if (string-match remove-re x) nil x))
14677 files))
14678 (setq files (delq nil files))
14679 (mapc
14680 (lambda (f)
14681 (if (and (not uncompiled)
14682 (file-exists-p (concat f ".elc")))
14683 (load (concat f ".elc") nil nil t)
14684 (load (concat f ".el") nil nil t)))
14685 files)))
14687 ;;;###autoload
14688 (defun org-customize ()
14689 "Call the customize function with org as argument."
14690 (interactive)
14691 (org-load-modules-maybe)
14692 (org-require-autoloaded-modules)
14693 (customize-browse 'org))
14695 (defun org-create-customize-menu ()
14696 "Create a full customization menu for Org-mode, insert it into the menu."
14697 (interactive)
14698 (org-load-modules-maybe)
14699 (org-require-autoloaded-modules)
14700 (if (fboundp 'customize-menu-create)
14701 (progn
14702 (easy-menu-change
14703 '("Org") "Customize"
14704 `(["Browse Org group" org-customize t]
14705 "--"
14706 ,(customize-menu-create 'org)
14707 ["Set" Custom-set t]
14708 ["Save" Custom-save t]
14709 ["Reset to Current" Custom-reset-current t]
14710 ["Reset to Saved" Custom-reset-saved t]
14711 ["Reset to Standard Settings" Custom-reset-standard t]))
14712 (message "\"Org\"-menu now contains full customization menu"))
14713 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14715 ;;;; Miscellaneous stuff
14717 ;;; Generally useful functions
14719 (defun org-find-text-property-in-string (prop s)
14720 "Return the first non-nil value of property PROP in string S."
14721 (or (get-text-property 0 prop s)
14722 (get-text-property (or (next-single-property-change 0 prop s) 0)
14723 prop s)))
14725 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14726 "Display the given MESSAGE as a warning."
14727 (if (fboundp 'display-warning)
14728 (display-warning 'org message
14729 (if (featurep 'xemacs)
14730 'warning
14731 :warning))
14732 (let ((buf (get-buffer-create "*Org warnings*")))
14733 (with-current-buffer buf
14734 (goto-char (point-max))
14735 (insert "Warning (Org): " message)
14736 (unless (bolp)
14737 (newline)))
14738 (display-buffer buf)
14739 (sit-for 0))))
14741 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14742 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14743 (if (and marker (marker-buffer marker)
14744 (buffer-live-p (marker-buffer marker)))
14745 (progn
14746 (switch-to-buffer (marker-buffer marker))
14747 (if (or (> marker (point-max)) (< marker (point-min)))
14748 (widen))
14749 (goto-char marker)
14750 (org-show-context 'org-goto))
14751 (if bookmark
14752 (bookmark-jump bookmark)
14753 (error "Cannot find location"))))
14755 (defun org-quote-csv-field (s)
14756 "Quote field for inclusion in CSV material."
14757 (if (string-match "[\",]" s)
14758 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14761 (defun org-plist-delete (plist property)
14762 "Delete PROPERTY from PLIST.
14763 This is in contrast to merely setting it to 0."
14764 (let (p)
14765 (while plist
14766 (if (not (eq property (car plist)))
14767 (setq p (plist-put p (car plist) (nth 1 plist))))
14768 (setq plist (cddr plist)))
14771 (defun org-force-self-insert (N)
14772 "Needed to enforce self-insert under remapping."
14773 (interactive "p")
14774 (self-insert-command N))
14776 (defun org-string-width (s)
14777 "Compute width of string, ignoring invisible characters.
14778 This ignores character with invisibility property `org-link', and also
14779 characters with property `org-cwidth', because these will become invisible
14780 upon the next fontification round."
14781 (let (b l)
14782 (when (or (eq t buffer-invisibility-spec)
14783 (assq 'org-link buffer-invisibility-spec))
14784 (while (setq b (text-property-any 0 (length s)
14785 'invisible 'org-link s))
14786 (setq s (concat (substring s 0 b)
14787 (substring s (or (next-single-property-change
14788 b 'invisible s) (length s)))))))
14789 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14790 (setq s (concat (substring s 0 b)
14791 (substring s (or (next-single-property-change
14792 b 'org-cwidth s) (length s))))))
14793 (setq l (string-width s) b -1)
14794 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14795 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14798 (defun org-get-indentation (&optional line)
14799 "Get the indentation of the current line, interpreting tabs.
14800 When LINE is given, assume it represents a line and compute its indentation."
14801 (if line
14802 (if (string-match "^ *" (org-remove-tabs line))
14803 (match-end 0))
14804 (save-excursion
14805 (beginning-of-line 1)
14806 (skip-chars-forward " \t")
14807 (current-column))))
14809 (defun org-remove-tabs (s &optional width)
14810 "Replace tabulators in S with spaces.
14811 Assumes that s is a single line, starting in column 0."
14812 (setq width (or width tab-width))
14813 (while (string-match "\t" s)
14814 (setq s (replace-match
14815 (make-string
14816 (- (* width (/ (+ (match-beginning 0) width) width))
14817 (match-beginning 0)) ?\ )
14818 t t s)))
14821 (defun org-fix-indentation (line ind)
14822 "Fix indentation in LINE.
14823 IND is a cons cell with target and minimum indentation.
14824 If the current indentation in LINE is smaller than the minimum,
14825 leave it alone. If it is larger than ind, set it to the target."
14826 (let* ((l (org-remove-tabs line))
14827 (i (org-get-indentation l))
14828 (i1 (car ind)) (i2 (cdr ind)))
14829 (if (>= i i2) (setq l (substring line i2)))
14830 (if (> i1 0)
14831 (concat (make-string i1 ?\ ) l)
14832 l)))
14834 (defun org-base-buffer (buffer)
14835 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14836 (if (not buffer)
14837 buffer
14838 (or (buffer-base-buffer buffer)
14839 buffer)))
14841 (defun org-trim (s)
14842 "Remove whitespace at beginning and end of string."
14843 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14844 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14847 (defun org-wrap (string &optional width lines)
14848 "Wrap string to either a number of lines, or a width in characters.
14849 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14850 that costs. If there is a word longer than WIDTH, the text is actually
14851 wrapped to the length of that word.
14852 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14853 many lines, whatever width that takes.
14854 The return value is a list of lines, without newlines at the end."
14855 (let* ((words (org-split-string string "[ \t\n]+"))
14856 (maxword (apply 'max (mapcar 'org-string-width words)))
14857 w ll)
14858 (cond (width
14859 (org-do-wrap words (max maxword width)))
14860 (lines
14861 (setq w maxword)
14862 (setq ll (org-do-wrap words maxword))
14863 (if (<= (length ll) lines)
14865 (setq ll words)
14866 (while (> (length ll) lines)
14867 (setq w (1+ w))
14868 (setq ll (org-do-wrap words w)))
14869 ll))
14870 (t (error "Cannot wrap this")))))
14872 (defun org-do-wrap (words width)
14873 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14874 (let (lines line)
14875 (while words
14876 (setq line (pop words))
14877 (while (and words (< (+ (length line) (length (car words))) width))
14878 (setq line (concat line " " (pop words))))
14879 (setq lines (push line lines)))
14880 (nreverse lines)))
14882 (defun org-split-string (string &optional separators)
14883 "Splits STRING into substrings at SEPARATORS.
14884 No empty strings are returned if there are matches at the beginning
14885 and end of string."
14886 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14887 (start 0)
14888 notfirst
14889 (list nil))
14890 (while (and (string-match rexp string
14891 (if (and notfirst
14892 (= start (match-beginning 0))
14893 (< start (length string)))
14894 (1+ start) start))
14895 (< (match-beginning 0) (length string)))
14896 (setq notfirst t)
14897 (or (eq (match-beginning 0) 0)
14898 (and (eq (match-beginning 0) (match-end 0))
14899 (eq (match-beginning 0) start))
14900 (setq list
14901 (cons (substring string start (match-beginning 0))
14902 list)))
14903 (setq start (match-end 0)))
14904 (or (eq start (length string))
14905 (setq list
14906 (cons (substring string start)
14907 list)))
14908 (nreverse list)))
14910 (defun org-uuidgen-p (s)
14911 "Is S an ID created by UUIDGEN?"
14912 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
14914 (defun org-context ()
14915 "Return a list of contexts of the current cursor position.
14916 If several contexts apply, all are returned.
14917 Each context entry is a list with a symbol naming the context, and
14918 two positions indicating start and end of the context. Possible
14919 contexts are:
14921 :headline anywhere in a headline
14922 :headline-stars on the leading stars in a headline
14923 :todo-keyword on a TODO keyword (including DONE) in a headline
14924 :tags on the TAGS in a headline
14925 :priority on the priority cookie in a headline
14926 :item on the first line of a plain list item
14927 :item-bullet on the bullet/number of a plain list item
14928 :checkbox on the checkbox in a plain list item
14929 :table in an org-mode table
14930 :table-special on a special filed in a table
14931 :table-table in a table.el table
14932 :link on a hyperlink
14933 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14934 :target on a <<target>>
14935 :radio-target on a <<<radio-target>>>
14936 :latex-fragment on a LaTeX fragment
14937 :latex-preview on a LaTeX fragment with overlayed preview image
14939 This function expects the position to be visible because it uses font-lock
14940 faces as a help to recognize the following contexts: :table-special, :link,
14941 and :keyword."
14942 (let* ((f (get-text-property (point) 'face))
14943 (faces (if (listp f) f (list f)))
14944 (p (point)) clist o)
14945 ;; First the large context
14946 (cond
14947 ((org-on-heading-p t)
14948 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14949 (when (progn
14950 (beginning-of-line 1)
14951 (looking-at org-todo-line-tags-regexp))
14952 (push (org-point-in-group p 1 :headline-stars) clist)
14953 (push (org-point-in-group p 2 :todo-keyword) clist)
14954 (push (org-point-in-group p 4 :tags) clist))
14955 (goto-char p)
14956 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14957 (if (looking-at "\\[#[A-Z0-9]\\]")
14958 (push (org-point-in-group p 0 :priority) clist)))
14960 ((org-at-item-p)
14961 (push (org-point-in-group p 2 :item-bullet) clist)
14962 (push (list :item (point-at-bol)
14963 (save-excursion (org-end-of-item) (point)))
14964 clist)
14965 (and (org-at-item-checkbox-p)
14966 (push (org-point-in-group p 0 :checkbox) clist)))
14968 ((org-at-table-p)
14969 (push (list :table (org-table-begin) (org-table-end)) clist)
14970 (if (memq 'org-formula faces)
14971 (push (list :table-special
14972 (previous-single-property-change p 'face)
14973 (next-single-property-change p 'face)) clist)))
14974 ((org-at-table-p 'any)
14975 (push (list :table-table) clist)))
14976 (goto-char p)
14978 ;; Now the small context
14979 (cond
14980 ((org-at-timestamp-p)
14981 (push (org-point-in-group p 0 :timestamp) clist))
14982 ((memq 'org-link faces)
14983 (push (list :link
14984 (previous-single-property-change p 'face)
14985 (next-single-property-change p 'face)) clist))
14986 ((memq 'org-special-keyword faces)
14987 (push (list :keyword
14988 (previous-single-property-change p 'face)
14989 (next-single-property-change p 'face)) clist))
14990 ((org-on-target-p)
14991 (push (org-point-in-group p 0 :target) clist)
14992 (goto-char (1- (match-beginning 0)))
14993 (if (looking-at org-radio-target-regexp)
14994 (push (org-point-in-group p 0 :radio-target) clist))
14995 (goto-char p))
14996 ((setq o (car (delq nil
14997 (mapcar
14998 (lambda (x)
14999 (if (memq x org-latex-fragment-image-overlays) x))
15000 (org-overlays-at (point))))))
15001 (push (list :latex-fragment
15002 (org-overlay-start o) (org-overlay-end o)) clist)
15003 (push (list :latex-preview
15004 (org-overlay-start o) (org-overlay-end o)) clist))
15005 ((org-inside-LaTeX-fragment-p)
15006 ;; FIXME: positions wrong.
15007 (push (list :latex-fragment (point) (point)) clist)))
15009 (setq clist (nreverse (delq nil clist)))
15010 clist))
15012 ;; FIXME: Compare with at-regexp-p Do we need both?
15013 (defun org-in-regexp (re &optional nlines visually)
15014 "Check if point is inside a match of regexp.
15015 Normally only the current line is checked, but you can include NLINES extra
15016 lines both before and after point into the search.
15017 If VISUALLY is set, require that the cursor is not after the match but
15018 really on, so that the block visually is on the match."
15019 (catch 'exit
15020 (let ((pos (point))
15021 (eol (point-at-eol (+ 1 (or nlines 0))))
15022 (inc (if visually 1 0)))
15023 (save-excursion
15024 (beginning-of-line (- 1 (or nlines 0)))
15025 (while (re-search-forward re eol t)
15026 (if (and (<= (match-beginning 0) pos)
15027 (>= (+ inc (match-end 0)) pos))
15028 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15030 (defun org-at-regexp-p (regexp)
15031 "Is point inside a match of REGEXP in the current line?"
15032 (catch 'exit
15033 (save-excursion
15034 (let ((pos (point)) (end (point-at-eol)))
15035 (beginning-of-line 1)
15036 (while (re-search-forward regexp end t)
15037 (if (and (<= (match-beginning 0) pos)
15038 (>= (match-end 0) pos))
15039 (throw 'exit t)))
15040 nil))))
15042 (defun org-occur-in-agenda-files (regexp &optional nlines)
15043 "Call `multi-occur' with buffers for all agenda files."
15044 (interactive "sOrg-files matching: \np")
15045 (let* ((files (org-agenda-files))
15046 (tnames (mapcar 'file-truename files))
15047 (extra org-agenda-text-search-extra-files)
15049 (when (eq (car extra) 'agenda-archives)
15050 (setq extra (cdr extra))
15051 (setq files (org-add-archive-files files)))
15052 (while (setq f (pop extra))
15053 (unless (member (file-truename f) tnames)
15054 (add-to-list 'files f 'append)
15055 (add-to-list 'tnames (file-truename f) 'append)))
15056 (multi-occur
15057 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15058 regexp)))
15060 (if (boundp 'occur-mode-find-occurrence-hook)
15061 ;; Emacs 23
15062 (add-hook 'occur-mode-find-occurrence-hook
15063 (lambda ()
15064 (when (org-mode-p)
15065 (org-reveal))))
15066 ;; Emacs 22
15067 (defadvice occur-mode-goto-occurrence
15068 (after org-occur-reveal activate)
15069 (and (org-mode-p) (org-reveal)))
15070 (defadvice occur-mode-goto-occurrence-other-window
15071 (after org-occur-reveal activate)
15072 (and (org-mode-p) (org-reveal)))
15073 (defadvice occur-mode-display-occurrence
15074 (after org-occur-reveal activate)
15075 (when (org-mode-p)
15076 (let ((pos (occur-mode-find-occurrence)))
15077 (with-current-buffer (marker-buffer pos)
15078 (save-excursion
15079 (goto-char pos)
15080 (org-reveal)))))))
15082 (defun org-uniquify (list)
15083 "Remove duplicate elements from LIST."
15084 (let (res)
15085 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15086 res))
15088 (defun org-delete-all (elts list)
15089 "Remove all elements in ELTS from LIST."
15090 (while elts
15091 (setq list (delete (pop elts) list)))
15092 list)
15094 (defun org-back-over-empty-lines ()
15095 "Move backwards over whitespace, to the beginning of the first empty line.
15096 Returns the number of empty lines passed."
15097 (let ((pos (point)))
15098 (skip-chars-backward " \t\n\r")
15099 (beginning-of-line 2)
15100 (goto-char (min (point) pos))
15101 (count-lines (point) pos)))
15103 (defun org-skip-whitespace ()
15104 (skip-chars-forward " \t\n\r"))
15106 (defun org-point-in-group (point group &optional context)
15107 "Check if POINT is in match-group GROUP.
15108 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15109 match. If the match group does ot exist or point is not inside it,
15110 return nil."
15111 (and (match-beginning group)
15112 (>= point (match-beginning group))
15113 (<= point (match-end group))
15114 (if context
15115 (list context (match-beginning group) (match-end group))
15116 t)))
15118 (defun org-switch-to-buffer-other-window (&rest args)
15119 "Switch to buffer in a second window on the current frame.
15120 In particular, do not allow pop-up frames."
15121 (let (pop-up-frames special-display-buffer-names special-display-regexps
15122 special-display-function)
15123 (apply 'switch-to-buffer-other-window args)))
15125 (defun org-combine-plists (&rest plists)
15126 "Create a single property list from all plists in PLISTS.
15127 The process starts by copying the first list, and then setting properties
15128 from the other lists. Settings in the last list are the most significant
15129 ones and overrule settings in the other lists."
15130 (let ((rtn (copy-sequence (pop plists)))
15131 p v ls)
15132 (while plists
15133 (setq ls (pop plists))
15134 (while ls
15135 (setq p (pop ls) v (pop ls))
15136 (setq rtn (plist-put rtn p v))))
15137 rtn))
15139 (defun org-move-line-down (arg)
15140 "Move the current line down. With prefix argument, move it past ARG lines."
15141 (interactive "p")
15142 (let ((col (current-column))
15143 beg end pos)
15144 (beginning-of-line 1) (setq beg (point))
15145 (beginning-of-line 2) (setq end (point))
15146 (beginning-of-line (+ 1 arg))
15147 (setq pos (move-marker (make-marker) (point)))
15148 (insert (delete-and-extract-region beg end))
15149 (goto-char pos)
15150 (org-move-to-column col)))
15152 (defun org-move-line-up (arg)
15153 "Move the current line up. With prefix argument, move it past ARG lines."
15154 (interactive "p")
15155 (let ((col (current-column))
15156 beg end pos)
15157 (beginning-of-line 1) (setq beg (point))
15158 (beginning-of-line 2) (setq end (point))
15159 (beginning-of-line (- arg))
15160 (setq pos (move-marker (make-marker) (point)))
15161 (insert (delete-and-extract-region beg end))
15162 (goto-char pos)
15163 (org-move-to-column col)))
15165 (defun org-replace-escapes (string table)
15166 "Replace %-escapes in STRING with values in TABLE.
15167 TABLE is an association list with keys like \"%a\" and string values.
15168 The sequences in STRING may contain normal field width and padding information,
15169 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15170 so values can contain further %-escapes if they are define later in TABLE."
15171 (let ((case-fold-search nil)
15172 e re rpl)
15173 (while (setq e (pop table))
15174 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15175 (while (string-match re string)
15176 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15177 (cdr e)))
15178 (setq string (replace-match rpl t t string))))
15179 string))
15182 (defun org-sublist (list start end)
15183 "Return a section of LIST, from START to END.
15184 Counting starts at 1."
15185 (let (rtn (c start))
15186 (setq list (nthcdr (1- start) list))
15187 (while (and list (<= c end))
15188 (push (pop list) rtn)
15189 (setq c (1+ c)))
15190 (nreverse rtn)))
15192 (defun org-find-base-buffer-visiting (file)
15193 "Like `find-buffer-visiting' but alway return the base buffer and
15194 not an indirect buffer."
15195 (let ((buf (find-buffer-visiting file)))
15196 (if buf
15197 (or (buffer-base-buffer buf) buf)
15198 nil)))
15200 (defun org-image-file-name-regexp (&optional extensions)
15201 "Return regexp matching the file names of images.
15202 If EXTENSIONS is given, only match these."
15203 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15204 (image-file-name-regexp)
15205 (let ((image-file-name-extensions
15206 (or extensions
15207 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15208 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15209 (concat "\\."
15210 (regexp-opt (nconc (mapcar 'upcase
15211 image-file-name-extensions)
15212 image-file-name-extensions)
15214 "\\'"))))
15216 (defun org-file-image-p (file &optional extensions)
15217 "Return non-nil if FILE is an image."
15218 (save-match-data
15219 (string-match (org-image-file-name-regexp extensions) file)))
15221 (defun org-get-cursor-date ()
15222 "Return the date at cursor in as a time.
15223 This works in the calendar and in the agenda, anywhere else it just
15224 returns the current time."
15225 (let (date day defd)
15226 (cond
15227 ((eq major-mode 'calendar-mode)
15228 (setq date (calendar-cursor-to-date)
15229 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15230 ((eq major-mode 'org-agenda-mode)
15231 (setq day (get-text-property (point) 'day))
15232 (if day
15233 (setq date (calendar-gregorian-from-absolute day)
15234 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15235 (nth 2 date))))))
15236 (or defd (current-time))))
15238 (defvar org-agenda-action-marker (make-marker)
15239 "Marker pointing to the entry for the next agenda action.")
15241 (defun org-mark-entry-for-agenda-action ()
15242 "Mark the current entry as target of an agenda action.
15243 Agenda actions are actions executed from the agenda with the key `k',
15244 which make use of the date at the cursor."
15245 (interactive)
15246 (move-marker org-agenda-action-marker
15247 (save-excursion (org-back-to-heading t) (point))
15248 (current-buffer))
15249 (message
15250 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15252 ;;; Paragraph filling stuff.
15253 ;; We want this to be just right, so use the full arsenal.
15255 (defun org-indent-line-function ()
15256 "Indent line like previous, but further if previous was headline or item."
15257 (interactive)
15258 (let* ((pos (point))
15259 (itemp (org-at-item-p))
15260 (org-drawer-regexp (or org-drawer-regexp "\000"))
15261 column bpos bcol tpos tcol bullet btype bullet-type)
15262 ;; Find the previous relevant line
15263 (beginning-of-line 1)
15264 (cond
15265 ((looking-at "#") (setq column 0))
15266 ((looking-at "\\*+ ") (setq column 0))
15267 ((and (looking-at "[ \t]*:END:")
15268 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15269 (save-excursion
15270 (goto-char (1- (match-beginning 1)))
15271 (setq column (current-column))))
15273 (beginning-of-line 0)
15274 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15275 (not (looking-at "[ \t]*:END:"))
15276 (not (looking-at org-drawer-regexp)))
15277 (beginning-of-line 0))
15278 (cond
15279 ((looking-at "\\*+[ \t]+")
15280 (if (not org-adapt-indentation)
15281 (setq column 0)
15282 (goto-char (match-end 0))
15283 (setq column (current-column))))
15284 ((looking-at org-drawer-regexp)
15285 (goto-char (1- (match-beginning 1)))
15286 (setq column (current-column)))
15287 ((looking-at "\\([ \t]*\\):END:")
15288 (goto-char (match-end 1))
15289 (setq column (current-column)))
15290 ((org-in-item-p)
15291 (org-beginning-of-item)
15292 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15293 (setq bpos (match-beginning 1) tpos (match-end 0)
15294 bcol (progn (goto-char bpos) (current-column))
15295 tcol (progn (goto-char tpos) (current-column))
15296 bullet (match-string 1)
15297 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15298 (if (> tcol (+ bcol org-description-max-indent))
15299 (setq tcol (+ bcol 5)))
15300 (if (not itemp)
15301 (setq column tcol)
15302 (goto-char pos)
15303 (beginning-of-line 1)
15304 (if (looking-at "\\S-")
15305 (progn
15306 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15307 (setq bullet (match-string 1)
15308 btype (if (string-match "[0-9]" bullet) "n" bullet))
15309 (setq column (if (equal btype bullet-type) bcol tcol)))
15310 (setq column (org-get-indentation)))))
15311 (t (setq column (org-get-indentation))))))
15312 (goto-char pos)
15313 (if (<= (current-column) (current-indentation))
15314 (org-indent-line-to column)
15315 (save-excursion (org-indent-line-to column)))
15316 (setq column (current-column))
15317 (beginning-of-line 1)
15318 (if (looking-at
15319 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15320 (replace-match (concat "\\1" (format org-property-format
15321 (match-string 2) (match-string 3)))
15322 t nil))
15323 (org-move-to-column column)))
15325 (defun org-set-autofill-regexps ()
15326 (interactive)
15327 ;; In the paragraph separator we include headlines, because filling
15328 ;; text in a line directly attached to a headline would otherwise
15329 ;; fill the headline as well.
15330 (org-set-local 'comment-start-skip "^#+[ \t]*")
15331 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15332 ;; The paragraph starter includes hand-formatted lists.
15333 (org-set-local 'paragraph-start
15334 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15335 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15336 ;; But only if the user has not turned off tables or fixed-width regions
15337 (org-set-local
15338 'auto-fill-inhibit-regexp
15339 (concat "\\*+ \\|#\\+"
15340 "\\|[ \t]*" org-keyword-time-regexp
15341 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15342 (concat
15343 "\\|[ \t]*["
15344 (if org-enable-table-editor "|" "")
15345 (if org-enable-fixed-width-editor ":" "")
15346 "]"))))
15347 ;; We use our own fill-paragraph function, to make sure that tables
15348 ;; and fixed-width regions are not wrapped. That function will pass
15349 ;; through to `fill-paragraph' when appropriate.
15350 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15351 ; Adaptive filling: To get full control, first make sure that
15352 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15353 (org-set-local 'adaptive-fill-regexp "\000")
15354 (org-set-local 'adaptive-fill-function
15355 'org-adaptive-fill-function)
15356 (org-set-local
15357 'align-mode-rules-list
15358 '((org-in-buffer-settings
15359 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15360 (modes . '(org-mode))))))
15362 (defun org-fill-paragraph (&optional justify)
15363 "Re-align a table, pass through to fill-paragraph if no table."
15364 (let ((table-p (org-at-table-p))
15365 (table.el-p (org-at-table.el-p)))
15366 (cond ((and (equal (char-after (point-at-bol)) ?*)
15367 (save-excursion (goto-char (point-at-bol))
15368 (looking-at outline-regexp)))
15369 t) ; skip headlines
15370 (table.el-p t) ; skip table.el tables
15371 (table-p (org-table-align) t) ; align org-mode tables
15372 (t nil)))) ; call paragraph-fill
15374 ;; For reference, this is the default value of adaptive-fill-regexp
15375 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15377 (defun org-adaptive-fill-function ()
15378 "Return a fill prefix for org-mode files.
15379 In particular, this makes sure hanging paragraphs for hand-formatted lists
15380 work correctly."
15381 (cond ((looking-at "#[ \t]+")
15382 (match-string 0))
15383 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15384 (save-excursion
15385 (if (> (match-end 1) (+ (match-beginning 1)
15386 org-description-max-indent))
15387 (goto-char (+ (match-beginning 1) 5))
15388 (goto-char (match-end 0)))
15389 (make-string (current-column) ?\ )))
15390 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15391 (save-excursion
15392 (goto-char (match-end 0))
15393 (make-string (current-column) ?\ )))
15394 (t nil)))
15396 ;;; Other stuff.
15398 (defun org-toggle-fixed-width-section (arg)
15399 "Toggle the fixed-width export.
15400 If there is no active region, the QUOTE keyword at the current headline is
15401 inserted or removed. When present, it causes the text between this headline
15402 and the next to be exported as fixed-width text, and unmodified.
15403 If there is an active region, this command adds or removes a colon as the
15404 first character of this line. If the first character of a line is a colon,
15405 this line is also exported in fixed-width font."
15406 (interactive "P")
15407 (let* ((cc 0)
15408 (regionp (org-region-active-p))
15409 (beg (if regionp (region-beginning) (point)))
15410 (end (if regionp (region-end)))
15411 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15412 (case-fold-search nil)
15413 (re "[ \t]*\\(: \\)")
15414 off)
15415 (if regionp
15416 (save-excursion
15417 (goto-char beg)
15418 (setq cc (current-column))
15419 (beginning-of-line 1)
15420 (setq off (looking-at re))
15421 (while (> nlines 0)
15422 (setq nlines (1- nlines))
15423 (beginning-of-line 1)
15424 (cond
15425 (arg
15426 (org-move-to-column cc t)
15427 (insert ": \n")
15428 (forward-line -1))
15429 ((and off (looking-at re))
15430 (replace-match "" t t nil 1))
15431 ((not off) (org-move-to-column cc t) (insert ": ")))
15432 (forward-line 1)))
15433 (save-excursion
15434 (org-back-to-heading)
15435 (if (looking-at (concat outline-regexp
15436 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15437 (replace-match "" t t nil 1)
15438 (if (looking-at outline-regexp)
15439 (progn
15440 (goto-char (match-end 0))
15441 (insert org-quote-string " "))))))))
15443 (defun org-reftex-citation ()
15444 "Use reftex-citation to insert a citation into the buffer.
15445 This looks for a line like
15447 #+BIBLIOGRAPHY: foo plain option:-d
15449 and derives from it that foo.bib is the bbliography file relevant
15450 for this document. It then installs the necessary environment for RefTeX
15451 to work in this buffer and calls `reftex-citation' to insert a citation
15452 into the buffer.
15454 Export of such citations to both LaTeX and HTML is handled by the contributed
15455 package org-exp-bibtex by Taru Karttunen."
15456 (interactive)
15457 (let ((reftex-docstruct-symbol 'rds)
15458 (reftex-cite-format "\\cite{%l}")
15459 rds bib)
15460 (save-excursion
15461 (save-restriction
15462 (widen)
15463 (let ((case-fold-search t)
15464 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
15465 (if (not (save-excursion
15466 (or (re-search-forward re nil t)
15467 (re-search-backward re nil t))))
15468 (error "No bibliography defined in file")
15469 (setq bib (concat (match-string 1) ".bib")
15470 rds (list (list 'bib bib)))))))
15471 (call-interactively 'reftex-citation)))
15473 ;;;; Functions extending outline functionality
15475 (defun org-beginning-of-line (&optional arg)
15476 "Go to the beginning of the current line. If that is invisible, continue
15477 to a visible line beginning. This makes the function of C-a more intuitive.
15478 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15479 first attempt, and only move to after the tags when the cursor is already
15480 beyond the end of the headline."
15481 (interactive "P")
15482 (let ((pos (point))
15483 (special (if (consp org-special-ctrl-a/e)
15484 (car org-special-ctrl-a/e)
15485 org-special-ctrl-a/e))
15486 refpos)
15487 (beginning-of-line 1)
15488 (if (and arg (fboundp 'move-beginning-of-line))
15489 (call-interactively 'move-beginning-of-line)
15490 (if (bobp)
15492 (backward-char 1)
15493 (if (org-invisible-p)
15494 (while (and (not (bobp)) (org-invisible-p))
15495 (backward-char 1)
15496 (beginning-of-line 1))
15497 (forward-char 1))))
15498 (when special
15499 (cond
15500 ((and (looking-at org-complex-heading-regexp)
15501 (= (char-after (match-end 1)) ?\ ))
15502 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15503 (point-at-eol)))
15504 (goto-char
15505 (if (eq special t)
15506 (cond ((> pos refpos) refpos)
15507 ((= pos (point)) refpos)
15508 (t (point)))
15509 (cond ((> pos (point)) (point))
15510 ((not (eq last-command this-command)) (point))
15511 (t refpos)))))
15512 ((org-at-item-p)
15513 (goto-char
15514 (if (eq special t)
15515 (cond ((> pos (match-end 4)) (match-end 4))
15516 ((= pos (point)) (match-end 4))
15517 (t (point)))
15518 (cond ((> pos (point)) (point))
15519 ((not (eq last-command this-command)) (point))
15520 (t (match-end 4))))))))
15521 (org-no-warnings
15522 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15524 (defun org-end-of-line (&optional arg)
15525 "Go to the end of the line.
15526 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15527 first attempt, and only move to after the tags when the cursor is already
15528 beyond the end of the headline."
15529 (interactive "P")
15530 (let ((special (if (consp org-special-ctrl-a/e)
15531 (cdr org-special-ctrl-a/e)
15532 org-special-ctrl-a/e)))
15533 (if (or (not special)
15534 (not (org-on-heading-p))
15535 arg)
15536 (call-interactively (if (fboundp 'move-end-of-line)
15537 'move-end-of-line
15538 'end-of-line))
15539 (let ((pos (point)))
15540 (beginning-of-line 1)
15541 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15542 (if (eq special t)
15543 (if (or (< pos (match-beginning 1))
15544 (= pos (match-end 0)))
15545 (goto-char (match-beginning 1))
15546 (goto-char (match-end 0)))
15547 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15548 (goto-char (match-end 0))
15549 (goto-char (match-beginning 1))))
15550 (call-interactively (if (fboundp 'move-end-of-line)
15551 'move-end-of-line
15552 'end-of-line)))))
15553 (org-no-warnings
15554 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15556 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15557 (define-key org-mode-map "\C-e" 'org-end-of-line)
15559 (defun org-backward-sentence (&optional arg)
15560 "Go to beginning of sentence, or beginning of table field.
15561 This will call `backward-sentence' or `org-table-beginning-of-field',
15562 depending on context."
15563 (interactive "P")
15564 (cond
15565 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
15566 (t (call-interactively 'backward-sentence))))
15568 (defun org-forward-sentence (&optional arg)
15569 "Go to end of sentence, or end of table field.
15570 This will call `forward-sentence' or `org-table-end-of-field',
15571 depending on context."
15572 (interactive "P")
15573 (cond
15574 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
15575 (t (call-interactively 'forward-sentence))))
15577 (define-key org-mode-map "\M-a" 'org-backward-sentence)
15578 (define-key org-mode-map "\M-e" 'org-forward-sentence)
15580 (defun org-kill-line (&optional arg)
15581 "Kill line, to tags or end of line."
15582 (interactive "P")
15583 (cond
15584 ((or (not org-special-ctrl-k)
15585 (bolp)
15586 (not (org-on-heading-p)))
15587 (call-interactively 'kill-line))
15588 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15589 (kill-region (point) (match-beginning 1))
15590 (org-set-tags nil t))
15591 (t (kill-region (point) (point-at-eol)))))
15593 (define-key org-mode-map "\C-k" 'org-kill-line)
15595 (defun org-yank (&optional arg)
15596 "Yank. If the kill is a subtree, treat it specially.
15597 This command will look at the current kill and check if is a single
15598 subtree, or a series of subtrees[1]. If it passes the test, and if the
15599 cursor is at the beginning of a line or after the stars of a currently
15600 empty headline, then the yank is handled specially. How exactly depends
15601 on the value of the following variables, both set by default.
15603 org-yank-folded-subtrees
15604 When set, the subtree(s) will be folded after insertion, but only
15605 if doing so would now swallow text after the yanked text.
15607 org-yank-adjusted-subtrees
15608 When set, the subtree will be promoted or demoted in order to
15609 fit into the local outline tree structure, which means that the level
15610 will be adjusted so that it becomes the smaller one of the two
15611 *visible* surrounding headings.
15613 Any prefix to this command will cause `yank' to be called directly with
15614 no special treatment. In particular, a simple `C-u' prefix will just
15615 plainly yank the text as it is.
15617 \[1] Basically, the test checks if the first non-white line is a heading
15618 and if there are no other headings with fewer stars."
15619 (interactive "P")
15620 (setq this-command 'yank)
15621 (if arg
15622 (call-interactively 'yank)
15623 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15624 (and (org-kill-is-subtree-p)
15625 (or (bolp)
15626 (and (looking-at "[ \t]*$")
15627 (string-match
15628 "\\`\\*+\\'"
15629 (buffer-substring (point-at-bol) (point)))))))
15630 swallowp)
15631 (cond
15632 ((and subtreep org-yank-folded-subtrees)
15633 (let ((beg (point))
15634 end)
15635 (if (and subtreep org-yank-adjusted-subtrees)
15636 (org-paste-subtree nil nil 'for-yank)
15637 (call-interactively 'yank))
15638 (setq end (point))
15639 (goto-char beg)
15640 (when (and (bolp) subtreep
15641 (not (setq swallowp
15642 (org-yank-folding-would-swallow-text beg end))))
15643 (or (looking-at outline-regexp)
15644 (re-search-forward (concat "^" outline-regexp) end t))
15645 (while (and (< (point) end) (looking-at outline-regexp))
15646 (hide-subtree)
15647 (org-cycle-show-empty-lines 'folded)
15648 (condition-case nil
15649 (outline-forward-same-level 1)
15650 (error (goto-char end)))))
15651 (when swallowp
15652 (message
15653 "Yanked text not folded because that would swallow text"))
15654 (goto-char end)
15655 (skip-chars-forward " \t\n\r")
15656 (beginning-of-line 1)
15657 (push-mark beg 'nomsg)))
15658 ((and subtreep org-yank-adjusted-subtrees)
15659 (let ((beg (point-at-bol)))
15660 (org-paste-subtree nil nil 'for-yank)
15661 (push-mark beg 'nomsg)))
15663 (call-interactively 'yank))))))
15665 (defun org-yank-folding-would-swallow-text (beg end)
15666 "Would hide-subtree at BEG swallow any text after END?"
15667 (let (level)
15668 (save-excursion
15669 (goto-char beg)
15670 (when (or (looking-at outline-regexp)
15671 (re-search-forward (concat "^" outline-regexp) end t))
15672 (setq level (org-outline-level)))
15673 (goto-char end)
15674 (skip-chars-forward " \t\r\n\v\f")
15675 (if (or (eobp)
15676 (and (bolp) (looking-at org-outline-regexp)
15677 (<= (org-outline-level) level)))
15678 nil ; Nothing would be swallowed
15679 t)))) ; something would swallow
15681 (define-key org-mode-map "\C-y" 'org-yank)
15683 (defun org-invisible-p ()
15684 "Check if point is at a character currently not visible."
15685 ;; Early versions of noutline don't have `outline-invisible-p'.
15686 (if (fboundp 'outline-invisible-p)
15687 (outline-invisible-p)
15688 (get-char-property (point) 'invisible)))
15690 (defun org-invisible-p2 ()
15691 "Check if point is at a character currently not visible."
15692 (save-excursion
15693 (if (and (eolp) (not (bobp))) (backward-char 1))
15694 ;; Early versions of noutline don't have `outline-invisible-p'.
15695 (if (fboundp 'outline-invisible-p)
15696 (outline-invisible-p)
15697 (get-char-property (point) 'invisible))))
15699 (defun org-back-to-heading (&optional invisible-ok)
15700 "Call `outline-back-to-heading', but provide a better error message."
15701 (condition-case nil
15702 (outline-back-to-heading invisible-ok)
15703 (error (error "Before first headline at position %d in buffer %s"
15704 (point) (current-buffer)))))
15706 (defun org-before-first-heading-p ()
15707 "Before first heading?"
15708 (save-excursion
15709 (null (re-search-backward "^\\*+ " nil t))))
15711 (defalias 'org-on-heading-p 'outline-on-heading-p)
15712 (defalias 'org-at-heading-p 'outline-on-heading-p)
15713 (defun org-at-heading-or-item-p ()
15714 (or (org-on-heading-p) (org-at-item-p)))
15716 (defun org-on-target-p ()
15717 (or (org-in-regexp org-radio-target-regexp)
15718 (org-in-regexp org-target-regexp)))
15720 (defun org-up-heading-all (arg)
15721 "Move to the heading line of which the present line is a subheading.
15722 This function considers both visible and invisible heading lines.
15723 With argument, move up ARG levels."
15724 (if (fboundp 'outline-up-heading-all)
15725 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15726 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15728 (defun org-up-heading-safe ()
15729 "Move to the heading line of which the present line is a subheading.
15730 This version will not throw an error. It will return the level of the
15731 headline found, or nil if no higher level is found.
15733 Also, this function will be a lot faster than `outline-up-heading',
15734 because it relies on stars being the outline starters. This can really
15735 make a significant difference in outlines with very many siblings."
15736 (let (start-level re)
15737 (org-back-to-heading t)
15738 (setq start-level (funcall outline-level))
15739 (if (equal start-level 1)
15741 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
15742 (if (re-search-backward re nil t)
15743 (funcall outline-level)))))
15745 (defun org-first-sibling-p ()
15746 "Is this heading the first child of its parents?"
15747 (interactive)
15748 (let ((re (concat "^" outline-regexp))
15749 level l)
15750 (unless (org-at-heading-p t)
15751 (error "Not at a heading"))
15752 (setq level (funcall outline-level))
15753 (save-excursion
15754 (if (not (re-search-backward re nil t))
15756 (setq l (funcall outline-level))
15757 (< l level)))))
15759 (defun org-goto-sibling (&optional previous)
15760 "Goto the next sibling, even if it is invisible.
15761 When PREVIOUS is set, go to the previous sibling instead. Returns t
15762 when a sibling was found. When none is found, return nil and don't
15763 move point."
15764 (let ((fun (if previous 're-search-backward 're-search-forward))
15765 (pos (point))
15766 (re (concat "^" outline-regexp))
15767 level l)
15768 (when (condition-case nil (org-back-to-heading t) (error nil))
15769 (setq level (funcall outline-level))
15770 (catch 'exit
15771 (or previous (forward-char 1))
15772 (while (funcall fun re nil t)
15773 (setq l (funcall outline-level))
15774 (when (< l level) (goto-char pos) (throw 'exit nil))
15775 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15776 (goto-char pos)
15777 nil))))
15779 (defun org-show-siblings ()
15780 "Show all siblings of the current headline."
15781 (save-excursion
15782 (while (org-goto-sibling) (org-flag-heading nil)))
15783 (save-excursion
15784 (while (org-goto-sibling 'previous)
15785 (org-flag-heading nil))))
15787 (defun org-show-hidden-entry ()
15788 "Show an entry where even the heading is hidden."
15789 (save-excursion
15790 (org-show-entry)))
15792 (defun org-flag-heading (flag &optional entry)
15793 "Flag the current heading. FLAG non-nil means make invisible.
15794 When ENTRY is non-nil, show the entire entry."
15795 (save-excursion
15796 (org-back-to-heading t)
15797 ;; Check if we should show the entire entry
15798 (if entry
15799 (progn
15800 (org-show-entry)
15801 (save-excursion
15802 (and (outline-next-heading)
15803 (org-flag-heading nil))))
15804 (outline-flag-region (max (point-min) (1- (point)))
15805 (save-excursion (outline-end-of-heading) (point))
15806 flag))))
15808 (defun org-forward-same-level (arg)
15809 "Move forward to the ARG'th subheading at same level as this one.
15810 Stop at the first and last subheadings of a superior heading.
15811 This is like outline-forward-same-level, but invisible headings are ok."
15812 (interactive "p")
15813 (org-back-to-heading t)
15814 (while (> arg 0)
15815 (let ((point-to-move-to (save-excursion
15816 (org-get-next-sibling))))
15817 (if point-to-move-to
15818 (progn
15819 (goto-char point-to-move-to)
15820 (setq arg (1- arg)))
15821 (progn
15822 (setq arg 0)
15823 (error "No following same-level heading"))))))
15825 (defun org-get-next-sibling ()
15826 "Move to next heading of the same level, and return point.
15827 If there is no such heading, return nil.
15828 This is like outline-next-sibling, but invisible headings are ok."
15829 (let ((level (funcall outline-level)))
15830 (outline-next-heading)
15831 (while (and (not (eobp)) (> (funcall outline-level) level))
15832 (outline-next-heading))
15833 (if (or (eobp) (< (funcall outline-level) level))
15835 (point))))
15837 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15838 ;; This is an exact copy of the original function, but it uses
15839 ;; `org-back-to-heading', to make it work also in invisible
15840 ;; trees. And is uses an invisible-OK argument.
15841 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15842 (org-back-to-heading invisible-OK)
15843 (let ((first t)
15844 (level (funcall outline-level)))
15845 (while (and (not (eobp))
15846 (or first (> (funcall outline-level) level)))
15847 (setq first nil)
15848 (outline-next-heading))
15849 (unless to-heading
15850 (if (memq (preceding-char) '(?\n ?\^M))
15851 (progn
15852 ;; Go to end of line before heading
15853 (forward-char -1)
15854 (if (memq (preceding-char) '(?\n ?\^M))
15855 ;; leave blank line before heading
15856 (forward-char -1))))))
15857 (point))
15859 (defun org-show-subtree ()
15860 "Show everything after this heading at deeper levels."
15861 (outline-flag-region
15862 (point)
15863 (save-excursion
15864 (outline-end-of-subtree) (outline-next-heading) (point))
15865 nil))
15867 (defun org-show-entry ()
15868 "Show the body directly following this heading.
15869 Show the heading too, if it is currently invisible."
15870 (interactive)
15871 (save-excursion
15872 (condition-case nil
15873 (progn
15874 (org-back-to-heading t)
15875 (outline-flag-region
15876 (max (point-min) (1- (point)))
15877 (save-excursion
15878 (if (re-search-forward
15879 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
15880 (match-beginning 1)
15881 (point-max)))
15882 nil))
15883 (error nil))))
15885 (defun org-make-options-regexp (kwds &optional extra)
15886 "Make a regular expression for keyword lines."
15887 (concat
15889 "#?[ \t]*\\+\\("
15890 (mapconcat 'regexp-quote kwds "\\|")
15891 (if extra (concat "\\|" extra))
15892 "\\):[ \t]*"
15893 "\\(.+\\)"))
15895 ;; Make isearch reveal the necessary context
15896 (defun org-isearch-end ()
15897 "Reveal context after isearch exits."
15898 (when isearch-success ; only if search was successful
15899 (if (featurep 'xemacs)
15900 ;; Under XEmacs, the hook is run in the correct place,
15901 ;; we directly show the context.
15902 (org-show-context 'isearch)
15903 ;; In Emacs the hook runs *before* restoring the overlays.
15904 ;; So we have to use a one-time post-command-hook to do this.
15905 ;; (Emacs 22 has a special variable, see function `org-mode')
15906 (unless (and (boundp 'isearch-mode-end-hook-quit)
15907 isearch-mode-end-hook-quit)
15908 ;; Only when the isearch was not quitted.
15909 (org-add-hook 'post-command-hook 'org-isearch-post-command
15910 'append 'local)))))
15912 (defun org-isearch-post-command ()
15913 "Remove self from hook, and show context."
15914 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15915 (org-show-context 'isearch))
15918 ;;;; Integration with and fixes for other packages
15920 ;;; Imenu support
15922 (defvar org-imenu-markers nil
15923 "All markers currently used by Imenu.")
15924 (make-variable-buffer-local 'org-imenu-markers)
15926 (defun org-imenu-new-marker (&optional pos)
15927 "Return a new marker for use by Imenu, and remember the marker."
15928 (let ((m (make-marker)))
15929 (move-marker m (or pos (point)))
15930 (push m org-imenu-markers)
15933 (defun org-imenu-get-tree ()
15934 "Produce the index for Imenu."
15935 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15936 (setq org-imenu-markers nil)
15937 (let* ((n org-imenu-depth)
15938 (re (concat "^" outline-regexp))
15939 (subs (make-vector (1+ n) nil))
15940 (last-level 0)
15941 m level head)
15942 (save-excursion
15943 (save-restriction
15944 (widen)
15945 (goto-char (point-max))
15946 (while (re-search-backward re nil t)
15947 (setq level (org-reduced-level (funcall outline-level)))
15948 (when (<= level n)
15949 (looking-at org-complex-heading-regexp)
15950 (setq head (org-link-display-format
15951 (org-match-string-no-properties 4))
15952 m (org-imenu-new-marker))
15953 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15954 (if (>= level last-level)
15955 (push (cons head m) (aref subs level))
15956 (push (cons head (aref subs (1+ level))) (aref subs level))
15957 (loop for i from (1+ level) to n do (aset subs i nil)))
15958 (setq last-level level)))))
15959 (aref subs 1)))
15961 (eval-after-load "imenu"
15962 '(progn
15963 (add-hook 'imenu-after-jump-hook
15964 (lambda ()
15965 (if (eq major-mode 'org-mode)
15966 (org-show-context 'org-goto))))))
15968 (defun org-link-display-format (link)
15969 "Replace a link with either the description, or the link target
15970 if no description is present"
15971 (save-match-data
15972 (if (string-match org-bracket-link-analytic-regexp link)
15973 (replace-match (or (match-string 5 link)
15974 (concat (match-string 1 link)
15975 (match-string 3 link)))
15976 nil nil link)
15977 link)))
15979 ;; Speedbar support
15981 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15982 "Overlay marking the agenda restriction line in speedbar.")
15983 (org-overlay-put org-speedbar-restriction-lock-overlay
15984 'face 'org-agenda-restriction-lock)
15985 (org-overlay-put org-speedbar-restriction-lock-overlay
15986 'help-echo "Agendas are currently limited to this item.")
15987 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15989 (defun org-speedbar-set-agenda-restriction ()
15990 "Restrict future agenda commands to the location at point in speedbar.
15991 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15992 (interactive)
15993 (require 'org-agenda)
15994 (let (p m tp np dir txt)
15995 (cond
15996 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15997 'org-imenu t))
15998 (setq m (get-text-property p 'org-imenu-marker))
15999 (save-excursion
16000 (save-restriction
16001 (set-buffer (marker-buffer m))
16002 (goto-char m)
16003 (org-agenda-set-restriction-lock 'subtree))))
16004 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16005 'speedbar-function 'speedbar-find-file))
16006 (setq tp (previous-single-property-change
16007 (1+ p) 'speedbar-function)
16008 np (next-single-property-change
16009 tp 'speedbar-function)
16010 dir (speedbar-line-directory)
16011 txt (buffer-substring-no-properties (or tp (point-min))
16012 (or np (point-max))))
16013 (save-excursion
16014 (save-restriction
16015 (set-buffer (find-file-noselect
16016 (let ((default-directory dir))
16017 (expand-file-name txt))))
16018 (unless (org-mode-p)
16019 (error "Cannot restrict to non-Org-mode file"))
16020 (org-agenda-set-restriction-lock 'file))))
16021 (t (error "Don't know how to restrict Org-mode's agenda")))
16022 (org-move-overlay org-speedbar-restriction-lock-overlay
16023 (point-at-bol) (point-at-eol))
16024 (setq current-prefix-arg nil)
16025 (org-agenda-maybe-redo)))
16027 (eval-after-load "speedbar"
16028 '(progn
16029 (speedbar-add-supported-extension ".org")
16030 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16031 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16032 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16033 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16034 (add-hook 'speedbar-visiting-tag-hook
16035 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16038 ;;; Fixes and Hacks for problems with other packages
16040 ;; Make flyspell not check words in links, to not mess up our keymap
16041 (defun org-mode-flyspell-verify ()
16042 "Don't let flyspell put overlays at active buttons."
16043 (not (get-text-property (point) 'keymap)))
16045 ;; Make `bookmark-jump' show the jump location if it was hidden.
16046 (eval-after-load "bookmark"
16047 '(if (boundp 'bookmark-after-jump-hook)
16048 ;; We can use the hook
16049 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16050 ;; Hook not available, use advice
16051 (defadvice bookmark-jump (after org-make-visible activate)
16052 "Make the position visible."
16053 (org-bookmark-jump-unhide))))
16055 ;; Make sure saveplace show the location if it was hidden
16056 (eval-after-load "saveplace"
16057 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16058 "Make the position visible."
16059 (org-bookmark-jump-unhide)))
16061 (defun org-bookmark-jump-unhide ()
16062 "Unhide the current position, to show the bookmark location."
16063 (and (org-mode-p)
16064 (or (org-invisible-p)
16065 (save-excursion (goto-char (max (point-min) (1- (point))))
16066 (org-invisible-p)))
16067 (org-show-context 'bookmark-jump)))
16069 ;; Make session.el ignore our circular variable
16070 (eval-after-load "session"
16071 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16073 ;;;; Experimental code
16075 (defun org-closed-in-range ()
16076 "Sparse tree of items closed in a certain time range.
16077 Still experimental, may disappear in the future."
16078 (interactive)
16079 ;; Get the time interval from the user.
16080 (let* ((time1 (time-to-seconds
16081 (org-read-date nil 'to-time nil "Starting date: ")))
16082 (time2 (time-to-seconds
16083 (org-read-date nil 'to-time nil "End date:")))
16084 ;; callback function
16085 (callback (lambda ()
16086 (let ((time
16087 (time-to-seconds
16088 (apply 'encode-time
16089 (org-parse-time-string
16090 (match-string 1))))))
16091 ;; check if time in interval
16092 (and (>= time time1) (<= time time2))))))
16093 ;; make tree, check each match with the callback
16094 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16096 ;;;; Finish up
16098 (provide 'org)
16100 (run-hooks 'org-load-hook)
16102 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16104 ;;; org.el ends here