iCalendar and XOXO export: Functions moved to new files.
[org-mode.git] / lisp / org.el
blob843f2b4a0aa5f360a47a6ab955a3fa2b27e982f6
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.25trans
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.25trans"
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-pre-cycle-hook nil
630 "Hook that is run before visibility cycling is happening.
631 The function(s) in this hook must accept a single argument which indicates
632 the new state that will be set right after running this hook. The
633 argument is a symbol. Before a global state change, it can have the values
634 `overview', `content', or `all'. Before a local state change, it can have
635 the values `folded', `children', or `subtree'."
636 :group 'org-cycle
637 :type 'hook)
639 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
640 org-cycle-hide-drawers
641 org-cycle-show-empty-lines
642 org-optimize-window-after-visibility-change)
643 "Hook that is run after `org-cycle' has changed the buffer visibility.
644 The function(s) in this hook must accept a single argument which indicates
645 the new state that was set by the most recent `org-cycle' command. The
646 argument is a symbol. After a global state change, it can have the values
647 `overview', `content', or `all'. After a local state change, it can have
648 the values `folded', `children', or `subtree'."
649 :group 'org-cycle
650 :type 'hook)
652 (defgroup org-edit-structure nil
653 "Options concerning structure editing in Org-mode."
654 :tag "Org Edit Structure"
655 :group 'org-structure)
657 (defcustom org-odd-levels-only nil
658 "Non-nil means, skip even levels and only use odd levels for the outline.
659 This has the effect that two stars are being added/taken away in
660 promotion/demotion commands. It also influences how levels are
661 handled by the exporters.
662 Changing it requires restart of `font-lock-mode' to become effective
663 for fontification also in regions already fontified.
664 You may also set this on a per-file basis by adding one of the following
665 lines to the buffer:
667 #+STARTUP: odd
668 #+STARTUP: oddeven"
669 :group 'org-edit-structure
670 :group 'org-font-lock
671 :type 'boolean)
673 (defcustom org-adapt-indentation t
674 "Non-nil means, adapt indentation when promoting and demoting.
675 When this is set and the *entire* text in an entry is indented, the
676 indentation is increased by one space in a demotion command, and
677 decreased by one in a promotion command. If any line in the entry
678 body starts at column 0, indentation is not changed at all."
679 :group 'org-edit-structure
680 :type 'boolean)
682 (defcustom org-special-ctrl-a/e nil
683 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
685 When t, `C-a' will bring back the cursor to the beginning of the
686 headline text, i.e. after the stars and after a possible TODO keyword.
687 In an item, this will be the position after the bullet.
688 When the cursor is already at that position, another `C-a' will bring
689 it to the beginning of the line.
691 `C-e' will jump to the end of the headline, ignoring the presence of tags
692 in the headline. A second `C-e' will then jump to the true end of the
693 line, after any tags.
695 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
696 and only a directly following, identical keypress will bring the cursor
697 to the special positions.
699 This may also be a cons cell where the behavior for `C-a' and `C-e' is
700 set separately."
701 :group 'org-edit-structure
702 :type '(choice
703 (const :tag "off" nil)
704 (const :tag "after stars/bullet and before tags first" t)
705 (const :tag "true line boundary first" reversed)
706 (cons :tag "Set C-a and C-e separately"
707 (choice :tag "Special C-a"
708 (const :tag "off" nil)
709 (const :tag "after stars/bullet first" t)
710 (const :tag "before stars/bullet first" reversed))
711 (choice :tag "Special C-e"
712 (const :tag "off" nil)
713 (const :tag "before tags first" t)
714 (const :tag "after tags first" reversed)))))
715 (if (fboundp 'defvaralias)
716 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
718 (defcustom org-special-ctrl-k nil
719 "Non-nil means `C-k' will behave specially in headlines.
720 When nil, `C-k' will call the default `kill-line' command.
721 When t, the following will happen while the cursor is in the headline:
723 - When the cursor is at the beginning of a headline, kill the entire
724 line and possible the folded subtree below the line.
725 - When in the middle of the headline text, kill the headline up to the tags.
726 - When after the headline text, kill the tags."
727 :group 'org-edit-structure
728 :type 'boolean)
730 (defcustom org-yank-folded-subtrees t
731 "Non-nil means, when yanking subtrees, fold them.
732 If the kill is a single subtree, or a sequence of subtrees, i.e. if
733 it starts with a heading and all other headings in it are either children
734 or siblings, then fold all the subtrees. However, do this only if no
735 text after the yank would be swallowed into a folded tree by this action."
736 :group 'org-edit-structure
737 :type 'boolean)
739 (defcustom org-yank-adjusted-subtrees nil
740 "Non-nil means, when yanking subtrees, adjust the level.
741 With this setting, `org-paste-subtree' is used to insert the subtree, see
742 this function for details."
743 :group 'org-edit-structure
744 :type 'boolean)
746 (defcustom org-M-RET-may-split-line '((default . t))
747 "Non-nil means, M-RET will split the line at the cursor position.
748 When nil, it will go to the end of the line before making a
749 new line.
750 You may also set this option in a different way for different
751 contexts. Valid contexts are:
753 headline when creating a new headline
754 item when creating a new item
755 table in a table field
756 default the value to be used for all contexts not explicitly
757 customized"
758 :group 'org-structure
759 :group 'org-table
760 :type '(choice
761 (const :tag "Always" t)
762 (const :tag "Never" nil)
763 (repeat :greedy t :tag "Individual contexts"
764 (cons
765 (choice :tag "Context"
766 (const headline)
767 (const item)
768 (const table)
769 (const default))
770 (boolean)))))
773 (defcustom org-insert-heading-respect-content nil
774 "Non-nil means, insert new headings after the current subtree.
775 When nil, the new heading is created directly after the current line.
776 The commands \\[org-insert-heading-respect-content] and
777 \\[org-insert-todo-heading-respect-content] turn this variable on
778 for the duration of the command."
779 :group 'org-structure
780 :type 'boolean)
782 (defcustom org-blank-before-new-entry '((heading . auto)
783 (plain-list-item . auto))
784 "Should `org-insert-heading' leave a blank line before new heading/item?
785 The value is an alist, with `heading' and `plain-list-item' as car,
786 and a boolean flag as cdr. For plain lists, if the variable
787 `org-empty-line-terminates-plain-lists' is set, the setting here
788 is ignored and no empty line is inserted, to keep the list in tact."
789 :group 'org-edit-structure
790 :type '(list
791 (cons (const heading)
792 (choice (const :tag "Never" nil)
793 (const :tag "Always" t)
794 (const :tag "Auto" auto)))
795 (cons (const plain-list-item)
796 (choice (const :tag "Never" nil)
797 (const :tag "Always" t)
798 (const :tag "Auto" auto)))))
800 (defcustom org-insert-heading-hook nil
801 "Hook being run after inserting a new heading."
802 :group 'org-edit-structure
803 :type 'hook)
805 (defcustom org-enable-fixed-width-editor t
806 "Non-nil means, lines starting with \":\" are treated as fixed-width.
807 This currently only means, they are never auto-wrapped.
808 When nil, such lines will be treated like ordinary lines.
809 See also the QUOTE keyword."
810 :group 'org-edit-structure
811 :type 'boolean)
813 (defcustom org-edit-src-region-extra nil
814 "Additional regexps to identify regions for editing with `org-edit-src-code'.
815 For examples see the function `org-edit-src-find-region-and-lang'.
816 The regular expression identifying the begin marker should end with a newline,
817 and the regexp marking the end line should start with a newline, to make sure
818 there are kept outside the narrowed region."
819 :group 'org-edit-structure
820 :type '(repeat
821 (list
822 (regexp :tag "begin regexp")
823 (regexp :tag "end regexp")
824 (choice :tag "language"
825 (string :tag "specify")
826 (integer :tag "from match group")
827 (const :tag "from `lang' element")
828 (const :tag "from `style' element")))))
830 (defcustom org-coderef-label-format "(ref:%s)"
831 "The default coderef format.
832 This format string will be used to search for coderef labels in literal
833 examples (EXAMPLE and SRC blocks). The format can be overwritten
834 an individual literal example with the -f option, like
836 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
838 #+END_SRC
840 If you want to use this for HTML export, make sure that the format does
841 not introduce special font-locking, and avoid the HTML special
842 characters `<', `>', and `&'. The reason for this restriction is that
843 the labels are searched for only after htmlize has done its job."
844 :group 'org-edit-structure ; FIXME this is not in the right group
845 :type 'string)
847 (defcustom org-edit-fixed-width-region-mode 'artist-mode
848 "The mode that should be used to edit fixed-width regions.
849 These are the regions where each line starts with a colon."
850 :group 'org-edit-structure
851 :type '(choice
852 (const artist-mode)
853 (const picture-mode)
854 (const fundamental-mode)
855 (function :tag "Other (specify)")))
857 (defcustom org-goto-auto-isearch t
858 "Non-nil means, typing characters in org-goto starts incremental search."
859 :group 'org-edit-structure
860 :type 'boolean)
862 (defgroup org-sparse-trees nil
863 "Options concerning sparse trees in Org-mode."
864 :tag "Org Sparse Trees"
865 :group 'org-structure)
867 (defcustom org-highlight-sparse-tree-matches t
868 "Non-nil means, highlight all matches that define a sparse tree.
869 The highlights will automatically disappear the next time the buffer is
870 changed by an edit command."
871 :group 'org-sparse-trees
872 :type 'boolean)
874 (defcustom org-remove-highlights-with-change t
875 "Non-nil means, any change to the buffer will remove temporary highlights.
876 Such highlights are created by `org-occur' and `org-clock-display'.
877 When nil, `C-c C-c needs to be used to get rid of the highlights.
878 The highlights created by `org-preview-latex-fragment' always need
879 `C-c C-c' to be removed."
880 :group 'org-sparse-trees
881 :group 'org-time
882 :type 'boolean)
885 (defcustom org-occur-hook '(org-first-headline-recenter)
886 "Hook that is run after `org-occur' has constructed a sparse tree.
887 This can be used to recenter the window to show as much of the structure
888 as possible."
889 :group 'org-sparse-trees
890 :type 'hook)
892 (defgroup org-imenu-and-speedbar nil
893 "Options concerning imenu and speedbar in Org-mode."
894 :tag "Org Imenu and Speedbar"
895 :group 'org-structure)
897 (defcustom org-imenu-depth 2
898 "The maximum level for Imenu access to Org-mode headlines.
899 This also applied for speedbar access."
900 :group 'org-imenu-and-speedbar
901 :type 'integer)
903 (defgroup org-table nil
904 "Options concerning tables in Org-mode."
905 :tag "Org Table"
906 :group 'org)
908 (defcustom org-enable-table-editor 'optimized
909 "Non-nil means, lines starting with \"|\" are handled by the table editor.
910 When nil, such lines will be treated like ordinary lines.
912 When equal to the symbol `optimized', the table editor will be optimized to
913 do the following:
914 - Automatic overwrite mode in front of whitespace in table fields.
915 This makes the structure of the table stay in tact as long as the edited
916 field does not exceed the column width.
917 - Minimize the number of realigns. Normally, the table is aligned each time
918 TAB or RET are pressed to move to another field. With optimization this
919 happens only if changes to a field might have changed the column width.
920 Optimization requires replacing the functions `self-insert-command',
921 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
922 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
923 very good at guessing when a re-align will be necessary, but you can always
924 force one with \\[org-ctrl-c-ctrl-c].
926 If you would like to use the optimized version in Org-mode, but the
927 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
929 This variable can be used to turn on and off the table editor during a session,
930 but in order to toggle optimization, a restart is required.
932 See also the variable `org-table-auto-blank-field'."
933 :group 'org-table
934 :type '(choice
935 (const :tag "off" nil)
936 (const :tag "on" t)
937 (const :tag "on, optimized" optimized)))
939 (defcustom org-self-insert-cluster-for-undo t
940 "Non-nil means cluster self-insert commands for undo when possible.
941 If this is set, then, like in the Emacs command loop, 20 consequtive
942 characters will be undone together.
943 This is configurable, because there is some impact on typing performance."
944 :group 'org-table
945 :type 'boolean)
947 (defcustom org-table-tab-recognizes-table.el t
948 "Non-nil means, TAB will automatically notice a table.el table.
949 When it sees such a table, it moves point into it and - if necessary -
950 calls `table-recognize-table'."
951 :group 'org-table-editing
952 :type 'boolean)
954 (defgroup org-link nil
955 "Options concerning links in Org-mode."
956 :tag "Org Link"
957 :group 'org)
959 (defvar org-link-abbrev-alist-local nil
960 "Buffer-local version of `org-link-abbrev-alist', which see.
961 The value of this is taken from the #+LINK lines.")
962 (make-variable-buffer-local 'org-link-abbrev-alist-local)
964 (defcustom org-link-abbrev-alist nil
965 "Alist of link abbreviations.
966 The car of each element is a string, to be replaced at the start of a link.
967 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
968 links in Org-mode buffers can have an optional tag after a double colon, e.g.
970 [[linkkey:tag][description]]
972 The 'linkkey' must be a word word, starting with a letter, followed
973 by letters, numbers, '-' or '_'.
975 If REPLACE is a string, the tag will simply be appended to create the link.
976 If the string contains \"%s\", the tag will be inserted there. Alternatively,
977 the placeholder \"%h\" will cause a url-encoded version of the tag to
978 be inserted at that point (see the function `url-hexify-string').
980 REPLACE may also be a function that will be called with the tag as the
981 only argument to create the link, which should be returned as a string.
983 See the manual for examples."
984 :group 'org-link
985 :type '(repeat
986 (cons
987 (string :tag "Protocol")
988 (choice
989 (string :tag "Format")
990 (function)))))
992 (defcustom org-descriptive-links t
993 "Non-nil means, hide link part and only show description of bracket links.
994 Bracket links are like [[link][description]]. This variable sets the initial
995 state in new org-mode buffers. The setting can then be toggled on a
996 per-buffer basis from the Org->Hyperlinks menu."
997 :group 'org-link
998 :type 'boolean)
1000 (defcustom org-link-file-path-type 'adaptive
1001 "How the path name in file links should be stored.
1002 Valid values are:
1004 relative Relative to the current directory, i.e. the directory of the file
1005 into which the link is being inserted.
1006 absolute Absolute path, if possible with ~ for home directory.
1007 noabbrev Absolute path, no abbreviation of home directory.
1008 adaptive Use relative path for files in the current directory and sub-
1009 directories of it. For other files, use an absolute path."
1010 :group 'org-link
1011 :type '(choice
1012 (const relative)
1013 (const absolute)
1014 (const noabbrev)
1015 (const adaptive)))
1017 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1018 "Types of links that should be activated in Org-mode files.
1019 This is a list of symbols, each leading to the activation of a certain link
1020 type. In principle, it does not hurt to turn on most link types - there may
1021 be a small gain when turning off unused link types. The types are:
1023 bracket The recommended [[link][description]] or [[link]] links with hiding.
1024 angular Links in angular brackets that may contain whitespace like
1025 <bbdb:Carsten Dominik>.
1026 plain Plain links in normal text, no whitespace, like http://google.com.
1027 radio Text that is matched by a radio target, see manual for details.
1028 tag Tag settings in a headline (link to tag search).
1029 date Time stamps (link to calendar).
1030 footnote Footnote labels.
1032 Changing this variable requires a restart of Emacs to become effective."
1033 :group 'org-link
1034 :type '(set :greedy t
1035 (const :tag "Double bracket links (new style)" bracket)
1036 (const :tag "Angular bracket links (old style)" angular)
1037 (const :tag "Plain text links" plain)
1038 (const :tag "Radio target matches" radio)
1039 (const :tag "Tags" tag)
1040 (const :tag "Timestamps" date)
1041 (const :tag "Footnotes" footnote)))
1043 (defcustom org-make-link-description-function nil
1044 "Function to use to generate link descriptions from links. If
1045 nil the link location will be used. This function must take two
1046 parameters; the first is the link and the second the description
1047 org-insert-link has generated, and should return the description
1048 to use."
1049 :group 'org-link
1050 :type 'function)
1052 (defgroup org-link-store nil
1053 "Options concerning storing links in Org-mode."
1054 :tag "Org Store Link"
1055 :group 'org-link)
1057 (defcustom org-email-link-description-format "Email %c: %.30s"
1058 "Format of the description part of a link to an email or usenet message.
1059 The following %-escapes will be replaced by corresponding information:
1061 %F full \"From\" field
1062 %f name, taken from \"From\" field, address if no name
1063 %T full \"To\" field
1064 %t first name in \"To\" field, address if no name
1065 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1066 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1067 %s subject
1068 %m message-id.
1070 You may use normal field width specification between the % and the letter.
1071 This is for example useful to limit the length of the subject.
1073 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1074 :group 'org-link-store
1075 :type 'string)
1077 (defcustom org-from-is-user-regexp
1078 (let (r1 r2)
1079 (when (and user-mail-address (not (string= user-mail-address "")))
1080 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1081 (when (and user-full-name (not (string= user-full-name "")))
1082 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1083 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1084 "Regexp matched against the \"From:\" header of an email or usenet message.
1085 It should match if the message is from the user him/herself."
1086 :group 'org-link-store
1087 :type 'regexp)
1089 (defcustom org-link-to-org-use-id 'create-if-interactive
1090 "Non-nil means, storing a link to an Org file will use entry IDs.
1092 Note that before this variable is even considered, org-id must be loaded,
1093 to please customize `org-modules' and turn it on.
1095 The variable can have the following values:
1097 t Create an ID if needed to make a link to the current entry.
1099 create-if-interactive
1100 If `org-store-link' is called directly (interactively, as a user
1101 command), do create an ID to support the link. But when doing the
1102 job for remember, only use the ID if it already exists. The
1103 purpose of this setting is to avoid proliferation of unwanted
1104 IDs, just because you happen to be in an Org file when you
1105 call `org-remember' that automatically and preemptively
1106 creates a link. If you do want to get an ID link in a remember
1107 template to an entry not having an ID, create it first by
1108 explicitly creating a link to it, using `C-c C-l' first.
1110 use-existing
1111 Use existing ID, do not create one.
1113 nil Never use an ID to make a link, instead link using a text search for
1114 the headline text."
1115 :group 'org-link-store
1116 :type '(choice
1117 (const :tag "Create ID to make link" t)
1118 (const :tag "Create if string link interactively"
1119 'create-if-interactive)
1120 (const :tag "Only use existing" 'use-existing)
1121 (const :tag "Do not use ID to create link" nil)))
1123 (defcustom org-context-in-file-links t
1124 "Non-nil means, file links from `org-store-link' contain context.
1125 A search string will be added to the file name with :: as separator and
1126 used to find the context when the link is activated by the command
1127 `org-open-at-point'.
1128 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1129 negates this setting for the duration of the command."
1130 :group 'org-link-store
1131 :type 'boolean)
1133 (defcustom org-keep-stored-link-after-insertion nil
1134 "Non-nil means, keep link in list for entire session.
1136 The command `org-store-link' adds a link pointing to the current
1137 location to an internal list. These links accumulate during a session.
1138 The command `org-insert-link' can be used to insert links into any
1139 Org-mode file (offering completion for all stored links). When this
1140 option is nil, every link which has been inserted once using \\[org-insert-link]
1141 will be removed from the list, to make completing the unused links
1142 more efficient."
1143 :group 'org-link-store
1144 :type 'boolean)
1146 (defgroup org-link-follow nil
1147 "Options concerning following links in Org-mode."
1148 :tag "Org Follow Link"
1149 :group 'org-link)
1151 (defcustom org-link-translation-function nil
1152 "Function to translate links with different syntax to Org syntax.
1153 This can be used to translate links created for example by the Planner
1154 or emacs-wiki packages to Org syntax.
1155 The function must accept two parameters, a TYPE containing the link
1156 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1157 which is everything after the link protocol. It should return a cons
1158 with possibly modified values of type and path.
1159 Org contains a function for this, so if you set this variable to
1160 `org-translate-link-from-planner', you should be able follow many
1161 links created by planner."
1162 :group 'org-link-follow
1163 :type 'function)
1165 (defcustom org-follow-link-hook nil
1166 "Hook that is run after a link has been followed."
1167 :group 'org-link-follow
1168 :type 'hook)
1170 (defcustom org-tab-follows-link nil
1171 "Non-nil means, on links TAB will follow the link.
1172 Needs to be set before org.el is loaded.
1173 This really should not be used, it does not make sense, and the
1174 implementation is bad."
1175 :group 'org-link-follow
1176 :type 'boolean)
1178 (defcustom org-return-follows-link nil
1179 "Non-nil means, on links RET will follow the link.
1180 Needs to be set before org.el is loaded."
1181 :group 'org-link-follow
1182 :type 'boolean)
1184 (defcustom org-mouse-1-follows-link
1185 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1186 "Non-nil means, mouse-1 on a link will follow the link.
1187 A longer mouse click will still set point. Does not work on XEmacs.
1188 Needs to be set before org.el is loaded."
1189 :group 'org-link-follow
1190 :type 'boolean)
1192 (defcustom org-mark-ring-length 4
1193 "Number of different positions to be recorded in the ring
1194 Changing this requires a restart of Emacs to work correctly."
1195 :group 'org-link-follow
1196 :type 'integer)
1198 (defcustom org-link-frame-setup
1199 '((vm . vm-visit-folder-other-frame)
1200 (gnus . gnus-other-frame)
1201 (file . find-file-other-window))
1202 "Setup the frame configuration for following links.
1203 When following a link with Emacs, it may often be useful to display
1204 this link in another window or frame. This variable can be used to
1205 set this up for the different types of links.
1206 For VM, use any of
1207 `vm-visit-folder'
1208 `vm-visit-folder-other-frame'
1209 For Gnus, use any of
1210 `gnus'
1211 `gnus-other-frame'
1212 `org-gnus-no-new-news'
1213 For FILE, use any of
1214 `find-file'
1215 `find-file-other-window'
1216 `find-file-other-frame'
1217 For the calendar, use the variable `calendar-setup'.
1218 For BBDB, it is currently only possible to display the matches in
1219 another window."
1220 :group 'org-link-follow
1221 :type '(list
1222 (cons (const vm)
1223 (choice
1224 (const vm-visit-folder)
1225 (const vm-visit-folder-other-window)
1226 (const vm-visit-folder-other-frame)))
1227 (cons (const gnus)
1228 (choice
1229 (const gnus)
1230 (const gnus-other-frame)
1231 (const org-gnus-no-new-news)))
1232 (cons (const file)
1233 (choice
1234 (const find-file)
1235 (const find-file-other-window)
1236 (const find-file-other-frame)))))
1238 (defcustom org-display-internal-link-with-indirect-buffer nil
1239 "Non-nil means, use indirect buffer to display infile links.
1240 Activating internal links (from one location in a file to another location
1241 in the same file) normally just jumps to the location. When the link is
1242 activated with a C-u prefix (or with mouse-3), the link is displayed in
1243 another window. When this option is set, the other window actually displays
1244 an indirect buffer clone of the current buffer, to avoid any visibility
1245 changes to the current buffer."
1246 :group 'org-link-follow
1247 :type 'boolean)
1249 (defcustom org-open-non-existing-files nil
1250 "Non-nil means, `org-open-file' will open non-existing files.
1251 When nil, an error will be generated."
1252 :group 'org-link-follow
1253 :type 'boolean)
1255 (defcustom org-open-directory-means-index-dot-org nil
1256 "Non-nil means, a link to a directory really means to index.org.
1257 When nil, following a directory link will run dired or open a finder/explorer
1258 window on that directory."
1259 :group 'org-link-follow
1260 :type 'boolean)
1262 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1263 "Function and arguments to call for following mailto links.
1264 This is a list with the first element being a lisp function, and the
1265 remaining elements being arguments to the function. In string arguments,
1266 %a will be replaced by the address, and %s will be replaced by the subject
1267 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1268 :group 'org-link-follow
1269 :type '(choice
1270 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1271 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1272 (const :tag "message-mail" (message-mail "%a" "%s"))
1273 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1275 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1276 "Non-nil means, ask for confirmation before executing shell links.
1277 Shell links can be dangerous: just think about a link
1279 [[shell:rm -rf ~/*][Google Search]]
1281 This link would show up in your Org-mode document as \"Google Search\",
1282 but really it would remove your entire home directory.
1283 Therefore we advise against setting this variable to nil.
1284 Just change it to `y-or-n-p' if you want to confirm with a
1285 single keystroke rather than having to type \"yes\"."
1286 :group 'org-link-follow
1287 :type '(choice
1288 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1289 (const :tag "with y-or-n (faster)" y-or-n-p)
1290 (const :tag "no confirmation (dangerous)" nil)))
1292 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1293 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1294 Elisp links can be dangerous: just think about a link
1296 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1298 This link would show up in your Org-mode document as \"Google Search\",
1299 but really it would remove your entire home directory.
1300 Therefore we advise against setting this variable to nil.
1301 Just change it to `y-or-n-p' if you want to confirm with a
1302 single keystroke rather than having to type \"yes\"."
1303 :group 'org-link-follow
1304 :type '(choice
1305 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1306 (const :tag "with y-or-n (faster)" y-or-n-p)
1307 (const :tag "no confirmation (dangerous)" nil)))
1309 (defconst org-file-apps-defaults-gnu
1310 '((remote . emacs)
1311 (system . mailcap)
1312 (t . mailcap))
1313 "Default file applications on a UNIX or GNU/Linux system.
1314 See `org-file-apps'.")
1316 (defconst org-file-apps-defaults-macosx
1317 '((remote . emacs)
1318 (t . "open %s")
1319 (system . "open %s")
1320 ("ps.gz" . "gv %s")
1321 ("eps.gz" . "gv %s")
1322 ("dvi" . "xdvi %s")
1323 ("fig" . "xfig %s"))
1324 "Default file applications on a MacOS X system.
1325 The system \"open\" is known as a default, but we use X11 applications
1326 for some files for which the OS does not have a good default.
1327 See `org-file-apps'.")
1329 (defconst org-file-apps-defaults-windowsnt
1330 (list
1331 '(remote . emacs)
1332 (cons t
1333 (list (if (featurep 'xemacs)
1334 'mswindows-shell-execute
1335 'w32-shell-execute)
1336 "open" 'file))
1337 (cons 'system
1338 (list (if (featurep 'xemacs)
1339 'mswindows-shell-execute
1340 'w32-shell-execute)
1341 "open" 'file)))
1342 "Default file applications on a Windows NT system.
1343 The system \"open\" is used for most files.
1344 See `org-file-apps'.")
1346 (defcustom org-file-apps
1348 (auto-mode . emacs)
1349 ("\\.x?html?\\'" . default)
1350 ("\\.pdf\\'" . default)
1352 "External applications for opening `file:path' items in a document.
1353 Org-mode uses system defaults for different file types, but
1354 you can use this variable to set the application for a given file
1355 extension. The entries in this list are cons cells where the car identifies
1356 files and the cdr the corresponding command. Possible values for the
1357 file identifier are
1358 \"regex\" Regular expression matched against the file name. For backward
1359 compatibility, this can also be a string with only alphanumeric
1360 characters, which is then interpreted as an extension.
1361 `directory' Matches a directory
1362 `remote' Matches a remote file, accessible through tramp or efs.
1363 Remote files most likely should be visited through Emacs
1364 because external applications cannot handle such paths.
1365 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1366 so all files Emacs knows how to handle. Using this with
1367 command `emacs' will open most files in Emacs. Beware that this
1368 will also open html files inside Emacs, unless you add
1369 (\"html\" . default) to the list as well.
1370 t Default for files not matched by any of the other options.
1371 `system' The system command to open files, like `open' on Windows
1372 and Mac OS X, and mailcap under GNU/Linux. This is the command
1373 that will be selected if you call `C-c C-o' with a double
1374 `C-u C-u' prefix.
1376 Possible values for the command are:
1377 `emacs' The file will be visited by the current Emacs process.
1378 `default' Use the default application for this file type, which is the
1379 association for t in the list, most likely in the system-specific
1380 part.
1381 This can be used to overrule an unwanted setting in the
1382 system-specific variable.
1383 `system' Use the system command for opening files, like \"open\".
1384 This command is specified by the entry whose car is `system'.
1385 Most likely, the system-specific version of this variable
1386 does define this command, but you can overrule/replace it
1387 here.
1388 string A command to be executed by a shell; %s will be replaced
1389 by the path to the file.
1390 sexp A Lisp form which will be evaluated. The file path will
1391 be available in the Lisp variable `file'.
1392 For more examples, see the system specific constants
1393 `org-file-apps-defaults-macosx'
1394 `org-file-apps-defaults-windowsnt'
1395 `org-file-apps-defaults-gnu'."
1396 :group 'org-link-follow
1397 :type '(repeat
1398 (cons (choice :value ""
1399 (string :tag "Extension")
1400 (const :tag "System command to open files" system)
1401 (const :tag "Default for unrecognized files" t)
1402 (const :tag "Remote file" remote)
1403 (const :tag "Links to a directory" directory)
1404 (const :tag "Any files that have Emacs modes"
1405 auto-mode))
1406 (choice :value ""
1407 (const :tag "Visit with Emacs" emacs)
1408 (const :tag "Use default" default)
1409 (const :tag "Use the system command" system)
1410 (string :tag "Command")
1411 (sexp :tag "Lisp form")))))
1413 (defgroup org-refile nil
1414 "Options concerning refiling entries in Org-mode."
1415 :tag "Org Refile"
1416 :group 'org)
1418 (defcustom org-directory "~/org"
1419 "Directory with org files.
1420 This is just a default location to look for Org files. There is no need
1421 at all to put your files into this directory. It is only used in the
1422 following situations:
1424 1. When a remember template specifies a target file that is not an
1425 absolute path. The path will then be interpreted relative to
1426 `org-directory'
1427 2. When a remember note is filed away in an interactive way (when exiting the
1428 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1429 with `org-directory' as the default path."
1430 :group 'org-refile
1431 :group 'org-remember
1432 :type 'directory)
1434 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1435 "Default target for storing notes.
1436 Used by the hooks for remember.el. This can be a string, or nil to mean
1437 the value of `remember-data-file'.
1438 You can set this on a per-template basis with the variable
1439 `org-remember-templates'."
1440 :group 'org-refile
1441 :group 'org-remember
1442 :type '(choice
1443 (const :tag "Default from remember-data-file" nil)
1444 file))
1446 (defcustom org-goto-interface 'outline
1447 "The default interface to be used for `org-goto'.
1448 Allowed values are:
1449 outline The interface shows an outline of the relevant file
1450 and the correct heading is found by moving through
1451 the outline or by searching with incremental search.
1452 outline-path-completion Headlines in the current buffer are offered via
1453 completion. This is the interface also used by
1454 the refile command."
1455 :group 'org-refile
1456 :type '(choice
1457 (const :tag "Outline" outline)
1458 (const :tag "Outline-path-completion" outline-path-completion)))
1460 (defcustom org-goto-max-level 5
1461 "Maximum level to be considered when running org-goto with refile interface."
1462 :group 'org-refile
1463 :type 'integer)
1465 (defcustom org-reverse-note-order nil
1466 "Non-nil means, store new notes at the beginning of a file or entry.
1467 When nil, new notes will be filed to the end of a file or entry.
1468 This can also be a list with cons cells of regular expressions that
1469 are matched against file names, and values."
1470 :group 'org-remember
1471 :group 'org-refile
1472 :type '(choice
1473 (const :tag "Reverse always" t)
1474 (const :tag "Reverse never" nil)
1475 (repeat :tag "By file name regexp"
1476 (cons regexp boolean))))
1478 (defcustom org-refile-targets nil
1479 "Targets for refiling entries with \\[org-refile].
1480 This is list of cons cells. Each cell contains:
1481 - a specification of the files to be considered, either a list of files,
1482 or a symbol whose function or variable value will be used to retrieve
1483 a file name or a list of file names. If you use `org-agenda-files' for
1484 that, all agenda files will be scanned for targets. Nil means, consider
1485 headings in the current buffer.
1486 - A specification of how to find candidate refile targets. This may be
1487 any of:
1488 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1489 This tag has to be present in all target headlines, inheritance will
1490 not be considered.
1491 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1492 todo keyword.
1493 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1494 headlines that are refiling targets.
1495 - a cons cell (:level . N). Any headline of level N is considered a target.
1496 Note that, when `org-odd-levels-only' is set, level corresponds to
1497 order in hierarchy, not to the number of stars.
1498 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1499 Note that, when `org-odd-levels-only' is set, level corresponds to
1500 order in hierarchy, not to the number of stars.
1502 When this variable is nil, all top-level headlines in the current buffer
1503 are used, equivalent to the value `((nil . (:level . 1))'."
1504 :group 'org-refile
1505 :type '(repeat
1506 (cons
1507 (choice :value org-agenda-files
1508 (const :tag "All agenda files" org-agenda-files)
1509 (const :tag "Current buffer" nil)
1510 (function) (variable) (file))
1511 (choice :tag "Identify target headline by"
1512 (cons :tag "Specific tag" (const :value :tag) (string))
1513 (cons :tag "TODO keyword" (const :value :todo) (string))
1514 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1515 (cons :tag "Level number" (const :value :level) (integer))
1516 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1518 (defcustom org-refile-use-outline-path nil
1519 "Non-nil means, provide refile targets as paths.
1520 So a level 3 headline will be available as level1/level2/level3.
1522 When the value is `file', also include the file name (without directory)
1523 into the path. In this case, you can also stop the completion after
1524 the file name, to get entries inserted as top level in the file.
1526 When `full-file-path', include the full file path."
1527 :group 'org-refile
1528 :type '(choice
1529 (const :tag "Not" nil)
1530 (const :tag "Yes" t)
1531 (const :tag "Start with file name" file)
1532 (const :tag "Start with full file path" full-file-path)))
1534 (defcustom org-outline-path-complete-in-steps t
1535 "Non-nil means, complete the outline path in hierarchical steps.
1536 When Org-mode uses the refile interface to select an outline path
1537 \(see variable `org-refile-use-outline-path'), the completion of
1538 the path can be done is a single go, or if can be done in steps down
1539 the headline hierarchy. Going in steps is probably the best if you
1540 do not use a special completion package like `ido' or `icicles'.
1541 However, when using these packages, going in one step can be very
1542 fast, while still showing the whole path to the entry."
1543 :group 'org-refile
1544 :type 'boolean)
1546 (defgroup org-todo nil
1547 "Options concerning TODO items in Org-mode."
1548 :tag "Org TODO"
1549 :group 'org)
1551 (defgroup org-progress nil
1552 "Options concerning Progress logging in Org-mode."
1553 :tag "Org Progress"
1554 :group 'org-time)
1556 (defvar org-todo-interpretation-widgets
1558 (:tag "Sequence (cycling hits every state)" sequence)
1559 (:tag "Type (cycling directly to DONE)" type))
1560 "The available interpretation symbols for customizing
1561 `org-todo-keywords'.
1562 Interested libraries should add to this list.")
1564 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1565 "List of TODO entry keyword sequences and their interpretation.
1566 \\<org-mode-map>This is a list of sequences.
1568 Each sequence starts with a symbol, either `sequence' or `type',
1569 indicating if the keywords should be interpreted as a sequence of
1570 action steps, or as different types of TODO items. The first
1571 keywords are states requiring action - these states will select a headline
1572 for inclusion into the global TODO list Org-mode produces. If one of
1573 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1574 signify that no further action is necessary. If \"|\" is not found,
1575 the last keyword is treated as the only DONE state of the sequence.
1577 The command \\[org-todo] cycles an entry through these states, and one
1578 additional state where no keyword is present. For details about this
1579 cycling, see the manual.
1581 TODO keywords and interpretation can also be set on a per-file basis with
1582 the special #+SEQ_TODO and #+TYP_TODO lines.
1584 Each keyword can optionally specify a character for fast state selection
1585 \(in combination with the variable `org-use-fast-todo-selection')
1586 and specifiers for state change logging, using the same syntax
1587 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1588 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1589 indicates to record a time stamp each time this state is selected.
1591 Each keyword may also specify if a timestamp or a note should be
1592 recorded when entering or leaving the state, by adding additional
1593 characters in the parenthesis after the keyword. This looks like this:
1594 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1595 record only the time of the state change. With X and Y being either
1596 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1597 Y when leaving the state if and only if the *target* state does not
1598 define X. You may omit any of the fast-selection key or X or /Y,
1599 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1601 For backward compatibility, this variable may also be just a list
1602 of keywords - in this case the interpretation (sequence or type) will be
1603 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1604 :group 'org-todo
1605 :group 'org-keywords
1606 :type '(choice
1607 (repeat :tag "Old syntax, just keywords"
1608 (string :tag "Keyword"))
1609 (repeat :tag "New syntax"
1610 (cons
1611 (choice
1612 :tag "Interpretation"
1613 ;;Quick and dirty way to see
1614 ;;`org-todo-interpretations'. This takes the
1615 ;;place of item arguments
1616 :convert-widget
1617 (lambda (widget)
1618 (widget-put widget
1619 :args (mapcar
1620 #'(lambda (x)
1621 (widget-convert
1622 (cons 'const x)))
1623 org-todo-interpretation-widgets))
1624 widget))
1625 (repeat
1626 (string :tag "Keyword"))))))
1628 (defvar org-todo-keywords-1 nil
1629 "All TODO and DONE keywords active in a buffer.")
1630 (make-variable-buffer-local 'org-todo-keywords-1)
1631 (defvar org-todo-keywords-for-agenda nil)
1632 (defvar org-done-keywords-for-agenda nil)
1633 (defvar org-todo-keyword-alist-for-agenda nil)
1634 (defvar org-tag-alist-for-agenda nil)
1635 (defvar org-agenda-contributing-files nil)
1636 (defvar org-not-done-keywords nil)
1637 (make-variable-buffer-local 'org-not-done-keywords)
1638 (defvar org-done-keywords nil)
1639 (make-variable-buffer-local 'org-done-keywords)
1640 (defvar org-todo-heads nil)
1641 (make-variable-buffer-local 'org-todo-heads)
1642 (defvar org-todo-sets nil)
1643 (make-variable-buffer-local 'org-todo-sets)
1644 (defvar org-todo-log-states nil)
1645 (make-variable-buffer-local 'org-todo-log-states)
1646 (defvar org-todo-kwd-alist nil)
1647 (make-variable-buffer-local 'org-todo-kwd-alist)
1648 (defvar org-todo-key-alist nil)
1649 (make-variable-buffer-local 'org-todo-key-alist)
1650 (defvar org-todo-key-trigger nil)
1651 (make-variable-buffer-local 'org-todo-key-trigger)
1653 (defcustom org-todo-interpretation 'sequence
1654 "Controls how TODO keywords are interpreted.
1655 This variable is in principle obsolete and is only used for
1656 backward compatibility, if the interpretation of todo keywords is
1657 not given already in `org-todo-keywords'. See that variable for
1658 more information."
1659 :group 'org-todo
1660 :group 'org-keywords
1661 :type '(choice (const sequence)
1662 (const type)))
1664 (defcustom org-use-fast-todo-selection t
1665 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1666 This variable describes if and under what circumstances the cycling
1667 mechanism for TODO keywords will be replaced by a single-key, direct
1668 selection scheme.
1670 When nil, fast selection is never used.
1672 When the symbol `prefix', it will be used when `org-todo' is called with
1673 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1674 in an agenda buffer.
1676 When t, fast selection is used by default. In this case, the prefix
1677 argument forces cycling instead.
1679 In all cases, the special interface is only used if access keys have actually
1680 been assigned by the user, i.e. if keywords in the configuration are followed
1681 by a letter in parenthesis, like TODO(t)."
1682 :group 'org-todo
1683 :type '(choice
1684 (const :tag "Never" nil)
1685 (const :tag "By default" t)
1686 (const :tag "Only with C-u C-c C-t" prefix)))
1688 (defcustom org-provide-todo-statistics t
1689 "Non-nil means, update todo statistics after insert and toggle.
1690 When this is set, todo statistics is updated in the parent of the current
1691 entry each time a todo state is changed."
1692 :group 'org-todo
1693 :type 'boolean)
1695 (defcustom org-after-todo-state-change-hook nil
1696 "Hook which is run after the state of a TODO item was changed.
1697 The new state (a string with a TODO keyword, or nil) is available in the
1698 Lisp variable `state'."
1699 :group 'org-todo
1700 :type 'hook)
1702 (defvar org-blocker-hook nil
1703 "Hook for functions that are allowed to block a state change.
1705 Each function gets as its single argument a property list, see
1706 `org-trigger-hook' for more information about this list.
1708 If any of the functions in this hook returns nil, the state change
1709 is blocked.")
1711 (defvar org-trigger-hook nil
1712 "Hook for functions that are triggered by a state change.
1714 Each function gets as its single argument a property list with at least
1715 the following elements:
1717 (:type type-of-change :position pos-at-entry-start
1718 :from old-state :to new-state)
1720 Depending on the type, more properties may be present.
1722 This mechanism is currently implemented for:
1724 TODO state changes
1725 ------------------
1726 :type todo-state-change
1727 :from previous state (keyword as a string), or nil, or a symbol
1728 'todo' or 'done', to indicate the general type of state.
1729 :to new state, like in :from")
1731 (defcustom org-enforce-todo-dependencies nil
1732 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1733 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1734 be blocked if any prior sibling is not yet done.
1735 Finally, if the parent is blocked because of ordered siblings of its own,
1736 the child will also be blocked.
1737 This variable needs to be set before org.el is loaded, and you need to
1738 restart Emacs after a change to make the change effective. The only way
1739 to change is while Emacs is running is through the customize interface."
1740 :set (lambda (var val)
1741 (set var val)
1742 (if val
1743 (add-hook 'org-blocker-hook
1744 'org-block-todo-from-children-or-siblings-or-parent)
1745 (remove-hook 'org-blocker-hook
1746 'org-block-todo-from-children-or-siblings-or-parent)))
1747 :group 'org-todo
1748 :type 'boolean)
1750 (defcustom org-enforce-todo-checkbox-dependencies nil
1751 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1752 When this is nil, checkboxes have no influence on switching TODO states.
1753 When non-nil, you first need to check off all check boxes before the TODO
1754 entry can be switched to DONE.
1755 This variable needs to be set before org.el is loaded, and you need to
1756 restart Emacs after a change to make the change effective. The only way
1757 to change is while Emacs is running is through the customize interface."
1758 :set (lambda (var val)
1759 (set var val)
1760 (if val
1761 (add-hook 'org-blocker-hook
1762 'org-block-todo-from-checkboxes)
1763 (remove-hook 'org-blocker-hook
1764 'org-block-todo-from-checkboxes)))
1765 :group 'org-todo
1766 :type 'boolean)
1768 (defcustom org-todo-state-tags-triggers nil
1769 "Tag changes that should be triggered by TODO state changes.
1770 This is a list. Each entry is
1772 (state-change (tag . flag) .......)
1774 State-change can be a string with a state, and empty string to indicate the
1775 state that has no TODO keyword, or it can be one of the symbols `todo'
1776 or `done', meaning any not-done or done state, respectively."
1777 :group 'org-todo
1778 :group 'org-tags
1779 :type '(repeat
1780 (cons (choice :tag "When changing to"
1781 (const :tag "Not-done state" todo)
1782 (const :tag "Done state" done)
1783 (string :tag "State"))
1784 (repeat
1785 (cons :tag "Tag action"
1786 (string :tag "Tag")
1787 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1789 (defcustom org-log-done nil
1790 "Information to record when a task moves to the DONE state.
1792 Possible values are:
1794 nil Don't add anything, just change the keyword
1795 time Add a time stamp to the task
1796 note Prompt a closing note and add it with template `org-log-note-headings'
1798 This option can also be set with on a per-file-basis with
1800 #+STARTUP: nologdone
1801 #+STARTUP: logdone
1802 #+STARTUP: lognotedone
1804 You can have local logging settings for a subtree by setting the LOGGING
1805 property to one or more of these keywords."
1806 :group 'org-todo
1807 :group 'org-progress
1808 :type '(choice
1809 (const :tag "No logging" nil)
1810 (const :tag "Record CLOSED timestamp" time)
1811 (const :tag "Record CLOSED timestamp with closing note." note)))
1813 ;; Normalize old uses of org-log-done.
1814 (cond
1815 ((eq org-log-done t) (setq org-log-done 'time))
1816 ((and (listp org-log-done) (memq 'done org-log-done))
1817 (setq org-log-done 'note)))
1819 (defcustom org-log-note-clock-out nil
1820 "Non-nil means, record a note when clocking out of an item.
1821 This can also be configured on a per-file basis by adding one of
1822 the following lines anywhere in the buffer:
1824 #+STARTUP: lognoteclock-out
1825 #+STARTUP: nolognoteclock-out"
1826 :group 'org-todo
1827 :group 'org-progress
1828 :type 'boolean)
1830 (defcustom org-log-done-with-time t
1831 "Non-nil means, the CLOSED time stamp will contain date and time.
1832 When nil, only the date will be recorded."
1833 :group 'org-progress
1834 :type 'boolean)
1836 (defcustom org-log-note-headings
1837 '((done . "CLOSING NOTE %t")
1838 (state . "State %-12s from %-12S %t")
1839 (note . "Note taken on %t")
1840 (clock-out . ""))
1841 "Headings for notes added to entries.
1842 The value is an alist, with the car being a symbol indicating the note
1843 context, and the cdr is the heading to be used. The heading may also be the
1844 empty string.
1845 %t in the heading will be replaced by a time stamp.
1846 %s will be replaced by the new TODO state, in double quotes.
1847 %S will be replaced by the old TODO state, in double quotes.
1848 %u will be replaced by the user name.
1849 %U will be replaced by the full user name."
1850 :group 'org-todo
1851 :group 'org-progress
1852 :type '(list :greedy t
1853 (cons (const :tag "Heading when closing an item" done) string)
1854 (cons (const :tag
1855 "Heading when changing todo state (todo sequence only)"
1856 state) string)
1857 (cons (const :tag "Heading when just taking a note" note) string)
1858 (cons (const :tag "Heading when clocking out" clock-out) string)))
1860 (unless (assq 'note org-log-note-headings)
1861 (push '(note . "%t") org-log-note-headings))
1863 (defcustom org-log-into-drawer nil
1864 "Non-nil means, insert state change notes and time stamps into a drawer.
1865 When nil, state changes notes will be inserted after the headline and
1866 any scheduling and clock lines, but not inside a drawer.
1868 The value of this variable should be the name of the drawer to use.
1869 LOGBOOK is proposed at the default drawer for this purpose, you can
1870 also set this to a string to define the drawer of your choice.
1872 A value of t is also allowed, representing \"LOGBOOK\".
1874 If this variable is set, `org-log-state-notes-insert-after-drawers'
1875 will be ignored."
1876 :group 'org-todo
1877 :group 'org-progress
1878 :type '(choice
1879 (const :tag "Not into a drawer" nil)
1880 (const :tag "LOGBOOK" t)
1881 (string :tag "Other")))
1883 (if (fboundp 'defvaralias)
1884 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1886 (defcustom org-log-state-notes-insert-after-drawers nil
1887 "Non-nil means, insert state change notes after any drawers in entry.
1888 Only the drawers that *immediately* follow the headline and the
1889 deadline/scheduled line are skipped.
1890 When nil, insert notes right after the heading and perhaps the line
1891 with deadline/scheduling if present.
1893 This variable will have no effect if `org-log-into-drawer' is
1894 set."
1895 :group 'org-todo
1896 :group 'org-progress
1897 :type 'boolean)
1899 (defcustom org-log-states-order-reversed t
1900 "Non-nil means, the latest state change note will be directly after heading.
1901 When nil, the notes will be orderer according to time."
1902 :group 'org-todo
1903 :group 'org-progress
1904 :type 'boolean)
1906 (defcustom org-log-repeat 'time
1907 "Non-nil means, record moving through the DONE state when triggering repeat.
1908 An auto-repeating tasks is immediately switched back to TODO when marked
1909 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1910 the TODO keyword definition, or recording a closing note by setting
1911 `org-log-done', there will be no record of the task moving through DONE.
1912 This variable forces taking a note anyway. Possible values are:
1914 nil Don't force a record
1915 time Record a time stamp
1916 note Record a note
1918 This option can also be set with on a per-file-basis with
1920 #+STARTUP: logrepeat
1921 #+STARTUP: lognoterepeat
1922 #+STARTUP: nologrepeat
1924 You can have local logging settings for a subtree by setting the LOGGING
1925 property to one or more of these keywords."
1926 :group 'org-todo
1927 :group 'org-progress
1928 :type '(choice
1929 (const :tag "Don't force a record" nil)
1930 (const :tag "Force recording the DONE state" time)
1931 (const :tag "Force recording a note with the DONE state" note)))
1934 (defgroup org-priorities nil
1935 "Priorities in Org-mode."
1936 :tag "Org Priorities"
1937 :group 'org-todo)
1939 (defcustom org-highest-priority ?A
1940 "The highest priority of TODO items. A character like ?A, ?B etc.
1941 Must have a smaller ASCII number than `org-lowest-priority'."
1942 :group 'org-priorities
1943 :type 'character)
1945 (defcustom org-lowest-priority ?C
1946 "The lowest priority of TODO items. A character like ?A, ?B etc.
1947 Must have a larger ASCII number than `org-highest-priority'."
1948 :group 'org-priorities
1949 :type 'character)
1951 (defcustom org-default-priority ?B
1952 "The default priority of TODO items.
1953 This is the priority an item get if no explicit priority is given."
1954 :group 'org-priorities
1955 :type 'character)
1957 (defcustom org-priority-start-cycle-with-default t
1958 "Non-nil means, start with default priority when starting to cycle.
1959 When this is nil, the first step in the cycle will be (depending on the
1960 command used) one higher or lower that the default priority."
1961 :group 'org-priorities
1962 :type 'boolean)
1964 (defgroup org-time nil
1965 "Options concerning time stamps and deadlines in Org-mode."
1966 :tag "Org Time"
1967 :group 'org)
1969 (defcustom org-insert-labeled-timestamps-at-point nil
1970 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1971 When nil, these labeled time stamps are forces into the second line of an
1972 entry, just after the headline. When scheduling from the global TODO list,
1973 the time stamp will always be forced into the second line."
1974 :group 'org-time
1975 :type 'boolean)
1977 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1978 "Formats for `format-time-string' which are used for time stamps.
1979 It is not recommended to change this constant.")
1981 (defcustom org-time-stamp-rounding-minutes '(0 5)
1982 "Number of minutes to round time stamps to.
1983 These are two values, the first applies when first creating a time stamp.
1984 The second applies when changing it with the commands `S-up' and `S-down'.
1985 When changing the time stamp, this means that it will change in steps
1986 of N minutes, as given by the second value.
1988 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1989 numbers should be factors of 60, so for example 5, 10, 15.
1991 When this is larger than 1, you can still force an exact time-stamp by using
1992 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1993 and by using a prefix arg to `S-up/down' to specify the exact number
1994 of minutes to shift."
1995 :group 'org-time
1996 :get '(lambda (var) ; Make sure all entries have 5 elements
1997 (if (integerp (default-value var))
1998 (list (default-value var) 5)
1999 (default-value var)))
2000 :type '(list
2001 (integer :tag "when inserting times")
2002 (integer :tag "when modifying times")))
2004 ;; Normalize old customizations of this variable.
2005 (when (integerp org-time-stamp-rounding-minutes)
2006 (setq org-time-stamp-rounding-minutes
2007 (list org-time-stamp-rounding-minutes
2008 org-time-stamp-rounding-minutes)))
2010 (defcustom org-display-custom-times nil
2011 "Non-nil means, overlay custom formats over all time stamps.
2012 The formats are defined through the variable `org-time-stamp-custom-formats'.
2013 To turn this on on a per-file basis, insert anywhere in the file:
2014 #+STARTUP: customtime"
2015 :group 'org-time
2016 :set 'set-default
2017 :type 'sexp)
2018 (make-variable-buffer-local 'org-display-custom-times)
2020 (defcustom org-time-stamp-custom-formats
2021 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2022 "Custom formats for time stamps. See `format-time-string' for the syntax.
2023 These are overlayed over the default ISO format if the variable
2024 `org-display-custom-times' is set. Time like %H:%M should be at the
2025 end of the second format."
2026 :group 'org-time
2027 :type 'sexp)
2029 (defun org-time-stamp-format (&optional long inactive)
2030 "Get the right format for a time string."
2031 (let ((f (if long (cdr org-time-stamp-formats)
2032 (car org-time-stamp-formats))))
2033 (if inactive
2034 (concat "[" (substring f 1 -1) "]")
2035 f)))
2037 (defcustom org-time-clocksum-format "%d:%02d"
2038 "The format string used when creating CLOCKSUM lines, or when
2039 org-mode generates a time duration."
2040 :group 'org-time
2041 :type 'string)
2043 (defcustom org-deadline-warning-days 14
2044 "No. of days before expiration during which a deadline becomes active.
2045 This variable governs the display in sparse trees and in the agenda.
2046 When 0 or negative, it means use this number (the absolute value of it)
2047 even if a deadline has a different individual lead time specified.
2049 Custom commands can set this variable in the options section."
2050 :group 'org-time
2051 :group 'org-agenda-daily/weekly
2052 :type 'integer)
2054 (defcustom org-read-date-prefer-future t
2055 "Non-nil means, assume future for incomplete date input from user.
2056 This affects the following situations:
2057 1. The user gives a day, but no month.
2058 For example, if today is the 15th, and you enter \"3\", Org-mode will
2059 read this as the third of *next* month. However, if you enter \"17\",
2060 it will be considered as *this* month.
2061 2. The user gives a month but not a year.
2062 For example, if it is april and you enter \"feb 2\", this will be read
2063 as feb 2, *next* year. \"May 5\", however, will be this year.
2065 Currently this does not work for ISO week specifications.
2067 When this option is nil, the current month and year will always be used
2068 as defaults."
2069 :group 'org-time
2070 :type 'boolean)
2072 (defcustom org-read-date-display-live t
2073 "Non-nil means, display current interpretation of date prompt live.
2074 This display will be in an overlay, in the minibuffer."
2075 :group 'org-time
2076 :type 'boolean)
2078 (defcustom org-read-date-popup-calendar t
2079 "Non-nil means, pop up a calendar when prompting for a date.
2080 In the calendar, the date can be selected with mouse-1. However, the
2081 minibuffer will also be active, and you can simply enter the date as well.
2082 When nil, only the minibuffer will be available."
2083 :group 'org-time
2084 :type 'boolean)
2085 (if (fboundp 'defvaralias)
2086 (defvaralias 'org-popup-calendar-for-date-prompt
2087 'org-read-date-popup-calendar))
2089 (defcustom org-read-date-minibuffer-setup-hook nil
2090 "Hook to be used to set up keys for the date/time interface.
2091 Add key definitions to `minibuffer-local-map', which will be a temporary
2092 copy."
2093 :group 'org-time
2094 :type 'hook)
2096 (defcustom org-extend-today-until 0
2097 "The hour when your day really ends. Must be an integer.
2098 This has influence for the following applications:
2099 - When switching the agenda to \"today\". It it is still earlier than
2100 the time given here, the day recognized as TODAY is actually yesterday.
2101 - When a date is read from the user and it is still before the time given
2102 here, the current date and time will be assumed to be yesterday, 23:59.
2103 Also, timestamps inserted in remember templates follow this rule.
2105 IMPORTANT: This is a feature whose implementation is and likely will
2106 remain incomplete. Really, it is only here because past midnight seems to
2107 be the favorite working time of John Wiegley :-)"
2108 :group 'org-time
2109 :type 'integer)
2111 (defcustom org-edit-timestamp-down-means-later nil
2112 "Non-nil means, S-down will increase the time in a time stamp.
2113 When nil, S-up will increase."
2114 :group 'org-time
2115 :type 'boolean)
2117 (defcustom org-calendar-follow-timestamp-change t
2118 "Non-nil means, make the calendar window follow timestamp changes.
2119 When a timestamp is modified and the calendar window is visible, it will be
2120 moved to the new date."
2121 :group 'org-time
2122 :type 'boolean)
2124 (defgroup org-tags nil
2125 "Options concerning tags in Org-mode."
2126 :tag "Org Tags"
2127 :group 'org)
2129 (defcustom org-tag-alist nil
2130 "List of tags allowed in Org-mode files.
2131 When this list is nil, Org-mode will base TAG input on what is already in the
2132 buffer.
2133 The value of this variable is an alist, the car of each entry must be a
2134 keyword as a string, the cdr may be a character that is used to select
2135 that tag through the fast-tag-selection interface.
2136 See the manual for details."
2137 :group 'org-tags
2138 :type '(repeat
2139 (choice
2140 (cons (string :tag "Tag name")
2141 (character :tag "Access char"))
2142 (const :tag "Start radio group" (:startgroup))
2143 (const :tag "End radio group" (:endgroup))
2144 (const :tag "New line" (:newline)))))
2146 (defcustom org-tag-persistent-alist nil
2147 "List of tags that will always appear in all Org-mode files.
2148 This is in addition to any in buffer settings or customizations
2149 of `org-tag-alist'.
2150 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2151 The value of this variable is an alist, the car of each entry must be a
2152 keyword as a string, the cdr may be a character that is used to select
2153 that tag through the fast-tag-selection interface.
2154 See the manual for details.
2155 To disable these tags on a per-file basis, insert anywhere in the file:
2156 #+STARTUP: noptag"
2157 :group 'org-tags
2158 :type '(repeat
2159 (choice
2160 (cons (string :tag "Tag name")
2161 (character :tag "Access char"))
2162 (const :tag "Start radio group" (:startgroup))
2163 (const :tag "End radio group" (:endgroup))
2164 (const :tag "New line" (:newline)))))
2166 (defvar org-file-tags nil
2167 "List of tags that can be inherited by all entries in the file.
2168 The tags will be inherited if the variable `org-use-tag-inheritance'
2169 says they should be.
2170 This variable is populated from #+TAG lines.")
2172 (defcustom org-use-fast-tag-selection 'auto
2173 "Non-nil means, use fast tag selection scheme.
2174 This is a special interface to select and deselect tags with single keys.
2175 When nil, fast selection is never used.
2176 When the symbol `auto', fast selection is used if and only if selection
2177 characters for tags have been configured, either through the variable
2178 `org-tag-alist' or through a #+TAGS line in the buffer.
2179 When t, fast selection is always used and selection keys are assigned
2180 automatically if necessary."
2181 :group 'org-tags
2182 :type '(choice
2183 (const :tag "Always" t)
2184 (const :tag "Never" nil)
2185 (const :tag "When selection characters are configured" 'auto)))
2187 (defcustom org-fast-tag-selection-single-key nil
2188 "Non-nil means, fast tag selection exits after first change.
2189 When nil, you have to press RET to exit it.
2190 During fast tag selection, you can toggle this flag with `C-c'.
2191 This variable can also have the value `expert'. In this case, the window
2192 displaying the tags menu is not even shown, until you press C-c again."
2193 :group 'org-tags
2194 :type '(choice
2195 (const :tag "No" nil)
2196 (const :tag "Yes" t)
2197 (const :tag "Expert" expert)))
2199 (defvar org-fast-tag-selection-include-todo nil
2200 "Non-nil means, fast tags selection interface will also offer TODO states.
2201 This is an undocumented feature, you should not rely on it.")
2203 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2204 "The column to which tags should be indented in a headline.
2205 If this number is positive, it specifies the column. If it is negative,
2206 it means that the tags should be flushright to that column. For example,
2207 -80 works well for a normal 80 character screen."
2208 :group 'org-tags
2209 :type 'integer)
2211 (defcustom org-auto-align-tags t
2212 "Non-nil means, realign tags after pro/demotion of TODO state change.
2213 These operations change the length of a headline and therefore shift
2214 the tags around. With this options turned on, after each such operation
2215 the tags are again aligned to `org-tags-column'."
2216 :group 'org-tags
2217 :type 'boolean)
2219 (defcustom org-use-tag-inheritance t
2220 "Non-nil means, tags in levels apply also for sublevels.
2221 When nil, only the tags directly given in a specific line apply there.
2222 This may also be a list of tags that should be inherited, or a regexp that
2223 matches tags that should be inherited. Additional control is possible
2224 with the variable `org-tags-exclude-from-inheritance' which gives an
2225 explicit list of tags to be excluded from inheritance., even if the value of
2226 `org-use-tag-inheritance' would select it for inheritance.
2228 If this option is t, a match early-on in a tree can lead to a large
2229 number of matches in the subtree when constructing the agenda or creating
2230 a sparse tree. If you only want to see the first match in a tree during
2231 a search, check out the variable `org-tags-match-list-sublevels'."
2232 :group 'org-tags
2233 :type '(choice
2234 (const :tag "Not" nil)
2235 (const :tag "Always" t)
2236 (repeat :tag "Specific tags" (string :tag "Tag"))
2237 (regexp :tag "Tags matched by regexp")))
2239 (defcustom org-tags-exclude-from-inheritance nil
2240 "List of tags that should never be inherited.
2241 This is a way to exclude a few tags from inheritance. For way to do
2242 the opposite, to actively allow inheritance for selected tags,
2243 see the variable `org-use-tag-inheritance'."
2244 :group 'org-tags
2245 :type '(repeat (string :tag "Tag")))
2247 (defun org-tag-inherit-p (tag)
2248 "Check if TAG is one that should be inherited."
2249 (cond
2250 ((member tag org-tags-exclude-from-inheritance) nil)
2251 ((eq org-use-tag-inheritance t) t)
2252 ((not org-use-tag-inheritance) nil)
2253 ((stringp org-use-tag-inheritance)
2254 (string-match org-use-tag-inheritance tag))
2255 ((listp org-use-tag-inheritance)
2256 (member tag org-use-tag-inheritance))
2257 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2259 (defcustom org-tags-match-list-sublevels t
2260 "Non-nil means list also sublevels of headlines matching a search.
2261 This variable applies to tags/property searches, and also to stuck
2262 projects because this search is based on a tags match as well.
2264 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2265 the sublevels of a headline matching a tag search often also match
2266 the same search. Listing all of them can create very long lists.
2267 Setting this variable to nil causes subtrees of a match to be skipped.
2269 As a special case, if the tag search is restricted to TODO items, the
2270 value of this variable is ignored and sublevels are always checked, to
2271 make sure all corresponding TODO items find their way into the list.
2273 This variable is semi-obsolete and probably should always be true. It
2274 is better to limit inheritance to certain tags using the variables
2275 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2276 :group 'org-tags
2277 :type '(choice
2278 (const :tag "No, don't list them" nil)
2279 (const :tag "Yes, do list them" t)
2280 (const :tag "List them, indented with leading dots" indented)))
2282 (defvar org-tags-history nil
2283 "History of minibuffer reads for tags.")
2284 (defvar org-last-tags-completion-table nil
2285 "The last used completion table for tags.")
2286 (defvar org-after-tags-change-hook nil
2287 "Hook that is run after the tags in a line have changed.")
2289 (defgroup org-properties nil
2290 "Options concerning properties in Org-mode."
2291 :tag "Org Properties"
2292 :group 'org)
2294 (defcustom org-property-format "%-10s %s"
2295 "How property key/value pairs should be formatted by `indent-line'.
2296 When `indent-line' hits a property definition, it will format the line
2297 according to this format, mainly to make sure that the values are
2298 lined-up with respect to each other."
2299 :group 'org-properties
2300 :type 'string)
2302 (defcustom org-use-property-inheritance nil
2303 "Non-nil means, properties apply also for sublevels.
2305 This setting is chiefly used during property searches. Turning it on can
2306 cause significant overhead when doing a search, which is why it is not
2307 on by default.
2309 When nil, only the properties directly given in the current entry count.
2310 When t, every property is inherited. The value may also be a list of
2311 properties that should have inheritance, or a regular expression matching
2312 properties that should be inherited.
2314 However, note that some special properties use inheritance under special
2315 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2316 and the properties ending in \"_ALL\" when they are used as descriptor
2317 for valid values of a property.
2319 Note for programmers:
2320 When querying an entry with `org-entry-get', you can control if inheritance
2321 should be used. By default, `org-entry-get' looks only at the local
2322 properties. You can request inheritance by setting the inherit argument
2323 to t (to force inheritance) or to `selective' (to respect the setting
2324 in this variable)."
2325 :group 'org-properties
2326 :type '(choice
2327 (const :tag "Not" nil)
2328 (const :tag "Always" t)
2329 (repeat :tag "Specific properties" (string :tag "Property"))
2330 (regexp :tag "Properties matched by regexp")))
2332 (defun org-property-inherit-p (property)
2333 "Check if PROPERTY is one that should be inherited."
2334 (cond
2335 ((eq org-use-property-inheritance t) t)
2336 ((not org-use-property-inheritance) nil)
2337 ((stringp org-use-property-inheritance)
2338 (string-match org-use-property-inheritance property))
2339 ((listp org-use-property-inheritance)
2340 (member property org-use-property-inheritance))
2341 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2343 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2344 "The default column format, if no other format has been defined.
2345 This variable can be set on the per-file basis by inserting a line
2347 #+COLUMNS: %25ITEM ....."
2348 :group 'org-properties
2349 :type 'string)
2351 (defcustom org-columns-ellipses ".."
2352 "The ellipses to be used when a field in column view is truncated.
2353 When this is the empty string, as many characters as possible are shown,
2354 but then there will be no visual indication that the field has been truncated.
2355 When this is a string of length N, the last N characters of a truncated
2356 field are replaced by this string. If the column is narrower than the
2357 ellipses string, only part of the ellipses string will be shown."
2358 :group 'org-properties
2359 :type 'string)
2361 (defcustom org-columns-modify-value-for-display-function nil
2362 "Function that modifies values for display in column view.
2363 For example, it can be used to cut out a certain part from a time stamp.
2364 The function must take 2 arguments:
2366 column-title The title of the column (*not* the property name)
2367 value The value that should be modified.
2369 The function should return the value that should be displayed,
2370 or nil if the normal value should be used."
2371 :group 'org-properties
2372 :type 'function)
2374 (defcustom org-effort-property "Effort"
2375 "The property that is being used to keep track of effort estimates.
2376 Effort estimates given in this property need to have the format H:MM."
2377 :group 'org-properties
2378 :group 'org-progress
2379 :type '(string :tag "Property"))
2381 (defconst org-global-properties-fixed
2382 '(("VISIBILITY_ALL" . "folded children content all"))
2383 "List of property/value pairs that can be inherited by any entry.
2385 These are fixed values, for the preset properties. The user variable
2386 that can be used to add to this list is `org-global-properties'.
2388 The entries in this list are cons cells where the car is a property
2389 name and cdr is a string with the value. If the value represents
2390 multiple items like an \"_ALL\" property, separate the items by
2391 spaces.")
2393 (defcustom org-global-properties nil
2394 "List of property/value pairs that can be inherited by any entry.
2396 This list will be combined with the constant `org-global-properties-fixed'.
2398 The entries in this list are cons cells where the car is a property
2399 name and cdr is a string with the value.
2401 You can set buffer-local values for the same purpose in the variable
2402 `org-file-properties' this by adding lines like
2404 #+PROPERTY: NAME VALUE"
2405 :group 'org-properties
2406 :type '(repeat
2407 (cons (string :tag "Property")
2408 (string :tag "Value"))))
2410 (defvar org-file-properties nil
2411 "List of property/value pairs that can be inherited by any entry.
2412 Valid for the current buffer.
2413 This variable is populated from #+PROPERTY lines.")
2414 (make-variable-buffer-local 'org-file-properties)
2416 (defgroup org-agenda nil
2417 "Options concerning agenda views in Org-mode."
2418 :tag "Org Agenda"
2419 :group 'org)
2421 (defvar org-category nil
2422 "Variable used by org files to set a category for agenda display.
2423 Such files should use a file variable to set it, for example
2425 # -*- mode: org; org-category: \"ELisp\"
2427 or contain a special line
2429 #+CATEGORY: ELisp
2431 If the file does not specify a category, then file's base name
2432 is used instead.")
2433 (make-variable-buffer-local 'org-category)
2434 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2436 (defcustom org-agenda-files nil
2437 "The files to be used for agenda display.
2438 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2439 \\[org-remove-file]. You can also use customize to edit the list.
2441 If an entry is a directory, all files in that directory that are matched by
2442 `org-agenda-file-regexp' will be part of the file list.
2444 If the value of the variable is not a list but a single file name, then
2445 the list of agenda files is actually stored and maintained in that file, one
2446 agenda file per line."
2447 :group 'org-agenda
2448 :type '(choice
2449 (repeat :tag "List of files and directories" file)
2450 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2452 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2453 "Regular expression to match files for `org-agenda-files'.
2454 If any element in the list in that variable contains a directory instead
2455 of a normal file, all files in that directory that are matched by this
2456 regular expression will be included."
2457 :group 'org-agenda
2458 :type 'regexp)
2460 (defcustom org-agenda-text-search-extra-files nil
2461 "List of extra files to be searched by text search commands.
2462 These files will be search in addition to the agenda files by the
2463 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2464 Note that these files will only be searched for text search commands,
2465 not for the other agenda views like todo lists, tag searches or the weekly
2466 agenda. This variable is intended to list notes and possibly archive files
2467 that should also be searched by these two commands.
2468 In fact, if the first element in the list is the symbol `agenda-archives',
2469 than all archive files of all agenda files will be added to the search
2470 scope."
2471 :group 'org-agenda
2472 :type '(set :greedy t
2473 (const :tag "Agenda Archives" agenda-archives)
2474 (repeat :inline t (file))))
2476 (if (fboundp 'defvaralias)
2477 (defvaralias 'org-agenda-multi-occur-extra-files
2478 'org-agenda-text-search-extra-files))
2480 (defcustom org-agenda-skip-unavailable-files nil
2481 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2482 A nil value means to remove them, after a query, from the list."
2483 :group 'org-agenda
2484 :type 'boolean)
2486 (defcustom org-calendar-to-agenda-key [?c]
2487 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2488 The command `org-calendar-goto-agenda' will be bound to this key. The
2489 default is the character `c' because then `c' can be used to switch back and
2490 forth between agenda and calendar."
2491 :group 'org-agenda
2492 :type 'sexp)
2494 (defcustom org-calendar-agenda-action-key [?k]
2495 "The key to be installed in `calendar-mode-map' for agenda-action.
2496 The command `org-agenda-action' will be bound to this key. The
2497 default is the character `k' because we use the same key in the agenda."
2498 :group 'org-agenda
2499 :type 'sexp)
2501 (eval-after-load "calendar"
2502 '(progn
2503 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2504 'org-calendar-goto-agenda)
2505 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2506 'org-agenda-action)))
2508 (defgroup org-latex nil
2509 "Options for embedding LaTeX code into Org-mode."
2510 :tag "Org LaTeX"
2511 :group 'org)
2513 (defcustom org-format-latex-options
2514 '(:foreground default :background default :scale 1.0
2515 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2516 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2517 "Options for creating images from LaTeX fragments.
2518 This is a property list with the following properties:
2519 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2520 `default' means use the foreground of the default face.
2521 :background the background color, or \"Transparent\".
2522 `default' means use the background of the default face.
2523 :scale a scaling factor for the size of the images.
2524 :html-foreground, :html-background, :html-scale
2525 the same numbers for HTML export.
2526 :matchers a list indicating which matchers should be used to
2527 find LaTeX fragments. Valid members of this list are:
2528 \"begin\" find environments
2529 \"$1\" find single characters surrounded by $.$
2530 \"$\" find math expressions surrounded by $...$
2531 \"$$\" find math expressions surrounded by $$....$$
2532 \"\\(\" find math expressions surrounded by \\(...\\)
2533 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2534 :group 'org-latex
2535 :type 'plist)
2537 (defcustom org-format-latex-header "\\documentclass{article}
2538 \\usepackage{fullpage} % do not remove
2539 \\usepackage{amssymb}
2540 \\usepackage[usenames]{color}
2541 \\usepackage{amsmath}
2542 \\usepackage{latexsym}
2543 \\usepackage[mathscr]{eucal}
2544 \\pagestyle{empty} % do not remove"
2545 "The document header used for processing LaTeX fragments."
2546 :group 'org-latex
2547 :type 'string)
2550 (defgroup org-font-lock nil
2551 "Font-lock settings for highlighting in Org-mode."
2552 :tag "Org Font Lock"
2553 :group 'org)
2555 (defcustom org-level-color-stars-only nil
2556 "Non-nil means fontify only the stars in each headline.
2557 When nil, the entire headline is fontified.
2558 Changing it requires restart of `font-lock-mode' to become effective
2559 also in regions already fontified."
2560 :group 'org-font-lock
2561 :type 'boolean)
2563 (defcustom org-hide-leading-stars nil
2564 "Non-nil means, hide the first N-1 stars in a headline.
2565 This works by using the face `org-hide' for these stars. This
2566 face is white for a light background, and black for a dark
2567 background. You may have to customize the face `org-hide' to
2568 make this work.
2569 Changing it requires restart of `font-lock-mode' to become effective
2570 also in regions already fontified.
2571 You may also set this on a per-file basis by adding one of the following
2572 lines to the buffer:
2574 #+STARTUP: hidestars
2575 #+STARTUP: showstars"
2576 :group 'org-font-lock
2577 :type 'boolean)
2579 (defcustom org-fontify-done-headline nil
2580 "Non-nil means, change the face of a headline if it is marked DONE.
2581 Normally, only the TODO/DONE keyword indicates the state of a headline.
2582 When this is non-nil, the headline after the keyword is set to the
2583 `org-headline-done' as an additional indication."
2584 :group 'org-font-lock
2585 :type 'boolean)
2587 (defcustom org-fontify-emphasized-text t
2588 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2589 Changing this variable requires a restart of Emacs to take effect."
2590 :group 'org-font-lock
2591 :type 'boolean)
2593 (defcustom org-highlight-latex-fragments-and-specials nil
2594 "Non-nil means, fontify what is treated specially by the exporters."
2595 :group 'org-font-lock
2596 :type 'boolean)
2598 (defcustom org-hide-emphasis-markers nil
2599 "Non-nil mean font-lock should hide the emphasis marker characters."
2600 :group 'org-font-lock
2601 :type 'boolean)
2603 (defvar org-emph-re nil
2604 "Regular expression for matching emphasis.")
2605 (defvar org-verbatim-re nil
2606 "Regular expression for matching verbatim text.")
2607 (defvar org-emphasis-regexp-components) ; defined just below
2608 (defvar org-emphasis-alist) ; defined just below
2609 (defun org-set-emph-re (var val)
2610 "Set variable and compute the emphasis regular expression."
2611 (set var val)
2612 (when (and (boundp 'org-emphasis-alist)
2613 (boundp 'org-emphasis-regexp-components)
2614 org-emphasis-alist org-emphasis-regexp-components)
2615 (let* ((e org-emphasis-regexp-components)
2616 (pre (car e))
2617 (post (nth 1 e))
2618 (border (nth 2 e))
2619 (body (nth 3 e))
2620 (nl (nth 4 e))
2621 (body1 (concat body "*?"))
2622 (markers (mapconcat 'car org-emphasis-alist ""))
2623 (vmarkers (mapconcat
2624 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2625 org-emphasis-alist "")))
2626 ;; make sure special characters appear at the right position in the class
2627 (if (string-match "\\^" markers)
2628 (setq markers (concat (replace-match "" t t markers) "^")))
2629 (if (string-match "-" markers)
2630 (setq markers (concat (replace-match "" t t markers) "-")))
2631 (if (string-match "\\^" vmarkers)
2632 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2633 (if (string-match "-" vmarkers)
2634 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2635 (if (> nl 0)
2636 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2637 (int-to-string nl) "\\}")))
2638 ;; Make the regexp
2639 (setq org-emph-re
2640 (concat "\\([" pre "]\\|^\\)"
2641 "\\("
2642 "\\([" markers "]\\)"
2643 "\\("
2644 "[^" border "]\\|"
2645 "[^" border "]"
2646 body1
2647 "[^" border "]"
2648 "\\)"
2649 "\\3\\)"
2650 "\\([" post "]\\|$\\)"))
2651 (setq org-verbatim-re
2652 (concat "\\([" pre "]\\|^\\)"
2653 "\\("
2654 "\\([" vmarkers "]\\)"
2655 "\\("
2656 "[^" border "]\\|"
2657 "[^" border "]"
2658 body1
2659 "[^" border "]"
2660 "\\)"
2661 "\\3\\)"
2662 "\\([" post "]\\|$\\)")))))
2664 (defcustom org-emphasis-regexp-components
2665 '(" \t('\"{" "- \t.,:!?;'\")}" " \t\r\n,\"'" "." 1)
2666 "Components used to build the regular expression for emphasis.
2667 This is a list with 6 entries. Terminology: In an emphasis string
2668 like \" *strong word* \", we call the initial space PREMATCH, the final
2669 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2670 and \"trong wor\" is the body. The different components in this variable
2671 specify what is allowed/forbidden in each part:
2673 pre Chars allowed as prematch. Beginning of line will be allowed too.
2674 post Chars allowed as postmatch. End of line will be allowed too.
2675 border The chars *forbidden* as border characters.
2676 body-regexp A regexp like \".\" to match a body character. Don't use
2677 non-shy groups here, and don't allow newline here.
2678 newline The maximum number of newlines allowed in an emphasis exp.
2680 Use customize to modify this, or restart Emacs after changing it."
2681 :group 'org-font-lock
2682 :set 'org-set-emph-re
2683 :type '(list
2684 (sexp :tag "Allowed chars in pre ")
2685 (sexp :tag "Allowed chars in post ")
2686 (sexp :tag "Forbidden chars in border ")
2687 (sexp :tag "Regexp for body ")
2688 (integer :tag "number of newlines allowed")
2689 (option (boolean :tag "Please ignore this button"))))
2691 (defcustom org-emphasis-alist
2692 `(("*" bold "<b>" "</b>")
2693 ("/" italic "<i>" "</i>")
2694 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2695 ("=" org-code "<code>" "</code>" verbatim)
2696 ("~" org-verbatim "<code>" "</code>" verbatim)
2697 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2698 "<del>" "</del>")
2700 "Special syntax for emphasized text.
2701 Text starting and ending with a special character will be emphasized, for
2702 example *bold*, _underlined_ and /italic/. This variable sets the marker
2703 characters, the face to be used by font-lock for highlighting in Org-mode
2704 Emacs buffers, and the HTML tags to be used for this.
2705 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2706 Use customize to modify this, or restart Emacs after changing it."
2707 :group 'org-font-lock
2708 :set 'org-set-emph-re
2709 :type '(repeat
2710 (list
2711 (string :tag "Marker character")
2712 (choice
2713 (face :tag "Font-lock-face")
2714 (plist :tag "Face property list"))
2715 (string :tag "HTML start tag")
2716 (string :tag "HTML end tag")
2717 (option (const verbatim)))))
2719 ;;; Miscellaneous options
2721 (defgroup org-completion nil
2722 "Completion in Org-mode."
2723 :tag "Org Completion"
2724 :group 'org)
2726 (defcustom org-completion-use-ido nil
2727 "Non-nil means, use ido completion wherever possible.
2728 Note that `ido-mode' must be active for this variable to be relevant.
2729 If you decide to turn this variable on, you might well want to turn off
2730 `org-outline-path-complete-in-steps'."
2731 :group 'org-completion
2732 :type 'boolean)
2734 (defcustom org-completion-fallback-command 'hippie-expand
2735 "The expansion command called by \\[org-complete] in normal context.
2736 Normal means, no org-mode-specific context."
2737 :group 'org-completion
2738 :type 'function)
2740 ;;; Functions and variables from ther packages
2741 ;; Declared here to avoid compiler warnings
2743 ;; XEmacs only
2744 (defvar outline-mode-menu-heading)
2745 (defvar outline-mode-menu-show)
2746 (defvar outline-mode-menu-hide)
2747 (defvar zmacs-regions) ; XEmacs regions
2749 ;; Emacs only
2750 (defvar mark-active)
2752 ;; Various packages
2753 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2754 (declare-function calendar-forward-day "cal-move" (arg))
2755 (declare-function calendar-goto-date "cal-move" (date))
2756 (declare-function calendar-goto-today "cal-move" ())
2757 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2758 (defvar calc-embedded-close-formula)
2759 (defvar calc-embedded-open-formula)
2760 (declare-function cdlatex-tab "ext:cdlatex" ())
2761 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2762 (defvar font-lock-unfontify-region-function)
2763 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2764 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2765 (defvar iswitchb-temp-buflist)
2766 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2767 (defvar org-agenda-tags-todo-honor-ignore-options)
2768 (declare-function org-agenda-skip "org-agenda" ())
2769 (declare-function org-format-agenda-item "org-agenda"
2770 (extra txt &optional category tags dotime noprefix remove-re))
2771 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2772 (declare-function org-agenda-change-all-lines "org-agenda"
2773 (newhead hdmarker &optional fixface just-this))
2774 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2775 (declare-function org-agenda-maybe-redo "org-agenda" ())
2776 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2777 (beg end))
2778 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2779 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2780 "org-agenda" (&optional end))
2782 (declare-function parse-time-string "parse-time" (string))
2783 (declare-function remember "remember" (&optional initial))
2784 (declare-function remember-buffer-desc "remember" ())
2785 (declare-function remember-finalize "remember" ())
2786 (defvar remember-save-after-remembering)
2787 (defvar remember-data-file)
2788 (defvar remember-register)
2789 (defvar remember-buffer)
2790 (defvar remember-handler-functions)
2791 (defvar remember-annotation-functions)
2792 (defvar texmathp-why)
2793 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2794 (declare-function table--at-cell-p "table" (position &optional object at-column))
2796 (defvar w3m-current-url)
2797 (defvar w3m-current-title)
2799 (defvar org-latex-regexps)
2801 ;;; Autoload and prepare some org modules
2803 ;; Some table stuff that needs to be defined here, because it is used
2804 ;; by the functions setting up org-mode or checking for table context.
2806 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2807 "Detects an org-type or table-type table.")
2808 (defconst org-table-line-regexp "^[ \t]*|"
2809 "Detects an org-type table line.")
2810 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2811 "Detects an org-type table line.")
2812 (defconst org-table-hline-regexp "^[ \t]*|-"
2813 "Detects an org-type table hline.")
2814 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2815 "Detects a table-type table hline.")
2816 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2817 "Searching from within a table (any type) this finds the first line
2818 outside the table.")
2820 ;; Autoload the functions in org-table.el that are needed by functions here.
2822 (eval-and-compile
2823 (org-autoload "org-table"
2824 '(org-table-align org-table-begin org-table-blank-field
2825 org-table-convert org-table-convert-region org-table-copy-down
2826 org-table-copy-region org-table-create
2827 org-table-create-or-convert-from-region
2828 org-table-create-with-table.el org-table-current-dline
2829 org-table-cut-region org-table-delete-column org-table-edit-field
2830 org-table-edit-formulas org-table-end org-table-eval-formula
2831 org-table-export org-table-field-info
2832 org-table-get-stored-formulas org-table-goto-column
2833 org-table-hline-and-move org-table-import org-table-insert-column
2834 org-table-insert-hline org-table-insert-row org-table-iterate
2835 org-table-justify-field-maybe org-table-kill-row
2836 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2837 org-table-move-column org-table-move-column-left
2838 org-table-move-column-right org-table-move-row
2839 org-table-move-row-down org-table-move-row-up
2840 org-table-next-field org-table-next-row org-table-paste-rectangle
2841 org-table-previous-field org-table-recalculate
2842 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2843 org-table-toggle-coordinate-overlays
2844 org-table-toggle-formula-debugger org-table-wrap-region
2845 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2847 (defun org-at-table-p (&optional table-type)
2848 "Return t if the cursor is inside an org-type table.
2849 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2850 (if org-enable-table-editor
2851 (save-excursion
2852 (beginning-of-line 1)
2853 (looking-at (if table-type org-table-any-line-regexp
2854 org-table-line-regexp)))
2855 nil))
2856 (defsubst org-table-p () (org-at-table-p))
2858 (defun org-at-table.el-p ()
2859 "Return t if and only if we are at a table.el table."
2860 (and (org-at-table-p 'any)
2861 (save-excursion
2862 (goto-char (org-table-begin 'any))
2863 (looking-at org-table1-hline-regexp))))
2864 (defun org-table-recognize-table.el ()
2865 "If there is a table.el table nearby, recognize it and move into it."
2866 (if org-table-tab-recognizes-table.el
2867 (if (org-at-table.el-p)
2868 (progn
2869 (beginning-of-line 1)
2870 (if (looking-at org-table-dataline-regexp)
2872 (if (looking-at org-table1-hline-regexp)
2873 (progn
2874 (beginning-of-line 2)
2875 (if (looking-at org-table-any-border-regexp)
2876 (beginning-of-line -1)))))
2877 (if (re-search-forward "|" (org-table-end t) t)
2878 (progn
2879 (require 'table)
2880 (if (table--at-cell-p (point))
2882 (message "recognizing table.el table...")
2883 (table-recognize-table)
2884 (message "recognizing table.el table...done")))
2885 (error "This should not happen..."))
2887 nil)
2888 nil))
2890 (defun org-at-table-hline-p ()
2891 "Return t if the cursor is inside a hline in a table."
2892 (if org-enable-table-editor
2893 (save-excursion
2894 (beginning-of-line 1)
2895 (looking-at org-table-hline-regexp))
2896 nil))
2898 (defvar org-table-clean-did-remove-column nil)
2900 (defun org-table-map-tables (function)
2901 "Apply FUNCTION to the start of all tables in the buffer."
2902 (save-excursion
2903 (save-restriction
2904 (widen)
2905 (goto-char (point-min))
2906 (while (re-search-forward org-table-any-line-regexp nil t)
2907 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2908 (beginning-of-line 1)
2909 (if (looking-at org-table-line-regexp)
2910 (save-excursion (funcall function)))
2911 (re-search-forward org-table-any-border-regexp nil 1))))
2912 (message "Mapping tables: done"))
2914 ;; Declare and autoload functions from org-exp.el & Co
2916 (declare-function org-default-export-plist "org-exp")
2917 (declare-function org-infile-export-plist "org-exp")
2918 (declare-function org-get-current-options "org-exp")
2919 (eval-and-compile
2920 (org-autoload "org-exp"
2921 '(org-export org-export-visible
2922 org-insert-export-options-template org-export-as-html-and-open
2923 org-export-as-html-batch org-export-as-html-to-buffer
2924 org-replace-region-by-html org-export-region-as-html
2925 org-export-as-html
2926 org-table-clean-before-export
2929 (eval-and-compile
2930 (org-autoload "org-ascii"
2931 '(org-export-as-ascii org-export-ascii-preprocess)))
2932 (eval-and-compile
2933 (org-autoload "org-icalendar"
2934 '(org-export-icalendar-this-file
2935 org-export-icalendar-all-agenda-files
2936 org-export-icalendar-combine-agenda-files)))
2937 (eval-and-compile
2938 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
2940 ;; Declare and autoload functions from org-agenda.el
2942 (eval-and-compile
2943 (org-autoload "org-agenda"
2944 '(org-agenda org-agenda-list org-search-view
2945 org-todo-list org-tags-view org-agenda-list-stuck-projects
2946 org-diary org-agenda-to-appt
2947 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2949 ;; Autoload org-remember
2951 (eval-and-compile
2952 (org-autoload "org-remember"
2953 '(org-remember-insinuate org-remember-annotation
2954 org-remember-apply-template org-remember org-remember-handler)))
2956 ;; Autoload org-clock.el
2959 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2960 (beg end))
2961 (declare-function org-clock-update-mode-line "org-clock" ())
2962 (defvar org-clock-start-time)
2963 (defvar org-clock-marker (make-marker)
2964 "Marker recording the last clock-in.")
2966 (eval-and-compile
2967 (org-autoload
2968 "org-clock"
2969 '(org-clock-in org-clock-out org-clock-cancel
2970 org-clock-goto org-clock-sum org-clock-display
2971 org-clock-remove-overlays org-clock-report
2972 org-clocktable-shift org-dblock-write:clocktable
2973 org-get-clocktable)))
2975 (defun org-clock-update-time-maybe ()
2976 "If this is a CLOCK line, update it and return t.
2977 Otherwise, return nil."
2978 (interactive)
2979 (save-excursion
2980 (beginning-of-line 1)
2981 (skip-chars-forward " \t")
2982 (when (looking-at org-clock-string)
2983 (let ((re (concat "[ \t]*" org-clock-string
2984 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2985 "\\([ \t]*=>.*\\)?\\)?"))
2986 ts te h m s neg)
2987 (cond
2988 ((not (looking-at re))
2989 nil)
2990 ((not (match-end 2))
2991 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2992 (> org-clock-marker (point))
2993 (<= org-clock-marker (point-at-eol)))
2994 ;; The clock is running here
2995 (setq org-clock-start-time
2996 (apply 'encode-time
2997 (org-parse-time-string (match-string 1))))
2998 (org-clock-update-mode-line)))
3000 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3001 (end-of-line 1)
3002 (setq ts (match-string 1)
3003 te (match-string 3))
3004 (setq s (- (time-to-seconds
3005 (apply 'encode-time (org-parse-time-string te)))
3006 (time-to-seconds
3007 (apply 'encode-time (org-parse-time-string ts))))
3008 neg (< s 0)
3009 s (abs s)
3010 h (floor (/ s 3600))
3011 s (- s (* 3600 h))
3012 m (floor (/ s 60))
3013 s (- s (* 60 s)))
3014 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3015 t))))))
3017 (defun org-check-running-clock ()
3018 "Check if the current buffer contains the running clock.
3019 If yes, offer to stop it and to save the buffer with the changes."
3020 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3021 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3022 (buffer-name))))
3023 (org-clock-out)
3024 (when (y-or-n-p "Save changed buffer?")
3025 (save-buffer))))
3027 (defun org-clocktable-try-shift (dir n)
3028 "Check if this line starts a clock table, if yes, shift the time block."
3029 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3030 (org-clocktable-shift dir n)))
3032 ;; Autoload org-timer.el
3034 (eval-and-compile
3035 (org-autoload
3036 "org-timer"
3037 '(org-timer-start org-timer org-timer-item
3038 org-timer-change-times-in-region)))
3040 ;; Autoload org-feed.el
3042 (eval-and-compile
3043 (org-autoload
3044 "org-feed"
3045 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3048 ;; Autoload archiving code
3049 ;; The stuff that is needed for cycling and tags has to be defined here.
3051 (defgroup org-archive nil
3052 "Options concerning archiving in Org-mode."
3053 :tag "Org Archive"
3054 :group 'org-structure)
3056 (defcustom org-archive-location "%s_archive::"
3057 "The location where subtrees should be archived.
3059 The value of this variable is a string, consisting of two parts,
3060 separated by a double-colon. The first part is a filename and
3061 the second part is a headline.
3063 When the filename is omitted, archiving happens in the same file.
3064 %s in the filename will be replaced by the current file
3065 name (without the directory part). Archiving to a different file
3066 is useful to keep archived entries from contributing to the
3067 Org-mode Agenda.
3069 The archived entries will be filed as subtrees of the specified
3070 headline. When the headline is omitted, the subtrees are simply
3071 filed away at the end of the file, as top-level entries. Also in
3072 the heading you can use %s to represent the file name, this can be
3073 useful when using the same archive for a number of different files.
3075 Here are a few examples:
3076 \"%s_archive::\"
3077 If the current file is Projects.org, archive in file
3078 Projects.org_archive, as top-level trees. This is the default.
3080 \"::* Archived Tasks\"
3081 Archive in the current file, under the top-level headline
3082 \"* Archived Tasks\".
3084 \"~/org/archive.org::\"
3085 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3087 \"~/org/archive.org::From %s\"
3088 Archive in file ~/org/archive.org (absolute path), und headlines
3089 \"From FILENAME\" where file name is the current file name.
3091 \"basement::** Finished Tasks\"
3092 Archive in file ./basement (relative path), as level 3 trees
3093 below the level 2 heading \"** Finished Tasks\".
3095 You may set this option on a per-file basis by adding to the buffer a
3096 line like
3098 #+ARCHIVE: basement::** Finished Tasks
3100 You may also define it locally for a subtree by setting an ARCHIVE property
3101 in the entry. If such a property is found in an entry, or anywhere up
3102 the hierarchy, it will be used."
3103 :group 'org-archive
3104 :type 'string)
3106 (defcustom org-archive-tag "ARCHIVE"
3107 "The tag that marks a subtree as archived.
3108 An archived subtree does not open during visibility cycling, and does
3109 not contribute to the agenda listings.
3110 After changing this, font-lock must be restarted in the relevant buffers to
3111 get the proper fontification."
3112 :group 'org-archive
3113 :group 'org-keywords
3114 :type 'string)
3116 (defcustom org-agenda-skip-archived-trees t
3117 "Non-nil means, the agenda will skip any items located in archived trees.
3118 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3119 variable is no longer recommended, you should leave it at the value t.
3120 Instead, use the key `v' to cycle the archives-mode in the agenda."
3121 :group 'org-archive
3122 :group 'org-agenda-skip
3123 :type 'boolean)
3125 (defcustom org-columns-skip-arrchived-trees t
3126 "Non-nil means, irgnore archived trees when creating column view."
3127 :group 'org-archive
3128 :group 'org-properties
3129 :type 'boolean)
3131 (defcustom org-cycle-open-archived-trees nil
3132 "Non-nil means, `org-cycle' will open archived trees.
3133 An archived tree is a tree marked with the tag ARCHIVE.
3134 When nil, archived trees will stay folded. You can still open them with
3135 normal outline commands like `show-all', but not with the cycling commands."
3136 :group 'org-archive
3137 :group 'org-cycle
3138 :type 'boolean)
3140 (defcustom org-sparse-tree-open-archived-trees nil
3141 "Non-nil means sparse tree construction shows matches in archived trees.
3142 When nil, matches in these trees are highlighted, but the trees are kept in
3143 collapsed state."
3144 :group 'org-archive
3145 :group 'org-sparse-trees
3146 :type 'boolean)
3148 (defun org-cycle-hide-archived-subtrees (state)
3149 "Re-hide all archived subtrees after a visibility state change."
3150 (when (and (not org-cycle-open-archived-trees)
3151 (not (memq state '(overview folded))))
3152 (save-excursion
3153 (let* ((globalp (memq state '(contents all)))
3154 (beg (if globalp (point-min) (point)))
3155 (end (if globalp (point-max) (org-end-of-subtree t))))
3156 (org-hide-archived-subtrees beg end)
3157 (goto-char beg)
3158 (if (looking-at (concat ".*:" org-archive-tag ":"))
3159 (message "%s" (substitute-command-keys
3160 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3162 (defun org-force-cycle-archived ()
3163 "Cycle subtree even if it is archived."
3164 (interactive)
3165 (setq this-command 'org-cycle)
3166 (let ((org-cycle-open-archived-trees t))
3167 (call-interactively 'org-cycle)))
3169 (defun org-hide-archived-subtrees (beg end)
3170 "Re-hide all archived subtrees after a visibility state change."
3171 (save-excursion
3172 (let* ((re (concat ":" org-archive-tag ":")))
3173 (goto-char beg)
3174 (while (re-search-forward re end t)
3175 (and (org-on-heading-p) (hide-subtree))
3176 (org-end-of-subtree t)))))
3178 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3180 (eval-and-compile
3181 (org-autoload "org-archive"
3182 '(org-add-archive-files org-archive-subtree
3183 org-archive-to-archive-sibling org-toggle-archive-tag)))
3185 ;; Autoload Column View Code
3187 (declare-function org-columns-number-to-string "org-colview")
3188 (declare-function org-columns-get-format-and-top-level "org-colview")
3189 (declare-function org-columns-compute "org-colview")
3191 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3192 '(org-columns-number-to-string org-columns-get-format-and-top-level
3193 org-columns-compute org-agenda-columns org-columns-remove-overlays
3194 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3196 ;; Autoload ID code
3198 (declare-function org-id-store-link "org-id")
3199 (declare-function org-id-locations-load "org-id")
3200 (declare-function org-id-locations-save "org-id")
3201 (defvar org-id-track-globally)
3202 (org-autoload "org-id"
3203 '(org-id-get-create org-id-new org-id-copy org-id-get
3204 org-id-get-with-outline-path-completion
3205 org-id-get-with-outline-drilling
3206 org-id-goto org-id-find org-id-store-link))
3208 ;; Autoload Plotting Code
3210 (org-autoload "org-plot"
3211 '(org-plot/gnuplot))
3213 ;;; Variables for pre-computed regular expressions, all buffer local
3215 (defvar org-drawer-regexp nil
3216 "Matches first line of a hidden block.")
3217 (make-variable-buffer-local 'org-drawer-regexp)
3218 (defvar org-todo-regexp nil
3219 "Matches any of the TODO state keywords.")
3220 (make-variable-buffer-local 'org-todo-regexp)
3221 (defvar org-not-done-regexp nil
3222 "Matches any of the TODO state keywords except the last one.")
3223 (make-variable-buffer-local 'org-not-done-regexp)
3224 (defvar org-not-done-heading-regexp nil
3225 "Matches a TODO headline that is not done.")
3226 (make-variable-buffer-local 'org-not-done-regexp)
3227 (defvar org-todo-line-regexp nil
3228 "Matches a headline and puts TODO state into group 2 if present.")
3229 (make-variable-buffer-local 'org-todo-line-regexp)
3230 (defvar org-complex-heading-regexp nil
3231 "Matches a headline and puts everything into groups:
3232 group 1: the stars
3233 group 2: The todo keyword, maybe
3234 group 3: Priority cookie
3235 group 4: True headline
3236 group 5: Tags")
3237 (make-variable-buffer-local 'org-complex-heading-regexp)
3238 (defvar org-todo-line-tags-regexp nil
3239 "Matches a headline and puts TODO state into group 2 if present.
3240 Also put tags into group 4 if tags are present.")
3241 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3242 (defvar org-nl-done-regexp nil
3243 "Matches newline followed by a headline with the DONE keyword.")
3244 (make-variable-buffer-local 'org-nl-done-regexp)
3245 (defvar org-looking-at-done-regexp nil
3246 "Matches the DONE keyword a point.")
3247 (make-variable-buffer-local 'org-looking-at-done-regexp)
3248 (defvar org-ds-keyword-length 12
3249 "Maximum length of the Deadline and SCHEDULED keywords.")
3250 (make-variable-buffer-local 'org-ds-keyword-length)
3251 (defvar org-deadline-regexp nil
3252 "Matches the DEADLINE keyword.")
3253 (make-variable-buffer-local 'org-deadline-regexp)
3254 (defvar org-deadline-time-regexp nil
3255 "Matches the DEADLINE keyword together with a time stamp.")
3256 (make-variable-buffer-local 'org-deadline-time-regexp)
3257 (defvar org-deadline-line-regexp nil
3258 "Matches the DEADLINE keyword and the rest of the line.")
3259 (make-variable-buffer-local 'org-deadline-line-regexp)
3260 (defvar org-scheduled-regexp nil
3261 "Matches the SCHEDULED keyword.")
3262 (make-variable-buffer-local 'org-scheduled-regexp)
3263 (defvar org-scheduled-time-regexp nil
3264 "Matches the SCHEDULED keyword together with a time stamp.")
3265 (make-variable-buffer-local 'org-scheduled-time-regexp)
3266 (defvar org-closed-time-regexp nil
3267 "Matches the CLOSED keyword together with a time stamp.")
3268 (make-variable-buffer-local 'org-closed-time-regexp)
3270 (defvar org-keyword-time-regexp nil
3271 "Matches any of the 4 keywords, together with the time stamp.")
3272 (make-variable-buffer-local 'org-keyword-time-regexp)
3273 (defvar org-keyword-time-not-clock-regexp nil
3274 "Matches any of the 3 keywords, together with the time stamp.")
3275 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3276 (defvar org-maybe-keyword-time-regexp nil
3277 "Matches a timestamp, possibly preceeded by a keyword.")
3278 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3279 (defvar org-planning-or-clock-line-re nil
3280 "Matches a line with planning or clock info.")
3281 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3283 (defconst org-plain-time-of-day-regexp
3284 (concat
3285 "\\(\\<[012]?[0-9]"
3286 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3287 "\\(--?"
3288 "\\(\\<[012]?[0-9]"
3289 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3290 "\\)?")
3291 "Regular expression to match a plain time or time range.
3292 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3293 groups carry important information:
3294 0 the full match
3295 1 the first time, range or not
3296 8 the second time, if it is a range.")
3298 (defconst org-plain-time-extension-regexp
3299 (concat
3300 "\\(\\<[012]?[0-9]"
3301 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3302 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3303 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3304 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3305 groups carry important information:
3306 0 the full match
3307 7 hours of duration
3308 9 minutes of duration")
3310 (defconst org-stamp-time-of-day-regexp
3311 (concat
3312 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3313 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3314 "\\(--?"
3315 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3316 "Regular expression to match a timestamp time or time range.
3317 After a match, the following groups carry important information:
3318 0 the full match
3319 1 date plus weekday, for backreferencing to make sure both times on same day
3320 2 the first time, range or not
3321 4 the second time, if it is a range.")
3323 (defconst org-startup-options
3324 '(("fold" org-startup-folded t)
3325 ("overview" org-startup-folded t)
3326 ("nofold" org-startup-folded nil)
3327 ("showall" org-startup-folded nil)
3328 ("content" org-startup-folded content)
3329 ("hidestars" org-hide-leading-stars t)
3330 ("showstars" org-hide-leading-stars nil)
3331 ("odd" org-odd-levels-only t)
3332 ("oddeven" org-odd-levels-only nil)
3333 ("align" org-startup-align-all-tables t)
3334 ("noalign" org-startup-align-all-tables nil)
3335 ("customtime" org-display-custom-times t)
3336 ("logdone" org-log-done time)
3337 ("lognotedone" org-log-done note)
3338 ("nologdone" org-log-done nil)
3339 ("lognoteclock-out" org-log-note-clock-out t)
3340 ("nolognoteclock-out" org-log-note-clock-out nil)
3341 ("logrepeat" org-log-repeat state)
3342 ("lognoterepeat" org-log-repeat note)
3343 ("nologrepeat" org-log-repeat nil)
3344 ("fninline" org-footnote-define-inline t)
3345 ("nofninline" org-footnote-define-inline nil)
3346 ("fnlocal" org-footnote-section nil)
3347 ("fnauto" org-footnote-auto-label t)
3348 ("fnprompt" org-footnote-auto-label nil)
3349 ("fnconfirm" org-footnote-auto-label confirm)
3350 ("fnplain" org-footnote-auto-label plain)
3351 ("constcgs" constants-unit-system cgs)
3352 ("constSI" constants-unit-system SI)
3353 ("noptag" org-tag-persistent-alist nil))
3354 "Variable associated with STARTUP options for org-mode.
3355 Each element is a list of three items: The startup options as written
3356 in the #+STARTUP line, the corresponding variable, and the value to
3357 set this variable to if the option is found. An optional forth element PUSH
3358 means to push this value onto the list in the variable.")
3360 (defun org-set-regexps-and-options ()
3361 "Precompute regular expressions for current buffer."
3362 (when (org-mode-p)
3363 (org-set-local 'org-todo-kwd-alist nil)
3364 (org-set-local 'org-todo-key-alist nil)
3365 (org-set-local 'org-todo-key-trigger nil)
3366 (org-set-local 'org-todo-keywords-1 nil)
3367 (org-set-local 'org-done-keywords nil)
3368 (org-set-local 'org-todo-heads nil)
3369 (org-set-local 'org-todo-sets nil)
3370 (org-set-local 'org-todo-log-states nil)
3371 (org-set-local 'org-file-properties nil)
3372 (org-set-local 'org-file-tags nil)
3373 (let ((re (org-make-options-regexp
3374 '("CATEGORY" "TODO" "COLUMNS"
3375 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3376 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3377 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3378 (splitre "[ \t]+")
3379 kwds kws0 kwsa key log value cat arch tags const links hw dws
3380 tail sep kws1 prio props ftags drawers
3381 ext-setup-or-nil setup-contents (start 0))
3382 (save-excursion
3383 (save-restriction
3384 (widen)
3385 (goto-char (point-min))
3386 (while (or (and ext-setup-or-nil
3387 (string-match re ext-setup-or-nil start)
3388 (setq start (match-end 0)))
3389 (and (setq ext-setup-or-nil nil start 0)
3390 (re-search-forward re nil t)))
3391 (setq key (upcase (match-string 1 ext-setup-or-nil))
3392 value (org-match-string-no-properties 2 ext-setup-or-nil))
3393 (cond
3394 ((equal key "CATEGORY")
3395 (if (string-match "[ \t]+$" value)
3396 (setq value (replace-match "" t t value)))
3397 (setq cat value))
3398 ((member key '("SEQ_TODO" "TODO"))
3399 (push (cons 'sequence (org-split-string value splitre)) kwds))
3400 ((equal key "TYP_TODO")
3401 (push (cons 'type (org-split-string value splitre)) kwds))
3402 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3403 ;; general TODO-like setup
3404 (push (cons (intern (downcase (match-string 1 key)))
3405 (org-split-string value splitre)) kwds))
3406 ((equal key "TAGS")
3407 (setq tags (append tags (if tags '("\\n") nil)
3408 (org-split-string value splitre))))
3409 ((equal key "COLUMNS")
3410 (org-set-local 'org-columns-default-format value))
3411 ((equal key "LINK")
3412 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3413 (push (cons (match-string 1 value)
3414 (org-trim (match-string 2 value)))
3415 links)))
3416 ((equal key "PRIORITIES")
3417 (setq prio (org-split-string value " +")))
3418 ((equal key "PROPERTY")
3419 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3420 (push (cons (match-string 1 value) (match-string 2 value))
3421 props)))
3422 ((equal key "FILETAGS")
3423 (when (string-match "\\S-" value)
3424 (setq ftags
3425 (append
3426 ftags
3427 (apply 'append
3428 (mapcar (lambda (x) (org-split-string x ":"))
3429 (org-split-string value)))))))
3430 ((equal key "DRAWERS")
3431 (setq drawers (org-split-string value splitre)))
3432 ((equal key "CONSTANTS")
3433 (setq const (append const (org-split-string value splitre))))
3434 ((equal key "STARTUP")
3435 (let ((opts (org-split-string value splitre))
3436 l var val)
3437 (while (setq l (pop opts))
3438 (when (setq l (assoc l org-startup-options))
3439 (setq var (nth 1 l) val (nth 2 l))
3440 (if (not (nth 3 l))
3441 (set (make-local-variable var) val)
3442 (if (not (listp (symbol-value var)))
3443 (set (make-local-variable var) nil))
3444 (set (make-local-variable var) (symbol-value var))
3445 (add-to-list var val))))))
3446 ((equal key "ARCHIVE")
3447 (string-match " *$" value)
3448 (setq arch (replace-match "" t t value))
3449 (remove-text-properties 0 (length arch)
3450 '(face t fontified t) arch))
3451 ((equal key "SETUPFILE")
3452 (setq setup-contents (org-file-contents
3453 (expand-file-name
3454 (org-remove-double-quotes value))
3455 'noerror))
3456 (if (not ext-setup-or-nil)
3457 (setq ext-setup-or-nil setup-contents start 0)
3458 (setq ext-setup-or-nil
3459 (concat (substring ext-setup-or-nil 0 start)
3460 "\n" setup-contents "\n"
3461 (substring ext-setup-or-nil start)))))
3462 ))))
3463 (when cat
3464 (org-set-local 'org-category (intern cat))
3465 (push (cons "CATEGORY" cat) props))
3466 (when prio
3467 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3468 (setq prio (mapcar 'string-to-char prio))
3469 (org-set-local 'org-highest-priority (nth 0 prio))
3470 (org-set-local 'org-lowest-priority (nth 1 prio))
3471 (org-set-local 'org-default-priority (nth 2 prio)))
3472 (and props (org-set-local 'org-file-properties (nreverse props)))
3473 (and ftags (org-set-local 'org-file-tags
3474 (mapcar 'org-add-prop-inherited ftags)))
3475 (and drawers (org-set-local 'org-drawers drawers))
3476 (and arch (org-set-local 'org-archive-location arch))
3477 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3478 ;; Process the TODO keywords
3479 (unless kwds
3480 ;; Use the global values as if they had been given locally.
3481 (setq kwds (default-value 'org-todo-keywords))
3482 (if (stringp (car kwds))
3483 (setq kwds (list (cons org-todo-interpretation
3484 (default-value 'org-todo-keywords)))))
3485 (setq kwds (reverse kwds)))
3486 (setq kwds (nreverse kwds))
3487 (let (inter kws kw)
3488 (while (setq kws (pop kwds))
3489 (let ((kws (or
3490 (run-hook-with-args-until-success
3491 'org-todo-setup-filter-hook kws)
3492 kws)))
3493 (setq inter (pop kws) sep (member "|" kws)
3494 kws0 (delete "|" (copy-sequence kws))
3495 kwsa nil
3496 kws1 (mapcar
3497 (lambda (x)
3498 ;; 1 2
3499 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3500 (progn
3501 (setq kw (match-string 1 x)
3502 key (and (match-end 2) (match-string 2 x))
3503 log (org-extract-log-state-settings x))
3504 (push (cons kw (and key (string-to-char key))) kwsa)
3505 (and log (push log org-todo-log-states))
3507 (error "Invalid TODO keyword %s" x)))
3508 kws0)
3509 kwsa (if kwsa (append '((:startgroup))
3510 (nreverse kwsa)
3511 '((:endgroup))))
3512 hw (car kws1)
3513 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3514 tail (list inter hw (car dws) (org-last dws))))
3515 (add-to-list 'org-todo-heads hw 'append)
3516 (push kws1 org-todo-sets)
3517 (setq org-done-keywords (append org-done-keywords dws nil))
3518 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3519 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3520 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3521 (setq org-todo-sets (nreverse org-todo-sets)
3522 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3523 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3524 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3525 ;; Process the constants
3526 (when const
3527 (let (e cst)
3528 (while (setq e (pop const))
3529 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3530 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3531 (setq org-table-formula-constants-local cst)))
3533 ;; Process the tags.
3534 (when tags
3535 (let (e tgs)
3536 (while (setq e (pop tags))
3537 (cond
3538 ((equal e "{") (push '(:startgroup) tgs))
3539 ((equal e "}") (push '(:endgroup) tgs))
3540 ((equal e "\\n") (push '(:newline) tgs))
3541 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3542 (push (cons (match-string 1 e)
3543 (string-to-char (match-string 2 e)))
3544 tgs))
3545 (t (push (list e) tgs))))
3546 (org-set-local 'org-tag-alist nil)
3547 (while (setq e (pop tgs))
3548 (or (and (stringp (car e))
3549 (assoc (car e) org-tag-alist))
3550 (push e org-tag-alist)))))
3552 ;; Compute the regular expressions and other local variables
3553 (if (not org-done-keywords)
3554 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3555 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3556 (length org-scheduled-string)
3557 (length org-clock-string)
3558 (length org-closed-string)))
3559 org-drawer-regexp
3560 (concat "^[ \t]*:\\("
3561 (mapconcat 'regexp-quote org-drawers "\\|")
3562 "\\):[ \t]*$")
3563 org-not-done-keywords
3564 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3565 org-todo-regexp
3566 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3567 "\\|") "\\)\\>")
3568 org-not-done-regexp
3569 (concat "\\<\\("
3570 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3571 "\\)\\>")
3572 org-not-done-heading-regexp
3573 (concat "^\\(\\*+\\)[ \t]+\\("
3574 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3575 "\\)\\>")
3576 org-todo-line-regexp
3577 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3578 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3579 "\\)\\>\\)?[ \t]*\\(.*\\)")
3580 org-complex-heading-regexp
3581 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3582 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3583 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3584 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3585 org-nl-done-regexp
3586 (concat "\n\\*+[ \t]+"
3587 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3588 "\\)" "\\>")
3589 org-todo-line-tags-regexp
3590 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3591 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3592 (org-re
3593 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3594 org-looking-at-done-regexp
3595 (concat "^" "\\(?:"
3596 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3597 "\\>")
3598 org-deadline-regexp (concat "\\<" org-deadline-string)
3599 org-deadline-time-regexp
3600 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3601 org-deadline-line-regexp
3602 (concat "\\<\\(" org-deadline-string "\\).*")
3603 org-scheduled-regexp
3604 (concat "\\<" org-scheduled-string)
3605 org-scheduled-time-regexp
3606 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3607 org-closed-time-regexp
3608 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3609 org-keyword-time-regexp
3610 (concat "\\<\\(" org-scheduled-string
3611 "\\|" org-deadline-string
3612 "\\|" org-closed-string
3613 "\\|" org-clock-string "\\)"
3614 " *[[<]\\([^]>]+\\)[]>]")
3615 org-keyword-time-not-clock-regexp
3616 (concat "\\<\\(" org-scheduled-string
3617 "\\|" org-deadline-string
3618 "\\|" org-closed-string
3619 "\\)"
3620 " *[[<]\\([^]>]+\\)[]>]")
3621 org-maybe-keyword-time-regexp
3622 (concat "\\(\\<\\(" org-scheduled-string
3623 "\\|" org-deadline-string
3624 "\\|" org-closed-string
3625 "\\|" org-clock-string "\\)\\)?"
3626 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3627 org-planning-or-clock-line-re
3628 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3629 "\\|" org-deadline-string
3630 "\\|" org-closed-string "\\|" org-clock-string
3631 "\\)\\>\\)")
3633 (org-compute-latex-and-specials-regexp)
3634 (org-set-font-lock-defaults))))
3636 (defun org-file-contents (file &optional noerror)
3637 "Return the contents of FILE, as a string."
3638 (if (or (not file)
3639 (not (file-readable-p file)))
3640 (if noerror
3641 (progn
3642 (message "Cannot read file %s" file)
3643 (ding) (sit-for 2)
3645 (error "Cannot read file %s" file))
3646 (with-temp-buffer
3647 (insert-file-contents file)
3648 (buffer-string))))
3650 (defun org-extract-log-state-settings (x)
3651 "Extract the log state setting from a TODO keyword string.
3652 This will extract info from a string like \"WAIT(w@/!)\"."
3653 (let (kw key log1 log2)
3654 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3655 (setq kw (match-string 1 x)
3656 key (and (match-end 2) (match-string 2 x))
3657 log1 (and (match-end 3) (match-string 3 x))
3658 log2 (and (match-end 4) (match-string 4 x)))
3659 (and (or log1 log2)
3660 (list kw
3661 (and log1 (if (equal log1 "!") 'time 'note))
3662 (and log2 (if (equal log2 "!") 'time 'note)))))))
3664 (defun org-remove-keyword-keys (list)
3665 "Remove a pair of parenthesis at the end of each string in LIST."
3666 (mapcar (lambda (x)
3667 (if (string-match "(.*)$" x)
3668 (substring x 0 (match-beginning 0))
3670 list))
3672 ;; FIXME: this could be done much better, using second characters etc.
3673 (defun org-assign-fast-keys (alist)
3674 "Assign fast keys to a keyword-key alist.
3675 Respect keys that are already there."
3676 (let (new e k c c1 c2 (char ?a))
3677 (while (setq e (pop alist))
3678 (cond
3679 ((equal e '(:startgroup)) (push e new))
3680 ((equal e '(:endgroup)) (push e new))
3681 ((equal e '(:newline)) (push e new))
3683 (setq k (car e) c2 nil)
3684 (if (cdr e)
3685 (setq c (cdr e))
3686 ;; automatically assign a character.
3687 (setq c1 (string-to-char
3688 (downcase (substring
3689 k (if (= (string-to-char k) ?@) 1 0)))))
3690 (if (or (rassoc c1 new) (rassoc c1 alist))
3691 (while (or (rassoc char new) (rassoc char alist))
3692 (setq char (1+ char)))
3693 (setq c2 c1))
3694 (setq c (or c2 char)))
3695 (push (cons k c) new))))
3696 (nreverse new)))
3698 ;;; Some variables used in various places
3700 (defvar org-window-configuration nil
3701 "Used in various places to store a window configuration.")
3702 (defvar org-finish-function nil
3703 "Function to be called when `C-c C-c' is used.
3704 This is for getting out of special buffers like remember.")
3707 ;; FIXME: Occasionally check by commenting these, to make sure
3708 ;; no other functions uses these, forgetting to let-bind them.
3709 (defvar entry)
3710 (defvar state)
3711 (defvar last-state)
3712 (defvar date)
3713 (defvar description)
3715 ;; Defined somewhere in this file, but used before definition.
3716 (defvar org-html-entities)
3717 (defvar org-struct-menu)
3718 (defvar org-org-menu)
3719 (defvar org-tbl-menu)
3720 (defvar org-agenda-keymap)
3722 ;;;; Define the Org-mode
3724 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3725 (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."))
3728 ;; We use a before-change function to check if a table might need
3729 ;; an update.
3730 (defvar org-table-may-need-update t
3731 "Indicates that a table might need an update.
3732 This variable is set by `org-before-change-function'.
3733 `org-table-align' sets it back to nil.")
3734 (defun org-before-change-function (beg end)
3735 "Every change indicates that a table might need an update."
3736 (setq org-table-may-need-update t))
3737 (defvar org-mode-map)
3738 (defvar org-mode-hook nil
3739 "Mode hook for Org-mode, run after the mode was turned on.")
3740 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3741 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3742 (defvar org-table-buffer-is-an nil)
3743 (defconst org-outline-regexp "\\*+ ")
3745 ;;;###autoload
3746 (define-derived-mode org-mode outline-mode "Org"
3747 "Outline-based notes management and organizer, alias
3748 \"Carsten's outline-mode for keeping track of everything.\"
3750 Org-mode develops organizational tasks around a NOTES file which
3751 contains information about projects as plain text. Org-mode is
3752 implemented on top of outline-mode, which is ideal to keep the content
3753 of large files well structured. It supports ToDo items, deadlines and
3754 time stamps, which magically appear in the diary listing of the Emacs
3755 calendar. Tables are easily created with a built-in table editor.
3756 Plain text URL-like links connect to websites, emails (VM), Usenet
3757 messages (Gnus), BBDB entries, and any files related to the project.
3758 For printing and sharing of notes, an Org-mode file (or a part of it)
3759 can be exported as a structured ASCII or HTML file.
3761 The following commands are available:
3763 \\{org-mode-map}"
3765 ;; Get rid of Outline menus, they are not needed
3766 ;; Need to do this here because define-derived-mode sets up
3767 ;; the keymap so late. Still, it is a waste to call this each time
3768 ;; we switch another buffer into org-mode.
3769 (if (featurep 'xemacs)
3770 (when (boundp 'outline-mode-menu-heading)
3771 ;; Assume this is Greg's port, it used easymenu
3772 (easy-menu-remove outline-mode-menu-heading)
3773 (easy-menu-remove outline-mode-menu-show)
3774 (easy-menu-remove outline-mode-menu-hide))
3775 (define-key org-mode-map [menu-bar headings] 'undefined)
3776 (define-key org-mode-map [menu-bar hide] 'undefined)
3777 (define-key org-mode-map [menu-bar show] 'undefined))
3779 (org-load-modules-maybe)
3780 (easy-menu-add org-org-menu)
3781 (easy-menu-add org-tbl-menu)
3782 (org-install-agenda-files-menu)
3783 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3784 (org-add-to-invisibility-spec '(org-cwidth))
3785 (when (featurep 'xemacs)
3786 (org-set-local 'line-move-ignore-invisible t))
3787 (org-set-local 'outline-regexp org-outline-regexp)
3788 (org-set-local 'outline-level 'org-outline-level)
3789 (when (and org-ellipsis
3790 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3791 (fboundp 'make-glyph-code))
3792 (unless org-display-table
3793 (setq org-display-table (make-display-table)))
3794 (set-display-table-slot
3795 org-display-table 4
3796 (vconcat (mapcar
3797 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3798 org-ellipsis)))
3799 (if (stringp org-ellipsis) org-ellipsis "..."))))
3800 (setq buffer-display-table org-display-table))
3801 (org-set-regexps-and-options)
3802 (when (and org-tag-faces (not org-tags-special-faces-re))
3803 ;; tag faces set outside customize.... force initialization.
3804 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3805 ;; Calc embedded
3806 (org-set-local 'calc-embedded-open-mode "# ")
3807 (modify-syntax-entry ?# "<")
3808 (modify-syntax-entry ?@ "w")
3809 (if org-startup-truncated (setq truncate-lines t))
3810 (org-set-local 'font-lock-unfontify-region-function
3811 'org-unfontify-region)
3812 ;; Activate before-change-function
3813 (org-set-local 'org-table-may-need-update t)
3814 (org-add-hook 'before-change-functions 'org-before-change-function nil
3815 'local)
3816 ;; Check for running clock before killing a buffer
3817 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3818 ;; Paragraphs and auto-filling
3819 (org-set-autofill-regexps)
3820 (setq indent-line-function 'org-indent-line-function)
3821 (org-update-radio-target-regexp)
3822 ;; Make sure dependence stuff works reliably, even for users who set it
3823 ;; too late :-(
3824 (if org-enforce-todo-dependencies
3825 (add-hook 'org-blocker-hook
3826 'org-block-todo-from-children-or-siblings-or-parent)
3827 (remove-hook 'org-blocker-hook
3828 'org-block-todo-from-children-or-siblings-or-parent))
3829 (if org-enforce-todo-checkbox-dependencies
3830 (add-hook 'org-blocker-hook
3831 'org-block-todo-from-checkboxes)
3832 (remove-hook 'org-blocker-hook
3833 'org-block-todo-from-checkboxes))
3835 ;; Comment characters
3836 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3837 (org-set-local 'comment-padding " ")
3839 ;; Align options lines
3840 (org-set-local
3841 'align-mode-rules-list
3842 '((org-in-buffer-settings
3843 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3844 (modes . '(org-mode)))))
3846 ;; Imenu
3847 (org-set-local 'imenu-create-index-function
3848 'org-imenu-get-tree)
3850 ;; Make isearch reveal context
3851 (if (or (featurep 'xemacs)
3852 (not (boundp 'outline-isearch-open-invisible-function)))
3853 ;; Emacs 21 and XEmacs make use of the hook
3854 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3855 ;; Emacs 22 deals with this through a special variable
3856 (org-set-local 'outline-isearch-open-invisible-function
3857 (lambda (&rest ignore) (org-show-context 'isearch))))
3859 ;; If empty file that did not turn on org-mode automatically, make it to.
3860 (if (and org-insert-mode-line-in-empty-file
3861 (interactive-p)
3862 (= (point-min) (point-max)))
3863 (insert "# -*- mode: org -*-\n\n"))
3865 (unless org-inhibit-startup
3866 (when org-startup-align-all-tables
3867 (let ((bmp (buffer-modified-p)))
3868 (org-table-map-tables 'org-table-align)
3869 (set-buffer-modified-p bmp)))
3870 (org-set-startup-visibility)))
3872 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3874 (defun org-current-time ()
3875 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3876 (if (> (car org-time-stamp-rounding-minutes) 1)
3877 (let ((r (car org-time-stamp-rounding-minutes))
3878 (time (decode-time)))
3879 (apply 'encode-time
3880 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3881 (nthcdr 2 time))))
3882 (current-time)))
3884 ;;;; Font-Lock stuff, including the activators
3886 (defvar org-mouse-map (make-sparse-keymap))
3887 (org-defkey org-mouse-map
3888 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3889 (org-defkey org-mouse-map
3890 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3891 (when org-mouse-1-follows-link
3892 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3893 (when org-tab-follows-link
3894 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3895 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3897 (require 'font-lock)
3899 (defconst org-non-link-chars "]\t\n\r<>")
3900 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3901 "shell" "elisp"))
3902 (defvar org-link-types-re nil
3903 "Matches a link that has a url-like prefix like \"http:\"")
3904 (defvar org-link-re-with-space nil
3905 "Matches a link with spaces, optional angular brackets around it.")
3906 (defvar org-link-re-with-space2 nil
3907 "Matches a link with spaces, optional angular brackets around it.")
3908 (defvar org-link-re-with-space3 nil
3909 "Matches a link with spaces, only for internal part in bracket links.")
3910 (defvar org-angle-link-re nil
3911 "Matches link with angular brackets, spaces are allowed.")
3912 (defvar org-plain-link-re nil
3913 "Matches plain link, without spaces.")
3914 (defvar org-bracket-link-regexp nil
3915 "Matches a link in double brackets.")
3916 (defvar org-bracket-link-analytic-regexp nil
3917 "Regular expression used to analyze links.
3918 Here is what the match groups contain after a match:
3919 1: http:
3920 2: http
3921 3: path
3922 4: [desc]
3923 5: desc")
3924 (defvar org-bracket-link-analytic-regexp++ nil
3925 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3926 (defvar org-any-link-re nil
3927 "Regular expression matching any link.")
3929 (defun org-make-link-regexps ()
3930 "Update the link regular expressions.
3931 This should be called after the variable `org-link-types' has changed."
3932 (setq org-link-types-re
3933 (concat
3934 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3935 org-link-re-with-space
3936 (concat
3937 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3938 "\\([^" org-non-link-chars " ]"
3939 "[^" org-non-link-chars "]*"
3940 "[^" org-non-link-chars " ]\\)>?")
3941 org-link-re-with-space2
3942 (concat
3943 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3944 "\\([^" org-non-link-chars " ]"
3945 "[^\t\n\r]*"
3946 "[^" org-non-link-chars " ]\\)>?")
3947 org-link-re-with-space3
3948 (concat
3949 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3950 "\\([^" org-non-link-chars " ]"
3951 "[^\t\n\r]*\\)")
3952 org-angle-link-re
3953 (concat
3954 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3955 "\\([^" org-non-link-chars " ]"
3956 "[^" org-non-link-chars "]*"
3957 "\\)>")
3958 org-plain-link-re
3959 (concat
3960 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3961 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3962 org-bracket-link-regexp
3963 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3964 org-bracket-link-analytic-regexp
3965 (concat
3966 "\\[\\["
3967 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3968 "\\([^]]+\\)"
3969 "\\]"
3970 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3971 "\\]")
3972 org-bracket-link-analytic-regexp++
3973 (concat
3974 "\\[\\["
3975 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3976 "\\([^]]+\\)"
3977 "\\]"
3978 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3979 "\\]")
3980 org-any-link-re
3981 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3982 org-angle-link-re "\\)\\|\\("
3983 org-plain-link-re "\\)")))
3985 (org-make-link-regexps)
3987 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3988 "Regular expression for fast time stamp matching.")
3989 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3990 "Regular expression for fast time stamp matching.")
3991 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3992 "Regular expression matching time strings for analysis.
3993 This one does not require the space after the date, so it can be used
3994 on a string that terminates immediately after the date.")
3995 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3996 "Regular expression matching time strings for analysis.")
3997 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3998 "Regular expression matching time stamps, with groups.")
3999 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4000 "Regular expression matching time stamps (also [..]), with groups.")
4001 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4002 "Regular expression matching a time stamp range.")
4003 (defconst org-tr-regexp-both
4004 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4005 "Regular expression matching a time stamp range.")
4006 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4007 org-ts-regexp "\\)?")
4008 "Regular expression matching a time stamp or time stamp range.")
4009 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4010 org-ts-regexp-both "\\)?")
4011 "Regular expression matching a time stamp or time stamp range.
4012 The time stamps may be either active or inactive.")
4014 (defvar org-emph-face nil)
4016 (defun org-do-emphasis-faces (limit)
4017 "Run through the buffer and add overlays to links."
4018 (let (rtn)
4019 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4020 (if (not (= (char-after (match-beginning 3))
4021 (char-after (match-beginning 4))))
4022 (progn
4023 (setq rtn t)
4024 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4025 'face
4026 (nth 1 (assoc (match-string 3)
4027 org-emphasis-alist)))
4028 (add-text-properties (match-beginning 2) (match-end 2)
4029 '(font-lock-multiline t))
4030 (when org-hide-emphasis-markers
4031 (add-text-properties (match-end 4) (match-beginning 5)
4032 '(invisible org-link))
4033 (add-text-properties (match-beginning 3) (match-end 3)
4034 '(invisible org-link)))))
4035 (backward-char 1))
4036 rtn))
4038 (defun org-emphasize (&optional char)
4039 "Insert or change an emphasis, i.e. a font like bold or italic.
4040 If there is an active region, change that region to a new emphasis.
4041 If there is no region, just insert the marker characters and position
4042 the cursor between them.
4043 CHAR should be either the marker character, or the first character of the
4044 HTML tag associated with that emphasis. If CHAR is a space, the means
4045 to remove the emphasis of the selected region.
4046 If char is not given (for example in an interactive call) it
4047 will be prompted for."
4048 (interactive)
4049 (let ((eal org-emphasis-alist) e det
4050 (erc org-emphasis-regexp-components)
4051 (prompt "")
4052 (string "") beg end move tag c s)
4053 (if (org-region-active-p)
4054 (setq beg (region-beginning) end (region-end)
4055 string (buffer-substring beg end))
4056 (setq move t))
4058 (while (setq e (pop eal))
4059 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4060 c (aref tag 0))
4061 (push (cons c (string-to-char (car e))) det)
4062 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4063 (substring tag 1)))))
4064 (setq det (nreverse det))
4065 (unless char
4066 (message "%s" (concat "Emphasis marker or tag:" prompt))
4067 (setq char (read-char-exclusive)))
4068 (setq char (or (cdr (assoc char det)) char))
4069 (if (equal char ?\ )
4070 (setq s "" move nil)
4071 (unless (assoc (char-to-string char) org-emphasis-alist)
4072 (error "No such emphasis marker: \"%c\"" char))
4073 (setq s (char-to-string char)))
4074 (while (and (> (length string) 1)
4075 (equal (substring string 0 1) (substring string -1))
4076 (assoc (substring string 0 1) org-emphasis-alist))
4077 (setq string (substring string 1 -1)))
4078 (setq string (concat s string s))
4079 (if beg (delete-region beg end))
4080 (unless (or (bolp)
4081 (string-match (concat "[" (nth 0 erc) "\n]")
4082 (char-to-string (char-before (point)))))
4083 (insert " "))
4084 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4085 (char-to-string (char-after (point))))
4086 (insert " ") (backward-char 1))
4087 (insert string)
4088 (and move (backward-char 1))))
4090 (defconst org-nonsticky-props
4091 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4094 (defun org-activate-plain-links (limit)
4095 "Run through the buffer and add overlays to links."
4096 (catch 'exit
4097 (let (f)
4098 (while (re-search-forward org-plain-link-re limit t)
4099 (setq f (get-text-property (match-beginning 0) 'face))
4100 (if (or (eq f 'org-tag)
4101 (and (listp f) (memq 'org-tag f)))
4103 (add-text-properties (match-beginning 0) (match-end 0)
4104 (list 'mouse-face 'highlight
4105 'rear-nonsticky org-nonsticky-props
4106 'keymap org-mouse-map
4108 (throw 'exit t))))))
4110 (defun org-activate-code (limit)
4111 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4112 (progn
4113 (remove-text-properties (match-beginning 0) (match-end 0)
4114 '(display t invisible t intangible t))
4115 t)))
4117 (defun org-activate-angle-links (limit)
4118 "Run through the buffer and add overlays to links."
4119 (if (re-search-forward org-angle-link-re limit t)
4120 (progn
4121 (add-text-properties (match-beginning 0) (match-end 0)
4122 (list 'mouse-face 'highlight
4123 'rear-nonsticky org-nonsticky-props
4124 'keymap org-mouse-map
4126 t)))
4128 (defun org-activate-footnote-links (limit)
4129 "Run through the buffer and add overlays to links."
4130 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4131 limit t)
4132 (progn
4133 (add-text-properties (match-beginning 2) (match-end 2)
4134 (list 'mouse-face 'highlight
4135 'rear-nonsticky org-nonsticky-props
4136 'keymap org-mouse-map
4137 'help-echo
4138 (if (= (point-at-bol) (match-beginning 2))
4139 "Footnote definition"
4140 "Footnote reference")
4142 t)))
4144 (defun org-activate-bracket-links (limit)
4145 "Run through the buffer and add overlays to bracketed links."
4146 (if (re-search-forward org-bracket-link-regexp limit t)
4147 (let* ((help (concat "LINK: "
4148 (org-match-string-no-properties 1)))
4149 ;; FIXME: above we should remove the escapes.
4150 ;; but that requires another match, protecting match data,
4151 ;; a lot of overhead for font-lock.
4152 (ip (org-maybe-intangible
4153 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4154 'keymap org-mouse-map 'mouse-face 'highlight
4155 'font-lock-multiline t 'help-echo help)))
4156 (vp (list 'rear-nonsticky org-nonsticky-props
4157 'keymap org-mouse-map 'mouse-face 'highlight
4158 'font-lock-multiline t 'help-echo help)))
4159 ;; We need to remove the invisible property here. Table narrowing
4160 ;; may have made some of this invisible.
4161 (remove-text-properties (match-beginning 0) (match-end 0)
4162 '(invisible nil))
4163 (if (match-end 3)
4164 (progn
4165 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4166 (add-text-properties (match-beginning 3) (match-end 3) vp)
4167 (add-text-properties (match-end 3) (match-end 0) ip))
4168 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4169 (add-text-properties (match-beginning 1) (match-end 1) vp)
4170 (add-text-properties (match-end 1) (match-end 0) ip))
4171 t)))
4173 (defun org-activate-dates (limit)
4174 "Run through the buffer and add overlays to dates."
4175 (if (re-search-forward org-tsr-regexp-both limit t)
4176 (progn
4177 (add-text-properties (match-beginning 0) (match-end 0)
4178 (list 'mouse-face 'highlight
4179 'rear-nonsticky org-nonsticky-props
4180 'keymap org-mouse-map))
4181 (when org-display-custom-times
4182 (if (match-end 3)
4183 (org-display-custom-time (match-beginning 3) (match-end 3)))
4184 (org-display-custom-time (match-beginning 1) (match-end 1)))
4185 t)))
4187 (defvar org-target-link-regexp nil
4188 "Regular expression matching radio targets in plain text.")
4189 (make-variable-buffer-local 'org-target-link-regexp)
4190 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4191 "Regular expression matching a link target.")
4192 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4193 "Regular expression matching a radio target.")
4194 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4195 "Regular expression matching any target.")
4197 (defun org-activate-target-links (limit)
4198 "Run through the buffer and add overlays to target matches."
4199 (when org-target-link-regexp
4200 (let ((case-fold-search t))
4201 (if (re-search-forward org-target-link-regexp limit t)
4202 (progn
4203 (add-text-properties (match-beginning 0) (match-end 0)
4204 (list 'mouse-face 'highlight
4205 'rear-nonsticky org-nonsticky-props
4206 'keymap org-mouse-map
4207 'help-echo "Radio target link"
4208 'org-linked-text t))
4209 t)))))
4211 (defun org-update-radio-target-regexp ()
4212 "Find all radio targets in this file and update the regular expression."
4213 (interactive)
4214 (when (memq 'radio org-activate-links)
4215 (setq org-target-link-regexp
4216 (org-make-target-link-regexp (org-all-targets 'radio)))
4217 (org-restart-font-lock)))
4219 (defun org-hide-wide-columns (limit)
4220 (let (s e)
4221 (setq s (text-property-any (point) (or limit (point-max))
4222 'org-cwidth t))
4223 (when s
4224 (setq e (next-single-property-change s 'org-cwidth))
4225 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4226 (goto-char e)
4227 t)))
4229 (defvar org-latex-and-specials-regexp nil
4230 "Regular expression for highlighting export special stuff.")
4231 (defvar org-match-substring-regexp)
4232 (defvar org-match-substring-with-braces-regexp)
4233 (defvar org-export-html-special-string-regexps)
4235 (defun org-compute-latex-and-specials-regexp ()
4236 "Compute regular expression for stuff treated specially by exporters."
4237 (if (not org-highlight-latex-fragments-and-specials)
4238 (org-set-local 'org-latex-and-specials-regexp nil)
4239 (require 'org-exp)
4240 (let*
4241 ((matchers (plist-get org-format-latex-options :matchers))
4242 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4243 org-latex-regexps)))
4244 (options (org-combine-plists (org-default-export-plist)
4245 (org-infile-export-plist)))
4246 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4247 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4248 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4249 (org-export-html-expand (plist-get options :expand-quoted-html))
4250 (org-export-with-special-strings (plist-get options :special-strings))
4251 (re-sub
4252 (cond
4253 ((equal org-export-with-sub-superscripts '{})
4254 (list org-match-substring-with-braces-regexp))
4255 (org-export-with-sub-superscripts
4256 (list org-match-substring-regexp))
4257 (t nil)))
4258 (re-latex
4259 (if org-export-with-LaTeX-fragments
4260 (mapcar (lambda (x) (nth 1 x)) latexs)))
4261 (re-macros
4262 (if org-export-with-TeX-macros
4263 (list (concat "\\\\"
4264 (regexp-opt
4265 (append (mapcar 'car org-html-entities)
4266 (if (boundp 'org-latex-entities)
4267 org-latex-entities nil))
4268 'words))) ; FIXME
4270 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4271 (re-special (if org-export-with-special-strings
4272 (mapcar (lambda (x) (car x))
4273 org-export-html-special-string-regexps)))
4274 (re-rest
4275 (delq nil
4276 (list
4277 (if org-export-html-expand "@<[^>\n]+>")
4278 ))))
4279 (org-set-local
4280 'org-latex-and-specials-regexp
4281 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4282 re-rest) "\\|")))))
4284 (defun org-do-latex-and-special-faces (limit)
4285 "Run through the buffer and add overlays to links."
4286 (when org-latex-and-specials-regexp
4287 (let (rtn d)
4288 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4289 limit t))
4290 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4291 'face))
4292 '(org-code org-verbatim underline)))
4293 (progn
4294 (setq rtn t
4295 d (cond ((member (char-after (1+ (match-beginning 0)))
4296 '(?_ ?^)) 1)
4297 (t 0)))
4298 (font-lock-prepend-text-property
4299 (+ d (match-beginning 0)) (match-end 0)
4300 'face 'org-latex-and-export-specials)
4301 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4302 '(font-lock-multiline t)))))
4303 rtn)))
4305 (defun org-restart-font-lock ()
4306 "Restart font-lock-mode, to force refontification."
4307 (when (and (boundp 'font-lock-mode) font-lock-mode)
4308 (font-lock-mode -1)
4309 (font-lock-mode 1)))
4311 (defun org-all-targets (&optional radio)
4312 "Return a list of all targets in this file.
4313 With optional argument RADIO, only find radio targets."
4314 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4315 rtn)
4316 (save-excursion
4317 (goto-char (point-min))
4318 (while (re-search-forward re nil t)
4319 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4320 rtn)))
4322 (defun org-make-target-link-regexp (targets)
4323 "Make regular expression matching all strings in TARGETS.
4324 The regular expression finds the targets also if there is a line break
4325 between words."
4326 (and targets
4327 (concat
4328 "\\<\\("
4329 (mapconcat
4330 (lambda (x)
4331 (while (string-match " +" x)
4332 (setq x (replace-match "\\s-+" t t x)))
4334 targets
4335 "\\|")
4336 "\\)\\>")))
4338 (defun org-activate-tags (limit)
4339 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4340 (progn
4341 (add-text-properties (match-beginning 1) (match-end 1)
4342 (list 'mouse-face 'highlight
4343 'rear-nonsticky org-nonsticky-props
4344 'keymap org-mouse-map))
4345 t)))
4347 (defun org-outline-level ()
4348 (save-excursion
4349 (looking-at outline-regexp)
4350 (if (match-beginning 1)
4351 (+ (org-get-string-indentation (match-string 1)) 1000)
4352 (1- (- (match-end 0) (match-beginning 0))))))
4354 (defvar org-font-lock-keywords nil)
4356 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4357 "Regular expression matching a property line.")
4359 (defvar org-font-lock-hook nil
4360 "Functions to be called for special font lock stuff.")
4362 (defun org-font-lock-hook (limit)
4363 (run-hook-with-args 'org-font-lock-hook limit))
4365 (defun org-set-font-lock-defaults ()
4366 (let* ((em org-fontify-emphasized-text)
4367 (lk org-activate-links)
4368 (org-font-lock-extra-keywords
4369 (list
4370 ;; Call the hook
4371 '(org-font-lock-hook)
4372 ;; Headlines
4373 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4374 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4375 ;; Table lines
4376 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4377 (1 'org-table t))
4378 ;; Table internals
4379 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4380 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4381 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4382 ;; Drawers
4383 (list org-drawer-regexp '(0 'org-special-keyword t))
4384 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4385 ;; Properties
4386 (list org-property-re
4387 '(1 'org-special-keyword t)
4388 '(3 'org-property-value t))
4389 (if org-format-transports-properties-p
4390 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4391 ;; Links
4392 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4393 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4394 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4395 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4396 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4397 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4398 (if (memq 'footnote lk) '(org-activate-footnote-links
4399 (2 'org-footnote t)))
4400 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4401 '(org-hide-wide-columns (0 nil append))
4402 ;; TODO lines
4403 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4404 '(1 (org-get-todo-face 1) t))
4405 ;; DONE
4406 (if org-fontify-done-headline
4407 (list (concat "^[*]+ +\\<\\("
4408 (mapconcat 'regexp-quote org-done-keywords "\\|")
4409 "\\)\\(.*\\)")
4410 '(2 'org-headline-done t))
4411 nil)
4412 ;; Priorities
4413 '(org-font-lock-add-priority-faces)
4414 ;; Tags
4415 '(org-font-lock-add-tag-faces)
4416 ;; Special keywords
4417 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4418 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4419 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4420 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4421 ;; Emphasis
4422 (if em
4423 (if (featurep 'xemacs)
4424 '(org-do-emphasis-faces (0 nil append))
4425 '(org-do-emphasis-faces)))
4426 ;; Checkboxes
4427 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4428 2 'org-checkbox prepend)
4429 (if org-provide-checkbox-statistics
4430 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4431 (0 (org-get-checkbox-statistics-face) t)))
4432 ;; Description list items
4433 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4434 2 'bold prepend)
4435 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4436 '(1 'org-archived prepend))
4437 ;; Specials
4438 '(org-do-latex-and-special-faces)
4439 ;; Code
4440 '(org-activate-code (1 'org-code t))
4441 ;; COMMENT
4442 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4443 "\\|" org-quote-string "\\)\\>")
4444 '(1 'org-special-keyword t))
4445 '("^#.*" (0 'font-lock-comment-face t))
4447 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4448 ;; Now set the full font-lock-keywords
4449 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4450 (org-set-local 'font-lock-defaults
4451 '(org-font-lock-keywords t nil nil backward-paragraph))
4452 (kill-local-variable 'font-lock-keywords) nil))
4454 (defvar org-m nil)
4455 (defvar org-l nil)
4456 (defvar org-f nil)
4457 (defun org-get-level-face (n)
4458 "Get the right face for match N in font-lock matching of headlines."
4459 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4460 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4461 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4462 (cond
4463 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4464 ((eq n 2) org-f)
4465 (t (if org-level-color-stars-only nil org-f))))
4467 (defun org-get-todo-face (kwd)
4468 "Get the right face for a TODO keyword KWD.
4469 If KWD is a number, get the corresponding match group."
4470 (if (numberp kwd) (setq kwd (match-string kwd)))
4471 (or (cdr (assoc kwd org-todo-keyword-faces))
4472 (and (member kwd org-done-keywords) 'org-done)
4473 'org-todo))
4475 (defun org-font-lock-add-tag-faces (limit)
4476 "Add the special tag faces."
4477 (when (and org-tag-faces org-tags-special-faces-re)
4478 (while (re-search-forward org-tags-special-faces-re limit t)
4479 (add-text-properties (match-beginning 1) (match-end 1)
4480 (list 'face (org-get-tag-face 1)
4481 'font-lock-fontified t))
4482 (backward-char 1))))
4484 (defun org-font-lock-add-priority-faces (limit)
4485 "Add the special priority faces."
4486 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4487 (add-text-properties
4488 (match-beginning 0) (match-end 0)
4489 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4490 org-priority-faces))
4491 'org-special-keyword)
4492 'font-lock-fontified t))))
4494 (defun org-get-tag-face (kwd)
4495 "Get the right face for a TODO keyword KWD.
4496 If KWD is a number, get the corresponding match group."
4497 (if (numberp kwd) (setq kwd (match-string kwd)))
4498 (or (cdr (assoc kwd org-tag-faces))
4499 'org-tag))
4501 (defun org-unfontify-region (beg end &optional maybe_loudly)
4502 "Remove fontification and activation overlays from links."
4503 (font-lock-default-unfontify-region beg end)
4504 (let* ((buffer-undo-list t)
4505 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4506 (inhibit-modification-hooks t)
4507 deactivate-mark buffer-file-name buffer-file-truename)
4508 (remove-text-properties beg end
4509 '(mouse-face t keymap t org-linked-text t
4510 invisible t intangible t))))
4512 ;;;; Visibility cycling, including org-goto and indirect buffer
4514 ;;; Cycling
4516 (defvar org-cycle-global-status nil)
4517 (make-variable-buffer-local 'org-cycle-global-status)
4518 (defvar org-cycle-subtree-status nil)
4519 (make-variable-buffer-local 'org-cycle-subtree-status)
4521 ;;;###autoload
4523 (defvar org-inlinetask-min-level)
4524 (defun org-cycle (&optional arg)
4525 "Visibility cycling for Org-mode.
4527 - When this function is called with a prefix argument, rotate the entire
4528 buffer through 3 states (global cycling)
4529 1. OVERVIEW: Show only top-level headlines.
4530 2. CONTENTS: Show all headlines of all levels, but no body text.
4531 3. SHOW ALL: Show everything.
4532 When called with two C-u C-u prefixes, switch to the startup visibility,
4533 determined by the variable `org-startup-folded', and by any VISIBILITY
4534 properties in the buffer.
4535 When called with three C-u C-u C-u prefixed, show the entire buffer,
4536 including drawers.
4538 - When point is at the beginning of a headline, rotate the subtree started
4539 by this line through 3 different states (local cycling)
4540 1. FOLDED: Only the main headline is shown.
4541 2. CHILDREN: The main headline and the direct children are shown.
4542 From this state, you can move to one of the children
4543 and zoom in further.
4544 3. SUBTREE: Show the entire subtree, including body text.
4546 - When there is a numeric prefix, go up to a heading with level ARG, do
4547 a `show-subtree' and return to the previous cursor position. If ARG
4548 is negative, go up that many levels.
4550 - When point is not at the beginning of a headline, execute the global
4551 binding for TAB, which is re-indenting the line. See the option
4552 `org-cycle-emulate-tab' for details.
4554 - Special case: if point is at the beginning of the buffer and there is
4555 no headline in line 1, this function will act as if called with prefix arg.
4556 But only if also the variable `org-cycle-global-at-bob' is t."
4557 (interactive "P")
4558 (org-load-modules-maybe)
4559 (let* ((limit-level
4560 (or org-cycle-max-level
4561 (and (boundp 'org-inlinetask-min-level)
4562 org-inlinetask-min-level
4563 (1- org-inlinetask-min-level))))
4564 (nstars (and limit-level
4565 (if org-odd-levels-only
4566 (and limit-level (1- (* limit-level 2)))
4567 limit-level)))
4568 (outline-regexp
4569 (cond
4570 ((not (org-mode-p)) outline-regexp)
4571 (org-cycle-include-plain-lists
4572 (concat "\\(?:\\*"
4573 (if nstars (format "\\{1,%d\\} " nstars) "+")
4574 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4575 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4576 (bob-special (and org-cycle-global-at-bob (bobp)
4577 (not (looking-at outline-regexp))))
4578 (org-cycle-hook
4579 (if bob-special
4580 (delq 'org-optimize-window-after-visibility-change
4581 (copy-sequence org-cycle-hook))
4582 org-cycle-hook))
4583 (pos (point)))
4585 (if (or bob-special (equal arg '(4)))
4586 ;; special case: use global cycling
4587 (setq arg t))
4589 (cond
4591 ((equal arg '(16))
4592 (org-set-startup-visibility)
4593 (message "Startup visibility, plus VISIBILITY properties"))
4595 ((equal arg '(64))
4596 (show-all)
4597 (message "Entire buffer visible, including drawers"))
4599 ((org-at-table-p 'any)
4600 ;; Enter the table or move to the next field in the table
4601 (or (org-table-recognize-table.el)
4602 (progn
4603 (if arg (org-table-edit-field t)
4604 (org-table-justify-field-maybe)
4605 (call-interactively 'org-table-next-field)))))
4607 ((eq arg t) ;; Global cycling
4609 (cond
4610 ((and (eq last-command this-command)
4611 (eq org-cycle-global-status 'overview))
4612 ;; We just created the overview - now do table of contents
4613 ;; This can be slow in very large buffers, so indicate action
4614 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4615 (message "CONTENTS...")
4616 (org-content)
4617 (message "CONTENTS...done")
4618 (setq org-cycle-global-status 'contents)
4619 (run-hook-with-args 'org-cycle-hook 'contents))
4621 ((and (eq last-command this-command)
4622 (eq org-cycle-global-status 'contents))
4623 ;; We just showed the table of contents - now show everything
4624 (run-hook-with-args 'org-pre-cycle-hook 'all)
4625 (show-all)
4626 (message "SHOW ALL")
4627 (setq org-cycle-global-status 'all)
4628 (run-hook-with-args 'org-cycle-hook 'all))
4631 ;; Default action: go to overview
4632 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4633 (org-overview)
4634 (message "OVERVIEW")
4635 (setq org-cycle-global-status 'overview)
4636 (run-hook-with-args 'org-cycle-hook 'overview))))
4638 ((and org-drawers org-drawer-regexp
4639 (save-excursion
4640 (beginning-of-line 1)
4641 (looking-at org-drawer-regexp)))
4642 ;; Toggle block visibility
4643 (org-flag-drawer
4644 (not (get-char-property (match-end 0) 'invisible))))
4646 ((integerp arg)
4647 ;; Show-subtree, ARG levels up from here.
4648 (save-excursion
4649 (org-back-to-heading)
4650 (outline-up-heading (if (< arg 0) (- arg)
4651 (- (funcall outline-level) arg)))
4652 (org-show-subtree)))
4654 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4655 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4656 ;; At a heading: rotate between three different views
4657 (org-back-to-heading)
4658 (let ((goal-column 0) eoh eol eos)
4659 ;; First, some boundaries
4660 (save-excursion
4661 (org-back-to-heading)
4662 (save-excursion
4663 (beginning-of-line 2)
4664 (while (and (not (eobp)) ;; this is like `next-line'
4665 (get-char-property (1- (point)) 'invisible))
4666 (beginning-of-line 2)) (setq eol (point)))
4667 (outline-end-of-heading) (setq eoh (point))
4668 (org-end-of-subtree t)
4669 (unless (eobp)
4670 (skip-chars-forward " \t\n")
4671 (beginning-of-line 1) ; in case this is an item
4673 (setq eos (1- (point))))
4674 ;; Find out what to do next and set `this-command'
4675 (cond
4676 ((= eos eoh)
4677 ;; Nothing is hidden behind this heading
4678 (run-hook-with-args 'org-pre-cycle-hook 'empty)
4679 (message "EMPTY ENTRY")
4680 (setq org-cycle-subtree-status nil)
4681 (save-excursion
4682 (goto-char eos)
4683 (outline-next-heading)
4684 (if (org-invisible-p) (org-flag-heading nil))))
4685 ((or (>= eol eos)
4686 (not (string-match "\\S-" (buffer-substring eol eos))))
4687 ;; Entire subtree is hidden in one line: open it
4688 (run-hook-with-args 'org-pre-cycle-hook 'children)
4689 (org-show-entry)
4690 (show-children)
4691 (message "CHILDREN")
4692 (save-excursion
4693 (goto-char eos)
4694 (outline-next-heading)
4695 (if (org-invisible-p) (org-flag-heading nil)))
4696 (setq org-cycle-subtree-status 'children)
4697 (run-hook-with-args 'org-cycle-hook 'children))
4698 ((and (eq last-command this-command)
4699 (eq org-cycle-subtree-status 'children))
4700 ;; We just showed the children, now show everything.
4701 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
4702 (org-show-subtree)
4703 (message "SUBTREE")
4704 (setq org-cycle-subtree-status 'subtree)
4705 (run-hook-with-args 'org-cycle-hook 'subtree))
4707 ;; Default action: hide the subtree.
4708 (run-hook-with-args 'org-pre-cycle-hook 'folded)
4709 (hide-subtree)
4710 (message "FOLDED")
4711 (setq org-cycle-subtree-status 'folded)
4712 (run-hook-with-args 'org-cycle-hook 'folded)))))
4714 ;; TAB emulation and template completion
4715 (buffer-read-only (org-back-to-heading))
4717 ((org-try-structure-completion))
4719 ((org-try-cdlatex-tab))
4721 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4722 (or (not (bolp))
4723 (not (looking-at outline-regexp))))
4724 (call-interactively (global-key-binding "\t")))
4726 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4727 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4728 (or (and (eq org-cycle-emulate-tab 'white)
4729 (= (match-end 0) (point-at-eol)))
4730 (and (eq org-cycle-emulate-tab 'whitestart)
4731 (>= (match-end 0) pos))))
4733 (eq org-cycle-emulate-tab t))
4734 (call-interactively (global-key-binding "\t")))
4736 (t (save-excursion
4737 (org-back-to-heading)
4738 (org-cycle))))))
4740 ;;;###autoload
4741 (defun org-global-cycle (&optional arg)
4742 "Cycle the global visibility. For details see `org-cycle'.
4743 With C-u prefix arg, switch to startup visibility.
4744 With a numeric prefix, show all headlines up to that level."
4745 (interactive "P")
4746 (let ((org-cycle-include-plain-lists
4747 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4748 (cond
4749 ((integerp arg)
4750 (show-all)
4751 (hide-sublevels arg)
4752 (setq org-cycle-global-status 'contents))
4753 ((equal arg '(4))
4754 (org-set-startup-visibility)
4755 (message "Startup visibility, plus VISIBILITY properties."))
4757 (org-cycle '(4))))))
4759 (defun org-set-startup-visibility ()
4760 "Set the visibility required by startup options and properties."
4761 (cond
4762 ((eq org-startup-folded t)
4763 (org-cycle '(4)))
4764 ((eq org-startup-folded 'content)
4765 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4766 (org-cycle '(4)) (org-cycle '(4)))))
4767 (org-set-visibility-according-to-property 'no-cleanup)
4768 (org-cycle-hide-archived-subtrees 'all)
4769 (org-cycle-hide-drawers 'all)
4770 (org-cycle-show-empty-lines 'all))
4772 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4773 "Switch subtree visibilities according to :VISIBILITY: property."
4774 (interactive)
4775 (let (org-show-entry-below state)
4776 (save-excursion
4777 (goto-char (point-min))
4778 (while (re-search-forward
4779 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4780 nil t)
4781 (setq state (match-string 1))
4782 (save-excursion
4783 (org-back-to-heading t)
4784 (hide-subtree)
4785 (org-reveal)
4786 (cond
4787 ((equal state '("fold" "folded"))
4788 (hide-subtree))
4789 ((equal state "children")
4790 (org-show-hidden-entry)
4791 (show-children))
4792 ((equal state "content")
4793 (save-excursion
4794 (save-restriction
4795 (org-narrow-to-subtree)
4796 (org-content))))
4797 ((member state '("all" "showall"))
4798 (show-subtree)))))
4799 (unless no-cleanup
4800 (org-cycle-hide-archived-subtrees 'all)
4801 (org-cycle-hide-drawers 'all)
4802 (org-cycle-show-empty-lines 'all)))))
4804 (defun org-overview ()
4805 "Switch to overview mode, showing only top-level headlines.
4806 Really, this shows all headlines with level equal or greater than the level
4807 of the first headline in the buffer. This is important, because if the
4808 first headline is not level one, then (hide-sublevels 1) gives confusing
4809 results."
4810 (interactive)
4811 (let ((level (save-excursion
4812 (goto-char (point-min))
4813 (if (re-search-forward (concat "^" outline-regexp) nil t)
4814 (progn
4815 (goto-char (match-beginning 0))
4816 (funcall outline-level))))))
4817 (and level (hide-sublevels level))))
4819 (defun org-content (&optional arg)
4820 "Show all headlines in the buffer, like a table of contents.
4821 With numerical argument N, show content up to level N."
4822 (interactive "P")
4823 (save-excursion
4824 ;; Visit all headings and show their offspring
4825 (and (integerp arg) (org-overview))
4826 (goto-char (point-max))
4827 (catch 'exit
4828 (while (and (progn (condition-case nil
4829 (outline-previous-visible-heading 1)
4830 (error (goto-char (point-min))))
4832 (looking-at outline-regexp))
4833 (if (integerp arg)
4834 (show-children (1- arg))
4835 (show-branches))
4836 (if (bobp) (throw 'exit nil))))))
4839 (defun org-optimize-window-after-visibility-change (state)
4840 "Adjust the window after a change in outline visibility.
4841 This function is the default value of the hook `org-cycle-hook'."
4842 (when (get-buffer-window (current-buffer))
4843 (cond
4844 ((eq state 'content) nil)
4845 ((eq state 'all) nil)
4846 ((eq state 'folded) nil)
4847 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4848 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4850 (defun org-compact-display-after-subtree-move ()
4851 "Show a compacter version of the tree of the entry's parent."
4852 (save-excursion
4853 (if (org-up-heading-safe)
4854 (progn
4855 (hide-subtree)
4856 (show-entry)
4857 (show-children)
4858 (org-cycle-show-empty-lines 'children)
4859 (org-cycle-hide-drawers 'children))
4860 (org-overview))))
4862 (defun org-cycle-show-empty-lines (state)
4863 "Show empty lines above all visible headlines.
4864 The region to be covered depends on STATE when called through
4865 `org-cycle-hook'. Lisp program can use t for STATE to get the
4866 entire buffer covered. Note that an empty line is only shown if there
4867 are at least `org-cycle-separator-lines' empty lines before the headline."
4868 (when (> org-cycle-separator-lines 0)
4869 (save-excursion
4870 (let* ((n org-cycle-separator-lines)
4871 (re (cond
4872 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4873 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4874 (t (let ((ns (number-to-string (- n 2))))
4875 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4876 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4877 beg end)
4878 (cond
4879 ((memq state '(overview contents t))
4880 (setq beg (point-min) end (point-max)))
4881 ((memq state '(children folded))
4882 (setq beg (point) end (progn (org-end-of-subtree t t)
4883 (beginning-of-line 2)
4884 (point)))))
4885 (when beg
4886 (goto-char beg)
4887 (while (re-search-forward re end t)
4888 (if (not (get-char-property (match-end 1) 'invisible))
4889 (outline-flag-region
4890 (match-beginning 1) (match-end 1) nil)))))))
4891 ;; Never hide empty lines at the end of the file.
4892 (save-excursion
4893 (goto-char (point-max))
4894 (outline-previous-heading)
4895 (outline-end-of-heading)
4896 (if (and (looking-at "[ \t\n]+")
4897 (= (match-end 0) (point-max)))
4898 (outline-flag-region (point) (match-end 0) nil))))
4900 (defun org-show-empty-lines-in-parent ()
4901 "Move to the parent and re-show empty lines before visible headlines."
4902 (save-excursion
4903 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4904 (org-cycle-show-empty-lines context))))
4906 (defun org-cycle-hide-drawers (state)
4907 "Re-hide all drawers after a visibility state change."
4908 (when (and (org-mode-p)
4909 (not (memq state '(overview folded))))
4910 (save-excursion
4911 (let* ((globalp (memq state '(contents all)))
4912 (beg (if globalp (point-min) (point)))
4913 (end (if globalp (point-max) (org-end-of-subtree t))))
4914 (goto-char beg)
4915 (while (re-search-forward org-drawer-regexp end t)
4916 (org-flag-drawer t))))))
4918 (defun org-flag-drawer (flag)
4919 (save-excursion
4920 (beginning-of-line 1)
4921 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4922 (let ((b (match-end 0))
4923 (outline-regexp org-outline-regexp))
4924 (if (re-search-forward
4925 "^[ \t]*:END:"
4926 (save-excursion (outline-next-heading) (point)) t)
4927 (outline-flag-region b (point-at-eol) flag)
4928 (error ":END: line missing"))))))
4930 (defun org-subtree-end-visible-p ()
4931 "Is the end of the current subtree visible?"
4932 (pos-visible-in-window-p
4933 (save-excursion (org-end-of-subtree t) (point))))
4935 (defun org-first-headline-recenter (&optional N)
4936 "Move cursor to the first headline and recenter the headline.
4937 Optional argument N means, put the headline into the Nth line of the window."
4938 (goto-char (point-min))
4939 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4940 (beginning-of-line)
4941 (recenter (prefix-numeric-value N))))
4943 ;;; Org-goto
4945 (defvar org-goto-window-configuration nil)
4946 (defvar org-goto-marker nil)
4947 (defvar org-goto-map
4948 (let ((map (make-sparse-keymap)))
4949 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4950 (while (setq cmd (pop cmds))
4951 (substitute-key-definition cmd cmd map global-map)))
4952 (suppress-keymap map)
4953 (org-defkey map "\C-m" 'org-goto-ret)
4954 (org-defkey map [(return)] 'org-goto-ret)
4955 (org-defkey map [(left)] 'org-goto-left)
4956 (org-defkey map [(right)] 'org-goto-right)
4957 (org-defkey map [(control ?g)] 'org-goto-quit)
4958 (org-defkey map "\C-i" 'org-cycle)
4959 (org-defkey map [(tab)] 'org-cycle)
4960 (org-defkey map [(down)] 'outline-next-visible-heading)
4961 (org-defkey map [(up)] 'outline-previous-visible-heading)
4962 (if org-goto-auto-isearch
4963 (if (fboundp 'define-key-after)
4964 (define-key-after map [t] 'org-goto-local-auto-isearch)
4965 nil)
4966 (org-defkey map "q" 'org-goto-quit)
4967 (org-defkey map "n" 'outline-next-visible-heading)
4968 (org-defkey map "p" 'outline-previous-visible-heading)
4969 (org-defkey map "f" 'outline-forward-same-level)
4970 (org-defkey map "b" 'outline-backward-same-level)
4971 (org-defkey map "u" 'outline-up-heading))
4972 (org-defkey map "/" 'org-occur)
4973 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4974 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4975 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4976 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4977 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4978 map))
4980 (defconst org-goto-help
4981 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4982 RET=jump to location [Q]uit and return to previous location
4983 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4985 (defvar org-goto-start-pos) ; dynamically scoped parameter
4987 ;; FIXME: Docstring doe not mention both interfaces
4988 (defun org-goto (&optional alternative-interface)
4989 "Look up a different location in the current file, keeping current visibility.
4991 When you want look-up or go to a different location in a document, the
4992 fastest way is often to fold the entire buffer and then dive into the tree.
4993 This method has the disadvantage, that the previous location will be folded,
4994 which may not be what you want.
4996 This command works around this by showing a copy of the current buffer
4997 in an indirect buffer, in overview mode. You can dive into the tree in
4998 that copy, use org-occur and incremental search to find a location.
4999 When pressing RET or `Q', the command returns to the original buffer in
5000 which the visibility is still unchanged. After RET is will also jump to
5001 the location selected in the indirect buffer and expose the
5002 the headline hierarchy above."
5003 (interactive "P")
5004 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5005 (org-refile-use-outline-path t)
5006 (interface
5007 (if (not alternative-interface)
5008 org-goto-interface
5009 (if (eq org-goto-interface 'outline)
5010 'outline-path-completion
5011 'outline)))
5012 (org-goto-start-pos (point))
5013 (selected-point
5014 (if (eq interface 'outline)
5015 (car (org-get-location (current-buffer) org-goto-help))
5016 (nth 3 (org-refile-get-location "Goto: ")))))
5017 (if selected-point
5018 (progn
5019 (org-mark-ring-push org-goto-start-pos)
5020 (goto-char selected-point)
5021 (if (or (org-invisible-p) (org-invisible-p2))
5022 (org-show-context 'org-goto)))
5023 (message "Quit"))))
5025 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5026 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5027 (defvar org-goto-local-auto-isearch-map) ; defined below
5029 (defun org-get-location (buf help)
5030 "Let the user select a location in the Org-mode buffer BUF.
5031 This function uses a recursive edit. It returns the selected position
5032 or nil."
5033 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5034 (isearch-hide-immediately nil)
5035 (isearch-search-fun-function
5036 (lambda () 'org-goto-local-search-headings))
5037 (org-goto-selected-point org-goto-exit-command))
5038 (save-excursion
5039 (save-window-excursion
5040 (delete-other-windows)
5041 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5042 (switch-to-buffer
5043 (condition-case nil
5044 (make-indirect-buffer (current-buffer) "*org-goto*")
5045 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5046 (with-output-to-temp-buffer "*Help*"
5047 (princ help))
5048 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5049 (setq buffer-read-only nil)
5050 (let ((org-startup-truncated t)
5051 (org-startup-folded nil)
5052 (org-startup-align-all-tables nil))
5053 (org-mode)
5054 (org-overview))
5055 (setq buffer-read-only t)
5056 (if (and (boundp 'org-goto-start-pos)
5057 (integer-or-marker-p org-goto-start-pos))
5058 (let ((org-show-hierarchy-above t)
5059 (org-show-siblings t)
5060 (org-show-following-heading t))
5061 (goto-char org-goto-start-pos)
5062 (and (org-invisible-p) (org-show-context)))
5063 (goto-char (point-min)))
5064 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5065 (message "Select location and press RET")
5066 (use-local-map org-goto-map)
5067 (recursive-edit)
5069 (kill-buffer "*org-goto*")
5070 (cons org-goto-selected-point org-goto-exit-command)))
5072 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5073 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5074 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5075 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5077 (defun org-goto-local-search-headings (string bound noerror)
5078 "Search and make sure that any matches are in headlines."
5079 (catch 'return
5080 (while (if isearch-forward
5081 (search-forward string bound noerror)
5082 (search-backward string bound noerror))
5083 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5084 (and (member :headline context)
5085 (not (member :tags context))))
5086 (throw 'return (point))))))
5088 (defun org-goto-local-auto-isearch ()
5089 "Start isearch."
5090 (interactive)
5091 (goto-char (point-min))
5092 (let ((keys (this-command-keys)))
5093 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5094 (isearch-mode t)
5095 (isearch-process-search-char (string-to-char keys)))))
5097 (defun org-goto-ret (&optional arg)
5098 "Finish `org-goto' by going to the new location."
5099 (interactive "P")
5100 (setq org-goto-selected-point (point)
5101 org-goto-exit-command 'return)
5102 (throw 'exit nil))
5104 (defun org-goto-left ()
5105 "Finish `org-goto' by going to the new location."
5106 (interactive)
5107 (if (org-on-heading-p)
5108 (progn
5109 (beginning-of-line 1)
5110 (setq org-goto-selected-point (point)
5111 org-goto-exit-command 'left)
5112 (throw 'exit nil))
5113 (error "Not on a heading")))
5115 (defun org-goto-right ()
5116 "Finish `org-goto' by going to the new location."
5117 (interactive)
5118 (if (org-on-heading-p)
5119 (progn
5120 (setq org-goto-selected-point (point)
5121 org-goto-exit-command 'right)
5122 (throw 'exit nil))
5123 (error "Not on a heading")))
5125 (defun org-goto-quit ()
5126 "Finish `org-goto' without cursor motion."
5127 (interactive)
5128 (setq org-goto-selected-point nil)
5129 (setq org-goto-exit-command 'quit)
5130 (throw 'exit nil))
5132 ;;; Indirect buffer display of subtrees
5134 (defvar org-indirect-dedicated-frame nil
5135 "This is the frame being used for indirect tree display.")
5136 (defvar org-last-indirect-buffer nil)
5138 (defun org-tree-to-indirect-buffer (&optional arg)
5139 "Create indirect buffer and narrow it to current subtree.
5140 With numerical prefix ARG, go up to this level and then take that tree.
5141 If ARG is negative, go up that many levels.
5142 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5143 indirect buffer previously made with this command, to avoid proliferation of
5144 indirect buffers. However, when you call the command with a `C-u' prefix, or
5145 when `org-indirect-buffer-display' is `new-frame', the last buffer
5146 is kept so that you can work with several indirect buffers at the same time.
5147 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5148 requests that a new frame be made for the new buffer, so that the dedicated
5149 frame is not changed."
5150 (interactive "P")
5151 (let ((cbuf (current-buffer))
5152 (cwin (selected-window))
5153 (pos (point))
5154 beg end level heading ibuf)
5155 (save-excursion
5156 (org-back-to-heading t)
5157 (when (numberp arg)
5158 (setq level (org-outline-level))
5159 (if (< arg 0) (setq arg (+ level arg)))
5160 (while (> (setq level (org-outline-level)) arg)
5161 (outline-up-heading 1 t)))
5162 (setq beg (point)
5163 heading (org-get-heading))
5164 (org-end-of-subtree t) (setq end (point)))
5165 (if (and (buffer-live-p org-last-indirect-buffer)
5166 (not (eq org-indirect-buffer-display 'new-frame))
5167 (not arg))
5168 (kill-buffer org-last-indirect-buffer))
5169 (setq ibuf (org-get-indirect-buffer cbuf)
5170 org-last-indirect-buffer ibuf)
5171 (cond
5172 ((or (eq org-indirect-buffer-display 'new-frame)
5173 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5174 (select-frame (make-frame))
5175 (delete-other-windows)
5176 (switch-to-buffer ibuf)
5177 (org-set-frame-title heading))
5178 ((eq org-indirect-buffer-display 'dedicated-frame)
5179 (raise-frame
5180 (select-frame (or (and org-indirect-dedicated-frame
5181 (frame-live-p org-indirect-dedicated-frame)
5182 org-indirect-dedicated-frame)
5183 (setq org-indirect-dedicated-frame (make-frame)))))
5184 (delete-other-windows)
5185 (switch-to-buffer ibuf)
5186 (org-set-frame-title (concat "Indirect: " heading)))
5187 ((eq org-indirect-buffer-display 'current-window)
5188 (switch-to-buffer ibuf))
5189 ((eq org-indirect-buffer-display 'other-window)
5190 (pop-to-buffer ibuf))
5191 (t (error "Invalid value.")))
5192 (if (featurep 'xemacs)
5193 (save-excursion (org-mode) (turn-on-font-lock)))
5194 (narrow-to-region beg end)
5195 (show-all)
5196 (goto-char pos)
5197 (and (window-live-p cwin) (select-window cwin))))
5199 (defun org-get-indirect-buffer (&optional buffer)
5200 (setq buffer (or buffer (current-buffer)))
5201 (let ((n 1) (base (buffer-name buffer)) bname)
5202 (while (buffer-live-p
5203 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5204 (setq n (1+ n)))
5205 (condition-case nil
5206 (make-indirect-buffer buffer bname 'clone)
5207 (error (make-indirect-buffer buffer bname)))))
5209 (defun org-set-frame-title (title)
5210 "Set the title of the current frame to the string TITLE."
5211 ;; FIXME: how to name a single frame in XEmacs???
5212 (unless (featurep 'xemacs)
5213 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5215 ;;;; Structure editing
5217 ;;; Inserting headlines
5219 (defun org-previous-line-empty-p ()
5220 (save-excursion
5221 (and (not (bobp))
5222 (or (beginning-of-line 0) t)
5223 (save-match-data
5224 (looking-at "[ \t]*$")))))
5226 (defun org-insert-heading (&optional force-heading)
5227 "Insert a new heading or item with same depth at point.
5228 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5229 If point is at the beginning of a headline, insert a sibling before the
5230 current headline. If point is not at the beginning, do not split the line,
5231 but create the new headline after the current line."
5232 (interactive "P")
5233 (if (= (buffer-size) 0)
5234 (insert "\n* ")
5235 (when (or force-heading (not (org-insert-item)))
5236 (let* ((empty-line-p nil)
5237 (head (save-excursion
5238 (condition-case nil
5239 (progn
5240 (org-back-to-heading)
5241 (setq empty-line-p (org-previous-line-empty-p))
5242 (match-string 0))
5243 (error "*"))))
5244 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5245 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5246 pos hide-previous previous-pos)
5247 (cond
5248 ((and (org-on-heading-p) (bolp)
5249 (or (bobp)
5250 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5251 ;; insert before the current line
5252 (open-line (if blank 2 1)))
5253 ((and (bolp)
5254 (or (bobp)
5255 (save-excursion
5256 (backward-char 1) (not (org-invisible-p)))))
5257 ;; insert right here
5258 nil)
5260 ;; somewhere in the line
5261 (save-excursion
5262 (setq previous-pos (point-at-bol))
5263 (end-of-line)
5264 (setq hide-previous (org-invisible-p)))
5265 (and org-insert-heading-respect-content (org-show-subtree))
5266 (let ((split
5267 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5268 (save-excursion
5269 (let ((p (point)))
5270 (goto-char (point-at-bol))
5271 (and (looking-at org-complex-heading-regexp)
5272 (> p (match-beginning 4)))))))
5273 tags pos)
5274 (cond
5275 (org-insert-heading-respect-content
5276 (org-end-of-subtree nil t)
5277 (or (bolp) (newline))
5278 (or (org-previous-line-empty-p)
5279 (and blank (newline)))
5280 (open-line 1))
5281 ((org-on-heading-p)
5282 (when hide-previous
5283 (show-children)
5284 (org-show-entry))
5285 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5286 (setq tags (and (match-end 2) (match-string 2)))
5287 (and (match-end 1)
5288 (delete-region (match-beginning 1) (match-end 1)))
5289 (setq pos (point-at-bol))
5290 (or split (end-of-line 1))
5291 (delete-horizontal-space)
5292 (newline (if blank 2 1))
5293 (when tags
5294 (save-excursion
5295 (goto-char pos)
5296 (end-of-line 1)
5297 (insert " " tags)
5298 (org-set-tags nil 'align))))
5300 (or split (end-of-line 1))
5301 (newline (if blank 2 1)))))))
5302 (insert head) (just-one-space)
5303 (setq pos (point))
5304 (end-of-line 1)
5305 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5306 (when (and org-insert-heading-respect-content hide-previous)
5307 (save-excursion
5308 (goto-char previous-pos)
5309 (hide-subtree)))
5310 (run-hooks 'org-insert-heading-hook)))))
5312 (defun org-get-heading (&optional no-tags)
5313 "Return the heading of the current entry, without the stars."
5314 (save-excursion
5315 (org-back-to-heading t)
5316 (if (looking-at
5317 (if no-tags
5318 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5319 "\\*+[ \t]+\\([^\r\n]*\\)"))
5320 (match-string 1) "")))
5322 (defun org-heading-components ()
5323 "Return the components of the current heading.
5324 This is a list with the following elements:
5325 - the level as an integer
5326 - the reduced level, different if `org-odd-levels-only' is set.
5327 - the TODO keyword, or nil
5328 - the priority character, like ?A, or nil if no priority is given
5329 - the headline text itself, or the tags string if no headline text
5330 - the tags string, or nil."
5331 (save-excursion
5332 (org-back-to-heading t)
5333 (if (looking-at org-complex-heading-regexp)
5334 (list (length (match-string 1))
5335 (org-reduced-level (length (match-string 1)))
5336 (org-match-string-no-properties 2)
5337 (and (match-end 3) (aref (match-string 3) 2))
5338 (org-match-string-no-properties 4)
5339 (org-match-string-no-properties 5)))))
5341 (defun org-get-entry ()
5342 "Get the entry text, after heading, entire subtree."
5343 (save-excursion
5344 (org-back-to-heading t)
5345 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5347 (defun org-insert-heading-after-current ()
5348 "Insert a new heading with same level as current, after current subtree."
5349 (interactive)
5350 (org-back-to-heading)
5351 (org-insert-heading)
5352 (org-move-subtree-down)
5353 (end-of-line 1))
5355 (defun org-insert-heading-respect-content ()
5356 (interactive)
5357 (let ((org-insert-heading-respect-content t))
5358 (org-insert-heading t)))
5360 (defun org-insert-todo-heading-respect-content (&optional force-state)
5361 (interactive "P")
5362 (let ((org-insert-heading-respect-content t))
5363 (org-insert-todo-heading force-state t)))
5365 (defun org-insert-todo-heading (arg &optional force-heading)
5366 "Insert a new heading with the same level and TODO state as current heading.
5367 If the heading has no TODO state, or if the state is DONE, use the first
5368 state (TODO by default). Also with prefix arg, force first state."
5369 (interactive "P")
5370 (when (or force-heading (not (org-insert-item 'checkbox)))
5371 (org-insert-heading force-heading)
5372 (save-excursion
5373 (org-back-to-heading)
5374 (outline-previous-heading)
5375 (looking-at org-todo-line-regexp))
5376 (let*
5377 ((new-mark-x
5378 (if (or arg
5379 (not (match-beginning 2))
5380 (member (match-string 2) org-done-keywords))
5381 (car org-todo-keywords-1)
5382 (match-string 2)))
5383 (new-mark
5385 (run-hook-with-args-until-success
5386 'org-todo-get-default-hook new-mark-x nil)
5387 new-mark-x)))
5388 (beginning-of-line 1)
5389 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5390 (insert new-mark " ")))
5391 (when org-provide-todo-statistics
5392 (org-update-parent-todo-statistics))))
5394 (defun org-insert-subheading (arg)
5395 "Insert a new subheading and demote it.
5396 Works for outline headings and for plain lists alike."
5397 (interactive "P")
5398 (org-insert-heading arg)
5399 (cond
5400 ((org-on-heading-p) (org-do-demote))
5401 ((org-at-item-p) (org-indent-item 1))))
5403 (defun org-insert-todo-subheading (arg)
5404 "Insert a new subheading with TODO keyword or checkbox and demote it.
5405 Works for outline headings and for plain lists alike."
5406 (interactive "P")
5407 (org-insert-todo-heading arg)
5408 (cond
5409 ((org-on-heading-p) (org-do-demote))
5410 ((org-at-item-p) (org-indent-item 1))))
5412 ;;; Promotion and Demotion
5414 (defun org-promote-subtree ()
5415 "Promote the entire subtree.
5416 See also `org-promote'."
5417 (interactive)
5418 (save-excursion
5419 (org-map-tree 'org-promote))
5420 (org-fix-position-after-promote))
5422 (defun org-demote-subtree ()
5423 "Demote the entire subtree. See `org-demote'.
5424 See also `org-promote'."
5425 (interactive)
5426 (save-excursion
5427 (org-map-tree 'org-demote))
5428 (org-fix-position-after-promote))
5431 (defun org-do-promote ()
5432 "Promote the current heading higher up the tree.
5433 If the region is active in `transient-mark-mode', promote all headings
5434 in the region."
5435 (interactive)
5436 (save-excursion
5437 (if (org-region-active-p)
5438 (org-map-region 'org-promote (region-beginning) (region-end))
5439 (org-promote)))
5440 (org-fix-position-after-promote))
5442 (defun org-do-demote ()
5443 "Demote the current heading lower down the tree.
5444 If the region is active in `transient-mark-mode', demote all headings
5445 in the region."
5446 (interactive)
5447 (save-excursion
5448 (if (org-region-active-p)
5449 (org-map-region 'org-demote (region-beginning) (region-end))
5450 (org-demote)))
5451 (org-fix-position-after-promote))
5453 (defun org-fix-position-after-promote ()
5454 "Make sure that after pro/demotion cursor position is right."
5455 (let ((pos (point)))
5456 (when (save-excursion
5457 (beginning-of-line 1)
5458 (looking-at org-todo-line-regexp)
5459 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5460 (cond ((eobp) (insert " "))
5461 ((eolp) (insert " "))
5462 ((equal (char-after) ?\ ) (forward-char 1))))))
5464 (defun org-reduced-level (l)
5465 "Compute the effective level of a heading.
5466 This takes into account the setting of `org-odd-levels-only'."
5467 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5469 (defun org-get-valid-level (level &optional change)
5470 "Rectify a level change under the influence of `org-odd-levels-only'
5471 LEVEL is a current level, CHANGE is by how much the level should be
5472 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5473 even level numbers will become the next higher odd number."
5474 (if org-odd-levels-only
5475 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5476 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5477 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5478 (max 1 (+ level (or change 0)))))
5480 (if (boundp 'define-obsolete-function-alias)
5481 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5482 (define-obsolete-function-alias 'org-get-legal-level
5483 'org-get-valid-level)
5484 (define-obsolete-function-alias 'org-get-legal-level
5485 'org-get-valid-level "23.1")))
5487 (defun org-promote ()
5488 "Promote the current heading higher up the tree.
5489 If the region is active in `transient-mark-mode', promote all headings
5490 in the region."
5491 (org-back-to-heading t)
5492 (let* ((level (save-match-data (funcall outline-level)))
5493 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5494 (diff (abs (- level (length up-head) -1))))
5495 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5496 (replace-match up-head nil t)
5497 ;; Fixup tag positioning
5498 (and org-auto-align-tags (org-set-tags nil t))
5499 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5501 (defun org-demote ()
5502 "Demote the current heading lower down the tree.
5503 If the region is active in `transient-mark-mode', demote all headings
5504 in the region."
5505 (org-back-to-heading t)
5506 (let* ((level (save-match-data (funcall outline-level)))
5507 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5508 (diff (abs (- level (length down-head) -1))))
5509 (replace-match down-head nil t)
5510 ;; Fixup tag positioning
5511 (and org-auto-align-tags (org-set-tags nil t))
5512 (if org-adapt-indentation (org-fixup-indentation diff))))
5514 (defun org-map-tree (fun)
5515 "Call FUN for every heading underneath the current one."
5516 (org-back-to-heading)
5517 (let ((level (funcall outline-level)))
5518 (save-excursion
5519 (funcall fun)
5520 (while (and (progn
5521 (outline-next-heading)
5522 (> (funcall outline-level) level))
5523 (not (eobp)))
5524 (funcall fun)))))
5526 (defun org-map-region (fun beg end)
5527 "Call FUN for every heading between BEG and END."
5528 (let ((org-ignore-region t))
5529 (save-excursion
5530 (setq end (copy-marker end))
5531 (goto-char beg)
5532 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5533 (< (point) end))
5534 (funcall fun))
5535 (while (and (progn
5536 (outline-next-heading)
5537 (< (point) end))
5538 (not (eobp)))
5539 (funcall fun)))))
5541 (defun org-fixup-indentation (diff)
5542 "Change the indentation in the current entry by DIFF
5543 However, if any line in the current entry has no indentation, or if it
5544 would end up with no indentation after the change, nothing at all is done."
5545 (save-excursion
5546 (let ((end (save-excursion (outline-next-heading)
5547 (point-marker)))
5548 (prohibit (if (> diff 0)
5549 "^\\S-"
5550 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5551 col)
5552 (unless (save-excursion (end-of-line 1)
5553 (re-search-forward prohibit end t))
5554 (while (and (< (point) end)
5555 (re-search-forward "^[ \t]+" end t))
5556 (goto-char (match-end 0))
5557 (setq col (current-column))
5558 (if (< diff 0) (replace-match ""))
5559 (org-indent-to-column (+ diff col))))
5560 (move-marker end nil))))
5562 (defun org-convert-to-odd-levels ()
5563 "Convert an org-mode file with all levels allowed to one with odd levels.
5564 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5565 level 5 etc."
5566 (interactive)
5567 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5568 (let ((org-odd-levels-only nil) n)
5569 (save-excursion
5570 (goto-char (point-min))
5571 (while (re-search-forward "^\\*\\*+ " nil t)
5572 (setq n (- (length (match-string 0)) 2))
5573 (while (>= (setq n (1- n)) 0)
5574 (org-demote))
5575 (end-of-line 1))))))
5578 (defun org-convert-to-oddeven-levels ()
5579 "Convert an org-mode file with only odd levels to one with odd and even levels.
5580 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5581 section with an even level, conversion would destroy the structure of the file. An error
5582 is signaled in this case."
5583 (interactive)
5584 (goto-char (point-min))
5585 ;; First check if there are no even levels
5586 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5587 (org-show-context t)
5588 (error "Not all levels are odd in this file. Conversion not possible."))
5589 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5590 (let ((org-odd-levels-only nil) n)
5591 (save-excursion
5592 (goto-char (point-min))
5593 (while (re-search-forward "^\\*\\*+ " nil t)
5594 (setq n (/ (1- (length (match-string 0))) 2))
5595 (while (>= (setq n (1- n)) 0)
5596 (org-promote))
5597 (end-of-line 1))))))
5599 (defun org-tr-level (n)
5600 "Make N odd if required."
5601 (if org-odd-levels-only (1+ (/ n 2)) n))
5603 ;;; Vertical tree motion, cutting and pasting of subtrees
5605 (defun org-move-subtree-up (&optional arg)
5606 "Move the current subtree up past ARG headlines of the same level."
5607 (interactive "p")
5608 (org-move-subtree-down (- (prefix-numeric-value arg))))
5610 (defun org-move-subtree-down (&optional arg)
5611 "Move the current subtree down past ARG headlines of the same level."
5612 (interactive "p")
5613 (setq arg (prefix-numeric-value arg))
5614 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5615 'outline-get-last-sibling))
5616 (ins-point (make-marker))
5617 (cnt (abs arg))
5618 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5619 ;; Select the tree
5620 (org-back-to-heading)
5621 (setq beg0 (point))
5622 (save-excursion
5623 (setq ne-beg (org-back-over-empty-lines))
5624 (setq beg (point)))
5625 (save-match-data
5626 (save-excursion (outline-end-of-heading)
5627 (setq folded (org-invisible-p)))
5628 (outline-end-of-subtree))
5629 (outline-next-heading)
5630 (setq ne-end (org-back-over-empty-lines))
5631 (setq end (point))
5632 (goto-char beg0)
5633 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5634 ;; include less whitespace
5635 (save-excursion
5636 (goto-char beg)
5637 (forward-line (- ne-beg ne-end))
5638 (setq beg (point))))
5639 ;; Find insertion point, with error handling
5640 (while (> cnt 0)
5641 (or (and (funcall movfunc) (looking-at outline-regexp))
5642 (progn (goto-char beg0)
5643 (error "Cannot move past superior level or buffer limit")))
5644 (setq cnt (1- cnt)))
5645 (if (> arg 0)
5646 ;; Moving forward - still need to move over subtree
5647 (progn (org-end-of-subtree t t)
5648 (save-excursion
5649 (org-back-over-empty-lines)
5650 (or (bolp) (newline)))))
5651 (setq ne-ins (org-back-over-empty-lines))
5652 (move-marker ins-point (point))
5653 (setq txt (buffer-substring beg end))
5654 (org-save-markers-in-region beg end)
5655 (delete-region beg end)
5656 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5657 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5658 (and (not (bolp)) (looking-at "\n") (forward-char 1))
5659 (let ((bbb (point)))
5660 (insert-before-markers txt)
5661 (org-reinstall-markers-in-region bbb)
5662 (move-marker ins-point bbb))
5663 (or (bolp) (insert "\n"))
5664 (setq ins-end (point))
5665 (goto-char ins-point)
5666 (org-skip-whitespace)
5667 (when (and (< arg 0)
5668 (org-first-sibling-p)
5669 (> ne-ins ne-beg))
5670 ;; Move whitespace back to beginning
5671 (save-excursion
5672 (goto-char ins-end)
5673 (let ((kill-whole-line t))
5674 (kill-line (- ne-ins ne-beg)) (point)))
5675 (insert (make-string (- ne-ins ne-beg) ?\n)))
5676 (move-marker ins-point nil)
5677 (org-compact-display-after-subtree-move)
5678 (org-show-empty-lines-in-parent)
5679 (unless folded
5680 (org-show-entry)
5681 (show-children)
5682 (org-cycle-hide-drawers 'children))))
5684 (defvar org-subtree-clip ""
5685 "Clipboard for cut and paste of subtrees.
5686 This is actually only a copy of the kill, because we use the normal kill
5687 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5689 (defvar org-subtree-clip-folded nil
5690 "Was the last copied subtree folded?
5691 This is used to fold the tree back after pasting.")
5693 (defun org-cut-subtree (&optional n)
5694 "Cut the current subtree into the clipboard.
5695 With prefix arg N, cut this many sequential subtrees.
5696 This is a short-hand for marking the subtree and then cutting it."
5697 (interactive "p")
5698 (org-copy-subtree n 'cut))
5700 (defun org-copy-subtree (&optional n cut force-store-markers)
5701 "Cut the current subtree into the clipboard.
5702 With prefix arg N, cut this many sequential subtrees.
5703 This is a short-hand for marking the subtree and then copying it.
5704 If CUT is non-nil, actually cut the subtree.
5705 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5706 of some markers in the region, even if CUT is non-nil. This is
5707 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5708 (interactive "p")
5709 (let (beg end folded (beg0 (point)))
5710 (if (interactive-p)
5711 (org-back-to-heading nil) ; take what looks like a subtree
5712 (org-back-to-heading t)) ; take what is really there
5713 (org-back-over-empty-lines)
5714 (setq beg (point))
5715 (skip-chars-forward " \t\r\n")
5716 (save-match-data
5717 (save-excursion (outline-end-of-heading)
5718 (setq folded (org-invisible-p)))
5719 (condition-case nil
5720 (outline-forward-same-level (1- n))
5721 (error nil))
5722 (org-end-of-subtree t t))
5723 (org-back-over-empty-lines)
5724 (setq end (point))
5725 (goto-char beg0)
5726 (when (> end beg)
5727 (setq org-subtree-clip-folded folded)
5728 (when (or cut force-store-markers)
5729 (org-save-markers-in-region beg end))
5730 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5731 (setq org-subtree-clip (current-kill 0))
5732 (message "%s: Subtree(s) with %d characters"
5733 (if cut "Cut" "Copied")
5734 (length org-subtree-clip)))))
5736 (defun org-paste-subtree (&optional level tree for-yank)
5737 "Paste the clipboard as a subtree, with modification of headline level.
5738 The entire subtree is promoted or demoted in order to match a new headline
5739 level.
5741 If the cursor is at the beginning of a headline, the same level as
5742 that headline is used to paste the tree
5744 If not, the new level is derived from the *visible* headings
5745 before and after the insertion point, and taken to be the inferior headline
5746 level of the two. So if the previous visible heading is level 3 and the
5747 next is level 4 (or vice versa), level 4 will be used for insertion.
5748 This makes sure that the subtree remains an independent subtree and does
5749 not swallow low level entries.
5751 You can also force a different level, either by using a numeric prefix
5752 argument, or by inserting the heading marker by hand. For example, if the
5753 cursor is after \"*****\", then the tree will be shifted to level 5.
5755 If optional TREE is given, use this text instead of the kill ring.
5757 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5758 move back over whitespace before inserting, and move point to the end of
5759 the inserted text when done."
5760 (interactive "P")
5761 (unless (org-kill-is-subtree-p tree)
5762 (error "%s"
5763 (substitute-command-keys
5764 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5765 (let* ((visp (not (org-invisible-p)))
5766 (txt (or tree (and kill-ring (current-kill 0))))
5767 (^re (concat "^\\(" outline-regexp "\\)"))
5768 (re (concat "\\(" outline-regexp "\\)"))
5769 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5771 (old-level (if (string-match ^re txt)
5772 (- (match-end 0) (match-beginning 0) 1)
5773 -1))
5774 (force-level (cond (level (prefix-numeric-value level))
5775 ((and (looking-at "[ \t]*$")
5776 (string-match
5777 ^re_ (buffer-substring
5778 (point-at-bol) (point))))
5779 (- (match-end 1) (match-beginning 1)))
5780 ((and (bolp)
5781 (looking-at org-outline-regexp))
5782 (- (match-end 0) (point) 1))
5783 (t nil)))
5784 (previous-level (save-excursion
5785 (condition-case nil
5786 (progn
5787 (outline-previous-visible-heading 1)
5788 (if (looking-at re)
5789 (- (match-end 0) (match-beginning 0) 1)
5791 (error 1))))
5792 (next-level (save-excursion
5793 (condition-case nil
5794 (progn
5795 (or (looking-at outline-regexp)
5796 (outline-next-visible-heading 1))
5797 (if (looking-at re)
5798 (- (match-end 0) (match-beginning 0) 1)
5800 (error 1))))
5801 (new-level (or force-level (max previous-level next-level)))
5802 (shift (if (or (= old-level -1)
5803 (= new-level -1)
5804 (= old-level new-level))
5806 (- new-level old-level)))
5807 (delta (if (> shift 0) -1 1))
5808 (func (if (> shift 0) 'org-demote 'org-promote))
5809 (org-odd-levels-only nil)
5810 beg end newend)
5811 ;; Remove the forced level indicator
5812 (if force-level
5813 (delete-region (point-at-bol) (point)))
5814 ;; Paste
5815 (beginning-of-line 1)
5816 (unless for-yank (org-back-over-empty-lines))
5817 (setq beg (point))
5818 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5819 (insert-before-markers txt)
5820 (unless (string-match "\n\\'" txt) (insert "\n"))
5821 (setq newend (point))
5822 (org-reinstall-markers-in-region beg)
5823 (setq end (point))
5824 (goto-char beg)
5825 (skip-chars-forward " \t\n\r")
5826 (setq beg (point))
5827 (if (and (org-invisible-p) visp)
5828 (save-excursion (outline-show-heading)))
5829 ;; Shift if necessary
5830 (unless (= shift 0)
5831 (save-restriction
5832 (narrow-to-region beg end)
5833 (while (not (= shift 0))
5834 (org-map-region func (point-min) (point-max))
5835 (setq shift (+ delta shift)))
5836 (goto-char (point-min))
5837 (setq newend (point-max))))
5838 (when (or (interactive-p) for-yank)
5839 (message "Clipboard pasted as level %d subtree" new-level))
5840 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5841 kill-ring
5842 (eq org-subtree-clip (current-kill 0))
5843 org-subtree-clip-folded)
5844 ;; The tree was folded before it was killed/copied
5845 (hide-subtree))
5846 (and for-yank (goto-char newend))))
5848 (defun org-kill-is-subtree-p (&optional txt)
5849 "Check if the current kill is an outline subtree, or a set of trees.
5850 Returns nil if kill does not start with a headline, or if the first
5851 headline level is not the largest headline level in the tree.
5852 So this will actually accept several entries of equal levels as well,
5853 which is OK for `org-paste-subtree'.
5854 If optional TXT is given, check this string instead of the current kill."
5855 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5856 (start-level (and kill
5857 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5858 org-outline-regexp "\\)")
5859 kill)
5860 (- (match-end 2) (match-beginning 2) 1)))
5861 (re (concat "^" org-outline-regexp))
5862 (start (1+ (or (match-beginning 2) -1))))
5863 (if (not start-level)
5864 (progn
5865 nil) ;; does not even start with a heading
5866 (catch 'exit
5867 (while (setq start (string-match re kill (1+ start)))
5868 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5869 (throw 'exit nil)))
5870 t))))
5872 (defvar org-markers-to-move nil
5873 "Markers that should be moved with a cut-and-paste operation.
5874 Those markers are stored together with their positions relative to
5875 the start of the region.")
5877 (defun org-save-markers-in-region (beg end)
5878 "Check markers in region.
5879 If these markers are between BEG and END, record their position relative
5880 to BEG, so that after moving the block of text, we can put the markers back
5881 into place.
5882 This function gets called just before an entry or tree gets cut from the
5883 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5884 called immediately, to move the markers with the entries."
5885 (setq org-markers-to-move nil)
5886 (when (featurep 'org-clock)
5887 (org-clock-save-markers-for-cut-and-paste beg end))
5888 (when (featurep 'org-agenda)
5889 (org-agenda-save-markers-for-cut-and-paste beg end)))
5891 (defun org-check-and-save-marker (marker beg end)
5892 "Check if MARKER is between BEG and END.
5893 If yes, remember the marker and the distance to BEG."
5894 (when (and (marker-buffer marker)
5895 (equal (marker-buffer marker) (current-buffer)))
5896 (if (and (>= marker beg) (< marker end))
5897 (push (cons marker (- marker beg)) org-markers-to-move))))
5899 (defun org-reinstall-markers-in-region (beg)
5900 "Move all remembered markers to their position relative to BEG."
5901 (mapc (lambda (x)
5902 (move-marker (car x) (+ beg (cdr x))))
5903 org-markers-to-move)
5904 (setq org-markers-to-move nil))
5906 (defun org-narrow-to-subtree ()
5907 "Narrow buffer to the current subtree."
5908 (interactive)
5909 (save-excursion
5910 (save-match-data
5911 (narrow-to-region
5912 (progn (org-back-to-heading) (point))
5913 (progn (org-end-of-subtree t) (point))))))
5915 (defun org-clone-subtree-with-time-shift (n &optional shift)
5916 "Clone the task (subtree) at point N times.
5917 The clones will be inserted as siblings.
5919 In interactive use, the user will be prompted for the number of clones
5920 to be produced, and for a time SHIFT, which may be a repeater as used
5921 in time stamps, for example `+3d'.
5923 When a valid repeater is given and the entry contains any time stamps,
5924 the clones will become a sequence in time, with time stamps in the
5925 subtree shifted for each clone produced. If SHIFT is nil or the
5926 empty string, time stamps will be left alone.
5928 If the original subtree did contain time stamps with a repeater,
5929 the following will happen:
5930 - the repeater will be removed in each clone
5931 - an additional clone will be produced, with the current, unshifted
5932 date(s) in the entry.
5933 - the original entry will be placed *after* all the clones, with
5934 repeater intact.
5935 - the start days in the repeater in the original entry will be shifted
5936 to past the last clone.
5937 I this way you can spell out a number of instances of a repeating task,
5938 and still retain the repeater to cover future instances of the task."
5939 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
5940 (let (beg end template task
5941 shift-n shift-what doshift nmin nmax (n-no-remove -1))
5942 (if (not (and (integerp n) (> n 0)))
5943 (error "Invalid number of replications %s" n))
5944 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
5945 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
5946 shift)))
5947 (error "Invalid shift specification %s" shift))
5948 (when doshift
5949 (setq shift-n (string-to-number (match-string 1 shift))
5950 shift-what (cdr (assoc (match-string 2 shift)
5951 '(("d" . day) ("w" . week)
5952 ("m" . month) ("y" . year))))))
5953 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
5954 (setq nmin 1 nmax n)
5955 (org-back-to-heading t)
5956 (setq beg (point))
5957 (org-end-of-subtree t t)
5958 (setq end (point))
5959 (setq template (buffer-substring beg end))
5960 (when (and doshift
5961 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
5962 (delete-region beg end)
5963 (setq end beg)
5964 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
5965 (goto-char end)
5966 (loop for n from nmin to nmax do
5967 (if (not doshift)
5968 (setq task template)
5969 (with-temp-buffer
5970 (insert template)
5971 (org-mode)
5972 (goto-char (point-min))
5973 (while (re-search-forward org-ts-regexp nil t)
5974 (org-timestamp-change (* n shift-n) shift-what))
5975 (unless (= n n-no-remove)
5976 (goto-char (point-min))
5977 (while (re-search-forward org-ts-regexp nil t)
5978 (save-excursion
5979 (goto-char (match-beginning 0))
5980 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
5981 (delete-region (match-beginning 1) (match-end 1))))))
5982 (setq task (buffer-string))))
5983 (insert task))
5984 (goto-char beg)))
5986 ;;; Outline Sorting
5988 (defun org-sort (with-case)
5989 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5990 Optional argument WITH-CASE means sort case-sensitively.
5991 With a double prefix argument, also remove duplicate entries."
5992 (interactive "P")
5993 (if (org-at-table-p)
5994 (org-call-with-arg 'org-table-sort-lines with-case)
5995 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5997 (defun org-sort-remove-invisible (s)
5998 (remove-text-properties 0 (length s) org-rm-props s)
5999 (while (string-match org-bracket-link-regexp s)
6000 (setq s (replace-match (if (match-end 2)
6001 (match-string 3 s)
6002 (match-string 1 s)) t t s)))
6005 (defvar org-priority-regexp) ; defined later in the file
6007 (defun org-sort-entries-or-items
6008 (&optional with-case sorting-type getkey-func compare-func property)
6009 "Sort entries on a certain level of an outline tree.
6010 If there is an active region, the entries in the region are sorted.
6011 Else, if the cursor is before the first entry, sort the top-level items.
6012 Else, the children of the entry at point are sorted.
6014 Sorting can be alphabetically, numerically, and by date/time as given by
6015 the first time stamp in the entry. The command prompts for the sorting
6016 type unless it has been given to the function through the SORTING-TYPE
6017 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6018 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6019 called with point at the beginning of the record. It must return either
6020 a string or a number that should serve as the sorting key for that record.
6022 Comparing entries ignores case by default. However, with an optional argument
6023 WITH-CASE, the sorting considers case as well."
6024 (interactive "P")
6025 (let ((case-func (if with-case 'identity 'downcase))
6026 start beg end stars re re2
6027 txt what tmp plain-list-p)
6028 ;; Find beginning and end of region to sort
6029 (cond
6030 ((org-region-active-p)
6031 ;; we will sort the region
6032 (setq end (region-end)
6033 what "region")
6034 (goto-char (region-beginning))
6035 (if (not (org-on-heading-p)) (outline-next-heading))
6036 (setq start (point)))
6037 ((org-at-item-p)
6038 ;; we will sort this plain list
6039 (org-beginning-of-item-list) (setq start (point))
6040 (org-end-of-item-list) (setq end (point))
6041 (goto-char start)
6042 (setq plain-list-p t
6043 what "plain list"))
6044 ((or (org-on-heading-p)
6045 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6046 ;; we will sort the children of the current headline
6047 (org-back-to-heading)
6048 (setq start (point)
6049 end (progn (org-end-of-subtree t t)
6050 (org-back-over-empty-lines)
6051 (point))
6052 what "children")
6053 (goto-char start)
6054 (show-subtree)
6055 (outline-next-heading))
6057 ;; we will sort the top-level entries in this file
6058 (goto-char (point-min))
6059 (or (org-on-heading-p) (outline-next-heading))
6060 (setq start (point) end (point-max) what "top-level")
6061 (goto-char start)
6062 (show-all)))
6064 (setq beg (point))
6065 (if (>= beg end) (error "Nothing to sort"))
6067 (unless plain-list-p
6068 (looking-at "\\(\\*+\\)")
6069 (setq stars (match-string 1)
6070 re (concat "^" (regexp-quote stars) " +")
6071 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6072 txt (buffer-substring beg end))
6073 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6074 (if (and (not (equal stars "*")) (string-match re2 txt))
6075 (error "Region to sort contains a level above the first entry")))
6077 (unless sorting-type
6078 (message
6079 (if plain-list-p
6080 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6081 "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:")
6082 what)
6083 (setq sorting-type (read-char-exclusive))
6085 (and (= (downcase sorting-type) ?f)
6086 (setq getkey-func
6087 (org-ido-completing-read "Sort using function: "
6088 obarray 'fboundp t nil nil))
6089 (setq getkey-func (intern getkey-func)))
6091 (and (= (downcase sorting-type) ?r)
6092 (setq property
6093 (org-ido-completing-read "Property: "
6094 (mapcar 'list (org-buffer-property-keys t))
6095 nil t))))
6097 (message "Sorting entries...")
6099 (save-restriction
6100 (narrow-to-region start end)
6102 (let ((dcst (downcase sorting-type))
6103 (now (current-time)))
6104 (sort-subr
6105 (/= dcst sorting-type)
6106 ;; This function moves to the beginning character of the "record" to
6107 ;; be sorted.
6108 (if plain-list-p
6109 (lambda nil
6110 (if (org-at-item-p) t (goto-char (point-max))))
6111 (lambda nil
6112 (if (re-search-forward re nil t)
6113 (goto-char (match-beginning 0))
6114 (goto-char (point-max)))))
6115 ;; This function moves to the last character of the "record" being
6116 ;; sorted.
6117 (if plain-list-p
6118 'org-end-of-item
6119 (lambda nil
6120 (save-match-data
6121 (condition-case nil
6122 (outline-forward-same-level 1)
6123 (error
6124 (goto-char (point-max)))))))
6126 ;; This function returns the value that gets sorted against.
6127 (if plain-list-p
6128 (lambda nil
6129 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6130 (cond
6131 ((= dcst ?n)
6132 (string-to-number (buffer-substring (match-end 0)
6133 (point-at-eol))))
6134 ((= dcst ?a)
6135 (buffer-substring (match-end 0) (point-at-eol)))
6136 ((= dcst ?t)
6137 (if (re-search-forward org-ts-regexp
6138 (point-at-eol) t)
6139 (org-time-string-to-time (match-string 0))
6140 now))
6141 ((= dcst ?f)
6142 (if getkey-func
6143 (progn
6144 (setq tmp (funcall getkey-func))
6145 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6146 tmp)
6147 (error "Invalid key function `%s'" getkey-func)))
6148 (t (error "Invalid sorting type `%c'" sorting-type)))))
6149 (lambda nil
6150 (cond
6151 ((= dcst ?n)
6152 (if (looking-at org-complex-heading-regexp)
6153 (string-to-number (match-string 4))
6154 nil))
6155 ((= dcst ?a)
6156 (if (looking-at org-complex-heading-regexp)
6157 (funcall case-func (match-string 4))
6158 nil))
6159 ((= dcst ?t)
6160 (if (re-search-forward org-ts-regexp
6161 (save-excursion
6162 (forward-line 2)
6163 (point)) t)
6164 (org-time-string-to-time (match-string 0))
6165 now))
6166 ((= dcst ?p)
6167 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6168 (string-to-char (match-string 2))
6169 org-default-priority))
6170 ((= dcst ?r)
6171 (or (org-entry-get nil property) ""))
6172 ((= dcst ?o)
6173 (if (looking-at org-complex-heading-regexp)
6174 (- 9999 (length (member (match-string 2)
6175 org-todo-keywords-1)))))
6176 ((= dcst ?f)
6177 (if getkey-func
6178 (progn
6179 (setq tmp (funcall getkey-func))
6180 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6181 tmp)
6182 (error "Invalid key function `%s'" getkey-func)))
6183 (t (error "Invalid sorting type `%c'" sorting-type)))))
6185 (cond
6186 ((= dcst ?a) 'string<)
6187 ((= dcst ?t) 'time-less-p)
6188 ((= dcst ?f) compare-func)
6189 (t nil)))))
6190 (message "Sorting entries...done")))
6192 (defun org-do-sort (table what &optional with-case sorting-type)
6193 "Sort TABLE of WHAT according to SORTING-TYPE.
6194 The user will be prompted for the SORTING-TYPE if the call to this
6195 function does not specify it. WHAT is only for the prompt, to indicate
6196 what is being sorted. The sorting key will be extracted from
6197 the car of the elements of the table.
6198 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6199 (unless sorting-type
6200 (message
6201 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6202 what)
6203 (setq sorting-type (read-char-exclusive)))
6204 (let ((dcst (downcase sorting-type))
6205 extractfun comparefun)
6206 ;; Define the appropriate functions
6207 (cond
6208 ((= dcst ?n)
6209 (setq extractfun 'string-to-number
6210 comparefun (if (= dcst sorting-type) '< '>)))
6211 ((= dcst ?a)
6212 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6213 (lambda(x) (downcase (org-sort-remove-invisible x))))
6214 comparefun (if (= dcst sorting-type)
6215 'string<
6216 (lambda (a b) (and (not (string< a b))
6217 (not (string= a b)))))))
6218 ((= dcst ?t)
6219 (setq extractfun
6220 (lambda (x)
6221 (if (or (string-match org-ts-regexp x)
6222 (string-match org-ts-regexp-both x))
6223 (time-to-seconds
6224 (org-time-string-to-time (match-string 0 x)))
6226 comparefun (if (= dcst sorting-type) '< '>)))
6227 (t (error "Invalid sorting type `%c'" sorting-type)))
6229 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6230 table)
6231 (lambda (a b) (funcall comparefun (car a) (car b))))))
6233 ;;; Editing source examples
6235 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6236 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6237 (defvar org-edit-src-force-single-line nil)
6238 (defvar org-edit-src-from-org-mode nil)
6239 (defvar org-edit-src-picture nil)
6241 (define-minor-mode org-exit-edit-mode
6242 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6244 (defun org-edit-src-code ()
6245 "Edit the source code example at point.
6246 An indirect buffer is created, and that buffer is then narrowed to the
6247 example at point and switched to the correct language mode. When done,
6248 exit by killing the buffer with \\[org-edit-src-exit]."
6249 (interactive)
6250 (let ((line (org-current-line))
6251 (case-fold-search t)
6252 (msg (substitute-command-keys
6253 "Edit, then exit with C-c ' (C-c and single quote)"))
6254 (info (org-edit-src-find-region-and-lang))
6255 (org-mode-p (eq major-mode 'org-mode))
6256 beg end lang lang-f single lfmt)
6257 (if (not info)
6259 (setq beg (nth 0 info)
6260 end (nth 1 info)
6261 lang (nth 2 info)
6262 single (nth 3 info)
6263 lfmt (nth 4 info)
6264 lang-f (intern (concat lang "-mode")))
6265 (unless (functionp lang-f)
6266 (error "No such language mode: %s" lang-f))
6267 (goto-line line)
6268 (if (get-buffer "*Org Edit Src Example*")
6269 (kill-buffer "*Org Edit Src Example*"))
6270 (switch-to-buffer (make-indirect-buffer (current-buffer)
6271 "*Org Edit Src Example*"))
6272 (narrow-to-region beg end)
6273 (remove-text-properties beg end '(display nil invisible nil
6274 intangible nil))
6275 (let ((org-inhibit-startup t))
6276 (funcall lang-f))
6277 (set (make-local-variable 'org-edit-src-force-single-line) single)
6278 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6279 (when lfmt
6280 (set (make-local-variable 'org-coderef-label-format) lfmt))
6281 (when org-mode-p
6282 (goto-char (point-min))
6283 (while (re-search-forward "^," nil t)
6284 (replace-match "")))
6285 (goto-line line)
6286 (org-exit-edit-mode)
6287 (org-set-local 'header-line-format msg)
6288 (message "%s" msg)
6289 t)))
6291 (defun org-edit-fixed-width-region ()
6292 "Edit the fixed-width ascii drawing at point.
6293 This must be a region where each line starts with a colon followed by
6294 a space character.
6295 An indirect buffer is created, and that buffer is then narrowed to the
6296 example at point and switched to artist-mode. When done,
6297 exit by killing the buffer with \\[org-edit-src-exit]."
6298 (interactive)
6299 (let ((line (org-current-line))
6300 (case-fold-search t)
6301 (msg (substitute-command-keys
6302 "Edit, then exit with C-c ' (C-c and single quote)"))
6303 (org-mode-p (eq major-mode 'org-mode))
6304 beg end)
6305 (beginning-of-line 1)
6306 (if (looking-at "[ \t]*[^:\n \t]")
6308 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6309 (setq beg (point) end beg)
6310 (save-excursion
6311 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6312 (setq beg (point-at-bol 2))
6313 (setq beg (point))))
6314 (save-excursion
6315 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6316 (setq end (1- (match-beginning 0)))
6317 (setq end (point))))
6318 (goto-line line))
6319 (if (get-buffer "*Org Edit Picture*")
6320 (kill-buffer "*Org Edit Picture*"))
6321 (switch-to-buffer (make-indirect-buffer (current-buffer)
6322 "*Org Edit Picture*"))
6323 (narrow-to-region beg end)
6324 (remove-text-properties beg end '(display nil invisible nil
6325 intangible nil))
6326 (when (fboundp 'font-lock-unfontify-region)
6327 (font-lock-unfontify-region (point-min) (point-max)))
6328 (cond
6329 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6330 (fundamental-mode)
6331 (artist-mode 1))
6332 (t (funcall org-edit-fixed-width-region-mode)))
6333 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6334 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6335 (set (make-local-variable 'org-edit-src-picture) t)
6336 (goto-char (point-min))
6337 (while (re-search-forward "^[ \t]*: ?" nil t)
6338 (replace-match ""))
6339 (goto-line line)
6340 (org-exit-edit-mode)
6341 (org-set-local 'header-line-format msg)
6342 (message "%s" msg)
6343 t)))
6346 (defun org-edit-src-find-region-and-lang ()
6347 "Find the region and language for a local edit.
6348 Return a list with beginning and end of the region, a string representing
6349 the language, a switch telling of the content should be in a single line."
6350 (let ((re-list
6351 (append
6352 org-edit-src-region-extra
6354 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6355 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6356 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6357 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6358 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6359 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6360 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6361 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6362 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6363 ("^#\\+html:" "\n" "html" single-line)
6364 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6365 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6366 ("^#\\+latex:" "\n" "latex" single-line)
6367 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6368 ("^#\\+ascii:" "\n" "ascii" single-line)
6370 (pos (point))
6371 re1 re2 single beg end lang lfmt match-re1)
6372 (catch 'exit
6373 (while (setq entry (pop re-list))
6374 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6375 single (nth 3 entry))
6376 (save-excursion
6377 (if (or (looking-at re1)
6378 (re-search-backward re1 nil t))
6379 (progn
6380 (setq match-re1 (match-string 0))
6381 (setq beg (match-end 0)
6382 lang (org-edit-src-get-lang lang)
6383 lfmt (org-edit-src-get-label-format match-re1))
6384 (if (and (re-search-forward re2 nil t)
6385 (>= (match-end 0) pos))
6386 (throw 'exit (list beg (match-beginning 0)
6387 lang single lfmt))))
6388 (if (or (looking-at re2)
6389 (re-search-forward re2 nil t))
6390 (progn
6391 (setq end (match-beginning 0))
6392 (if (and (re-search-backward re1 nil t)
6393 (<= (match-beginning 0) pos))
6394 (progn
6395 (setq lfmt (org-edit-src-get-label-format
6396 (match-string 0)))
6397 (throw 'exit
6398 (list (match-end 0) end
6399 (org-edit-src-get-lang lang)
6400 single lfmt))))))))))))
6402 (defun org-edit-src-get-lang (lang)
6403 "Extract the src language."
6404 (let ((m (match-string 0)))
6405 (cond
6406 ((stringp lang) lang)
6407 ((integerp lang) (match-string lang))
6408 ((and (eq lang 'lang)
6409 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6410 (match-string 1 m))
6411 ((and (eq lang 'style)
6412 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6413 (match-string 1 m))
6414 (t "fundamental"))))
6416 (defun org-edit-src-get-label-format (s)
6417 "Extract the label format."
6418 (save-match-data
6419 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6420 (match-string 1 s))))
6422 (defun org-edit-src-exit ()
6423 "Exit special edit and protect problematic lines."
6424 (interactive)
6425 (unless (buffer-base-buffer (current-buffer))
6426 (error "This is not an indirect buffer, something is wrong..."))
6427 (unless (> (point-min) 1)
6428 (error "This buffer is not narrowed, something is wrong..."))
6429 (goto-char (point-min))
6430 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6431 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6432 (when (org-bound-and-true-p org-edit-src-force-single-line)
6433 (goto-char (point-min))
6434 (while (re-search-forward "\n" nil t)
6435 (replace-match " "))
6436 (goto-char (point-min))
6437 (if (looking-at "\\s-*") (replace-match " "))
6438 (if (re-search-forward "\\s-+\\'" nil t)
6439 (replace-match "")))
6440 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6441 (goto-char (point-min))
6442 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6443 (replace-match ",\\1"))
6444 (when font-lock-mode
6445 (font-lock-unfontify-region (point-min) (point-max)))
6446 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6447 (when (org-bound-and-true-p org-edit-src-picture)
6448 (untabify (point-min) (point-max))
6449 (goto-char (point-min))
6450 (while (re-search-forward "^" nil t)
6451 (replace-match ": "))
6452 (when font-lock-mode
6453 (font-lock-unfontify-region (point-min) (point-max)))
6454 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6455 (kill-buffer (current-buffer))
6456 (and (org-mode-p) (org-restart-font-lock)))
6459 ;;; The orgstruct minor mode
6461 ;; Define a minor mode which can be used in other modes in order to
6462 ;; integrate the org-mode structure editing commands.
6464 ;; This is really a hack, because the org-mode structure commands use
6465 ;; keys which normally belong to the major mode. Here is how it
6466 ;; works: The minor mode defines all the keys necessary to operate the
6467 ;; structure commands, but wraps the commands into a function which
6468 ;; tests if the cursor is currently at a headline or a plain list
6469 ;; item. If that is the case, the structure command is used,
6470 ;; temporarily setting many Org-mode variables like regular
6471 ;; expressions for filling etc. However, when any of those keys is
6472 ;; used at a different location, function uses `key-binding' to look
6473 ;; up if the key has an associated command in another currently active
6474 ;; keymap (minor modes, major mode, global), and executes that
6475 ;; command. There might be problems if any of the keys is otherwise
6476 ;; used as a prefix key.
6478 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6479 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6480 ;; addresses this by checking explicitly for both bindings.
6482 (defvar orgstruct-mode-map (make-sparse-keymap)
6483 "Keymap for the minor `orgstruct-mode'.")
6485 (defvar org-local-vars nil
6486 "List of local variables, for use by `orgstruct-mode'")
6488 ;;;###autoload
6489 (define-minor-mode orgstruct-mode
6490 "Toggle the minor more `orgstruct-mode'.
6491 This mode is for using Org-mode structure commands in other modes.
6492 The following key behave as if Org-mode was active, if the cursor
6493 is on a headline, or on a plain list item (both in the definition
6494 of Org-mode).
6496 M-up Move entry/item up
6497 M-down Move entry/item down
6498 M-left Promote
6499 M-right Demote
6500 M-S-up Move entry/item up
6501 M-S-down Move entry/item down
6502 M-S-left Promote subtree
6503 M-S-right Demote subtree
6504 M-q Fill paragraph and items like in Org-mode
6505 C-c ^ Sort entries
6506 C-c - Cycle list bullet
6507 TAB Cycle item visibility
6508 M-RET Insert new heading/item
6509 S-M-RET Insert new TODO heading / Checkbox item
6510 C-c C-c Set tags / toggle checkbox"
6511 nil " OrgStruct" nil
6512 (org-load-modules-maybe)
6513 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6515 ;;;###autoload
6516 (defun turn-on-orgstruct ()
6517 "Unconditionally turn on `orgstruct-mode'."
6518 (orgstruct-mode 1))
6520 (defun orgstruct++-mode (&optional arg)
6521 "Toggle `orgstruct-mode', the enhanced version of it.
6522 In addition to setting orgstruct-mode, this also exports all indentation and
6523 autofilling variables from org-mode into the buffer. It will also
6524 recognize item context in multiline items.
6525 Note that turning off orgstruct-mode will *not* remove the
6526 indentation/paragraph settings. This can only be done by refreshing the
6527 major mode, for example with \[normal-mode]."
6528 (interactive "P")
6529 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6530 (if (< arg 1)
6531 (orgstruct-mode -1)
6532 (orgstruct-mode 1)
6533 (let (var val)
6534 (mapc
6535 (lambda (x)
6536 (when (string-match
6537 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6538 (symbol-name (car x)))
6539 (setq var (car x) val (nth 1 x))
6540 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6541 org-local-vars)
6542 (org-set-local 'orgstruct-is-++ t))))
6544 (defvar orgstruct-is-++ nil
6545 "Is orgstruct-mode in ++ version in the current-buffer?")
6546 (make-variable-buffer-local 'orgstruct-is-++)
6548 ;;;###autoload
6549 (defun turn-on-orgstruct++ ()
6550 "Unconditionally turn on `orgstruct++-mode'."
6551 (orgstruct++-mode 1))
6553 (defun orgstruct-error ()
6554 "Error when there is no default binding for a structure key."
6555 (interactive)
6556 (error "This key has no function outside structure elements"))
6558 (defun orgstruct-setup ()
6559 "Setup orgstruct keymaps."
6560 (let ((nfunc 0)
6561 (bindings
6562 (list
6563 '([(meta up)] org-metaup)
6564 '([(meta down)] org-metadown)
6565 '([(meta left)] org-metaleft)
6566 '([(meta right)] org-metaright)
6567 '([(meta shift up)] org-shiftmetaup)
6568 '([(meta shift down)] org-shiftmetadown)
6569 '([(meta shift left)] org-shiftmetaleft)
6570 '([(meta shift right)] org-shiftmetaright)
6571 '([(shift up)] org-shiftup)
6572 '([(shift down)] org-shiftdown)
6573 '([(shift left)] org-shiftleft)
6574 '([(shift right)] org-shiftright)
6575 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6576 '("\M-q" fill-paragraph)
6577 '("\C-c^" org-sort)
6578 '("\C-c-" org-cycle-list-bullet)))
6579 elt key fun cmd)
6580 (while (setq elt (pop bindings))
6581 (setq nfunc (1+ nfunc))
6582 (setq key (org-key (car elt))
6583 fun (nth 1 elt)
6584 cmd (orgstruct-make-binding fun nfunc key))
6585 (org-defkey orgstruct-mode-map key cmd))
6587 ;; Special treatment needed for TAB and RET
6588 (org-defkey orgstruct-mode-map [(tab)]
6589 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6590 (org-defkey orgstruct-mode-map "\C-i"
6591 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6593 (org-defkey orgstruct-mode-map "\M-\C-m"
6594 (orgstruct-make-binding 'org-insert-heading 105
6595 "\M-\C-m" [(meta return)]))
6596 (org-defkey orgstruct-mode-map [(meta return)]
6597 (orgstruct-make-binding 'org-insert-heading 106
6598 [(meta return)] "\M-\C-m"))
6600 (org-defkey orgstruct-mode-map [(shift meta return)]
6601 (orgstruct-make-binding 'org-insert-todo-heading 107
6602 [(meta return)] "\M-\C-m"))
6604 (unless org-local-vars
6605 (setq org-local-vars (org-get-local-variables)))
6609 (defun orgstruct-make-binding (fun n &rest keys)
6610 "Create a function for binding in the structure minor mode.
6611 FUN is the command to call inside a table. N is used to create a unique
6612 command name. KEYS are keys that should be checked in for a command
6613 to execute outside of tables."
6614 (eval
6615 (list 'defun
6616 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6617 '(arg)
6618 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6619 "Outside of structure, run the binding of `"
6620 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6621 "'.")
6622 '(interactive "p")
6623 (list 'if
6624 `(org-context-p 'headline 'item
6625 (and orgstruct-is-++
6626 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6627 'item-body))
6628 (list 'org-run-like-in-org-mode (list 'quote fun))
6629 (list 'let '(orgstruct-mode)
6630 (list 'call-interactively
6631 (append '(or)
6632 (mapcar (lambda (k)
6633 (list 'key-binding k))
6634 keys)
6635 '('orgstruct-error))))))))
6637 (defun org-context-p (&rest contexts)
6638 "Check if local context is any of CONTEXTS.
6639 Possible values in the list of contexts are `table', `headline', and `item'."
6640 (let ((pos (point)))
6641 (goto-char (point-at-bol))
6642 (prog1 (or (and (memq 'table contexts)
6643 (looking-at "[ \t]*|"))
6644 (and (memq 'headline contexts)
6645 ;;????????? (looking-at "\\*+"))
6646 (looking-at outline-regexp))
6647 (and (memq 'item contexts)
6648 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6649 (and (memq 'item-body contexts)
6650 (org-in-item-p)))
6651 (goto-char pos))))
6653 (defun org-get-local-variables ()
6654 "Return a list of all local variables in an org-mode buffer."
6655 (let (varlist)
6656 (with-current-buffer (get-buffer-create "*Org tmp*")
6657 (erase-buffer)
6658 (org-mode)
6659 (setq varlist (buffer-local-variables)))
6660 (kill-buffer "*Org tmp*")
6661 (delq nil
6662 (mapcar
6663 (lambda (x)
6664 (setq x
6665 (if (symbolp x)
6666 (list x)
6667 (list (car x) (list 'quote (cdr x)))))
6668 (if (string-match
6669 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6670 (symbol-name (car x)))
6671 x nil))
6672 varlist))))
6674 ;;;###autoload
6675 (defun org-run-like-in-org-mode (cmd)
6676 "Run a command, pretending that the current buffer is in Org-mode.
6677 This will temporarily bind local variables that are typically bound in
6678 Org-mode to the values they have in Org-mode, and then interactively
6679 call CMD."
6680 (org-load-modules-maybe)
6681 (unless org-local-vars
6682 (setq org-local-vars (org-get-local-variables)))
6683 (eval (list 'let org-local-vars
6684 (list 'call-interactively (list 'quote cmd)))))
6686 ;;;; Archiving
6688 (defun org-get-category (&optional pos)
6689 "Get the category applying to position POS."
6690 (get-text-property (or pos (point)) 'org-category))
6692 (defun org-refresh-category-properties ()
6693 "Refresh category text properties in the buffer."
6694 (let ((def-cat (cond
6695 ((null org-category)
6696 (if buffer-file-name
6697 (file-name-sans-extension
6698 (file-name-nondirectory buffer-file-name))
6699 "???"))
6700 ((symbolp org-category) (symbol-name org-category))
6701 (t org-category)))
6702 beg end cat pos optionp)
6703 (org-unmodified
6704 (save-excursion
6705 (save-restriction
6706 (widen)
6707 (goto-char (point-min))
6708 (put-text-property (point) (point-max) 'org-category def-cat)
6709 (while (re-search-forward
6710 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6711 (setq pos (match-end 0)
6712 optionp (equal (char-after (match-beginning 0)) ?#)
6713 cat (org-trim (match-string 2)))
6714 (if optionp
6715 (setq beg (point-at-bol) end (point-max))
6716 (org-back-to-heading t)
6717 (setq beg (point) end (org-end-of-subtree t t)))
6718 (put-text-property beg end 'org-category cat)
6719 (goto-char pos)))))))
6722 ;;;; Link Stuff
6724 ;;; Link abbreviations
6726 (defun org-link-expand-abbrev (link)
6727 "Apply replacements as defined in `org-link-abbrev-alist."
6728 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6729 (let* ((key (match-string 1 link))
6730 (as (or (assoc key org-link-abbrev-alist-local)
6731 (assoc key org-link-abbrev-alist)))
6732 (tag (and (match-end 2) (match-string 3 link)))
6733 rpl)
6734 (if (not as)
6735 link
6736 (setq rpl (cdr as))
6737 (cond
6738 ((symbolp rpl) (funcall rpl tag))
6739 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6740 ((string-match "%h" rpl)
6741 (replace-match (url-hexify-string (or tag "")) t t rpl))
6742 (t (concat rpl tag)))))
6743 link))
6745 ;;; Storing and inserting links
6747 (defvar org-insert-link-history nil
6748 "Minibuffer history for links inserted with `org-insert-link'.")
6750 (defvar org-stored-links nil
6751 "Contains the links stored with `org-store-link'.")
6753 (defvar org-store-link-plist nil
6754 "Plist with info about the most recently link created with `org-store-link'.")
6756 (defvar org-link-protocols nil
6757 "Link protocols added to Org-mode using `org-add-link-type'.")
6759 (defvar org-store-link-functions nil
6760 "List of functions that are called to create and store a link.
6761 Each function will be called in turn until one returns a non-nil
6762 value. Each function should check if it is responsible for creating
6763 this link (for example by looking at the major mode).
6764 If not, it must exit and return nil.
6765 If yes, it should return a non-nil value after a calling
6766 `org-store-link-props' with a list of properties and values.
6767 Special properties are:
6769 :type The link prefix. like \"http\". This must be given.
6770 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6771 This is obligatory as well.
6772 :description Optional default description for the second pair
6773 of brackets in an Org-mode link. The user can still change
6774 this when inserting this link into an Org-mode buffer.
6776 In addition to these, any additional properties can be specified
6777 and then used in remember templates.")
6779 (defun org-add-link-type (type &optional follow export)
6780 "Add TYPE to the list of `org-link-types'.
6781 Re-compute all regular expressions depending on `org-link-types'
6783 FOLLOW and EXPORT are two functions.
6785 FOLLOW should take the link path as the single argument and do whatever
6786 is necessary to follow the link, for example find a file or display
6787 a mail message.
6789 EXPORT should format the link path for export to one of the export formats.
6790 It should be a function accepting three arguments:
6792 path the path of the link, the text after the prefix (like \"http:\")
6793 desc the description of the link, if any, nil if there was no description
6794 format the export format, a symbol like `html' or `latex'.
6796 The function may use the FORMAT information to return different values
6797 depending on the format. The return value will be put literally into
6798 the exported file.
6799 Org-mode has a built-in default for exporting links. If you are happy with
6800 this default, there is no need to define an export function for the link
6801 type. For a simple example of an export function, see `org-bbdb.el'."
6802 (add-to-list 'org-link-types type t)
6803 (org-make-link-regexps)
6804 (if (assoc type org-link-protocols)
6805 (setcdr (assoc type org-link-protocols) (list follow export))
6806 (push (list type follow export) org-link-protocols)))
6808 ;;;###autoload
6809 (defun org-store-link (arg)
6810 "\\<org-mode-map>Store an org-link to the current location.
6811 This link is added to `org-stored-links' and can later be inserted
6812 into an org-buffer with \\[org-insert-link].
6814 For some link types, a prefix arg is interpreted:
6815 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6816 For file links, arg negates `org-context-in-file-links'."
6817 (interactive "P")
6818 (org-load-modules-maybe)
6819 (setq org-store-link-plist nil) ; reset
6820 (let (link cpltxt desc description search txt)
6821 (cond
6823 ((run-hook-with-args-until-success 'org-store-link-functions)
6824 (setq link (plist-get org-store-link-plist :link)
6825 desc (or (plist-get org-store-link-plist :description) link)))
6827 ((equal (buffer-name) "*Org Edit Src Example*")
6828 (let (label gc)
6829 (while (or (not label)
6830 (save-excursion
6831 (save-restriction
6832 (widen)
6833 (goto-char (point-min))
6834 (re-search-forward
6835 (regexp-quote (format org-coderef-label-format label))
6836 nil t))))
6837 (when label (message "Label exists already") (sit-for 2))
6838 (setq label (read-string "Code line label: " label)))
6839 (end-of-line 1)
6840 (setq link (format org-coderef-label-format label))
6841 (setq gc (- 79 (length link)))
6842 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6843 (insert link)
6844 (setq link (concat "(" label ")") desc nil)))
6846 ((eq major-mode 'calendar-mode)
6847 (let ((cd (calendar-cursor-to-date)))
6848 (setq link
6849 (format-time-string
6850 (car org-time-stamp-formats)
6851 (apply 'encode-time
6852 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6853 nil nil nil))))
6854 (org-store-link-props :type "calendar" :date cd)))
6856 ((eq major-mode 'w3-mode)
6857 (setq cpltxt (if (and (buffer-name)
6858 (not (string-match "Untitled" (buffer-name))))
6859 (buffer-name)
6860 (url-view-url t))
6861 link (org-make-link (url-view-url t)))
6862 (org-store-link-props :type "w3" :url (url-view-url t)))
6864 ((eq major-mode 'w3m-mode)
6865 (setq cpltxt (or w3m-current-title w3m-current-url)
6866 link (org-make-link w3m-current-url))
6867 (org-store-link-props :type "w3m" :url (url-view-url t)))
6869 ((setq search (run-hook-with-args-until-success
6870 'org-create-file-search-functions))
6871 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6872 "::" search))
6873 (setq cpltxt (or description link)))
6875 ((eq major-mode 'image-mode)
6876 (setq cpltxt (concat "file:"
6877 (abbreviate-file-name buffer-file-name))
6878 link (org-make-link cpltxt))
6879 (org-store-link-props :type "image" :file buffer-file-name))
6881 ((eq major-mode 'dired-mode)
6882 ;; link to the file in the current line
6883 (setq cpltxt (concat "file:"
6884 (abbreviate-file-name
6885 (expand-file-name
6886 (dired-get-filename nil t))))
6887 link (org-make-link cpltxt)))
6889 ((and buffer-file-name (org-mode-p))
6890 (cond
6891 ((org-in-regexp "<<\\(.*?\\)>>")
6892 (setq cpltxt
6893 (concat "file:"
6894 (abbreviate-file-name buffer-file-name)
6895 "::" (match-string 1))
6896 link (org-make-link cpltxt)))
6897 ((and (featurep 'org-id)
6898 (or (eq org-link-to-org-use-id t)
6899 (and (eq org-link-to-org-use-id 'create-if-interactive)
6900 (interactive-p))
6901 (and org-link-to-org-use-id
6902 (condition-case nil
6903 (org-entry-get nil "ID")
6904 (error nil)))))
6905 ;; We can make a link using the ID.
6906 (setq link (condition-case nil
6907 (prog1 (org-id-store-link)
6908 (setq desc (plist-get org-store-link-plist
6909 :description)))
6910 (error
6911 ;; probably before first headline, link to file only
6912 (concat "file:"
6913 (abbreviate-file-name buffer-file-name))))))
6915 ;; Just link to current headline
6916 (setq cpltxt (concat "file:"
6917 (abbreviate-file-name buffer-file-name)))
6918 ;; Add a context search string
6919 (when (org-xor org-context-in-file-links arg)
6920 (setq txt (cond
6921 ((org-on-heading-p) nil)
6922 ((org-region-active-p)
6923 (buffer-substring (region-beginning) (region-end)))
6924 (t nil)))
6925 (when (or (null txt) (string-match "\\S-" txt))
6926 (setq cpltxt
6927 (concat cpltxt "::"
6928 (condition-case nil
6929 (org-make-org-heading-search-string txt)
6930 (error "")))
6931 desc "NONE")))
6932 (if (string-match "::\\'" cpltxt)
6933 (setq cpltxt (substring cpltxt 0 -2)))
6934 (setq link (org-make-link cpltxt)))))
6936 ((buffer-file-name (buffer-base-buffer))
6937 ;; Just link to this file here.
6938 (setq cpltxt (concat "file:"
6939 (abbreviate-file-name
6940 (buffer-file-name (buffer-base-buffer)))))
6941 ;; Add a context string
6942 (when (org-xor org-context-in-file-links arg)
6943 (setq txt (if (org-region-active-p)
6944 (buffer-substring (region-beginning) (region-end))
6945 (buffer-substring (point-at-bol) (point-at-eol))))
6946 ;; Only use search option if there is some text.
6947 (when (string-match "\\S-" txt)
6948 (setq cpltxt
6949 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6950 desc "NONE")))
6951 (setq link (org-make-link cpltxt)))
6953 ((interactive-p)
6954 (error "Cannot link to a buffer which is not visiting a file"))
6956 (t (setq link nil)))
6958 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6959 (setq link (or link cpltxt)
6960 desc (or desc cpltxt))
6961 (if (equal desc "NONE") (setq desc nil))
6963 (if (and (interactive-p) link)
6964 (progn
6965 (setq org-stored-links
6966 (cons (list link desc) org-stored-links))
6967 (message "Stored: %s" (or desc link)))
6968 (and link (org-make-link-string link desc)))))
6970 (defun org-store-link-props (&rest plist)
6971 "Store link properties, extract names and addresses."
6972 (let (x adr)
6973 (when (setq x (plist-get plist :from))
6974 (setq adr (mail-extract-address-components x))
6975 (setq plist (plist-put plist :fromname (car adr)))
6976 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6977 (when (setq x (plist-get plist :to))
6978 (setq adr (mail-extract-address-components x))
6979 (setq plist (plist-put plist :toname (car adr)))
6980 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6981 (let ((from (plist-get plist :from))
6982 (to (plist-get plist :to)))
6983 (when (and from to org-from-is-user-regexp)
6984 (setq plist
6985 (plist-put plist :fromto
6986 (if (string-match org-from-is-user-regexp from)
6987 (concat "to %t")
6988 (concat "from %f"))))))
6989 (setq org-store-link-plist plist))
6991 (defun org-add-link-props (&rest plist)
6992 "Add these properties to the link property list."
6993 (let (key value)
6994 (while plist
6995 (setq key (pop plist) value (pop plist))
6996 (setq org-store-link-plist
6997 (plist-put org-store-link-plist key value)))))
6999 (defun org-email-link-description (&optional fmt)
7000 "Return the description part of an email link.
7001 This takes information from `org-store-link-plist' and formats it
7002 according to FMT (default from `org-email-link-description-format')."
7003 (setq fmt (or fmt org-email-link-description-format))
7004 (let* ((p org-store-link-plist)
7005 (to (plist-get p :toaddress))
7006 (from (plist-get p :fromaddress))
7007 (table
7008 (list
7009 (cons "%c" (plist-get p :fromto))
7010 (cons "%F" (plist-get p :from))
7011 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7012 (cons "%T" (plist-get p :to))
7013 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7014 (cons "%s" (plist-get p :subject))
7015 (cons "%m" (plist-get p :message-id)))))
7016 (when (string-match "%c" fmt)
7017 ;; Check if the user wrote this message
7018 (if (and org-from-is-user-regexp from to
7019 (save-match-data (string-match org-from-is-user-regexp from)))
7020 (setq fmt (replace-match "to %t" t t fmt))
7021 (setq fmt (replace-match "from %f" t t fmt))))
7022 (org-replace-escapes fmt table)))
7024 (defun org-make-org-heading-search-string (&optional string heading)
7025 "Make search string for STRING or current headline."
7026 (interactive)
7027 (let ((s (or string (org-get-heading))))
7028 (unless (and string (not heading))
7029 ;; We are using a headline, clean up garbage in there.
7030 (if (string-match org-todo-regexp s)
7031 (setq s (replace-match "" t t s)))
7032 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7033 (setq s (replace-match "" t t s)))
7034 (setq s (org-trim s))
7035 (if (string-match (concat "^\\(" org-quote-string "\\|"
7036 org-comment-string "\\)") s)
7037 (setq s (replace-match "" t t s)))
7038 (while (string-match org-ts-regexp s)
7039 (setq s (replace-match "" t t s))))
7040 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7041 (setq s (replace-match " " t t s)))
7042 (or string (setq s (concat "*" s))) ; Add * for headlines
7043 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7045 (defun org-make-link (&rest strings)
7046 "Concatenate STRINGS."
7047 (apply 'concat strings))
7049 (defun org-make-link-string (link &optional description)
7050 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7051 (unless (string-match "\\S-" link)
7052 (error "Empty link"))
7053 (when (stringp description)
7054 ;; Remove brackets from the description, they are fatal.
7055 (while (string-match "\\[" description)
7056 (setq description (replace-match "{" t t description)))
7057 (while (string-match "\\]" description)
7058 (setq description (replace-match "}" t t description))))
7059 (when (equal (org-link-escape link) description)
7060 ;; No description needed, it is identical
7061 (setq description nil))
7062 (when (and (not description)
7063 (not (equal link (org-link-escape link))))
7064 (setq description (org-extract-attributes link)))
7065 (concat "[[" (org-link-escape link) "]"
7066 (if description (concat "[" description "]") "")
7067 "]"))
7069 (defconst org-link-escape-chars
7070 '((?\ . "%20")
7071 (?\[ . "%5B")
7072 (?\] . "%5D")
7073 (?\340 . "%E0") ; `a
7074 (?\342 . "%E2") ; ^a
7075 (?\347 . "%E7") ; ,c
7076 (?\350 . "%E8") ; `e
7077 (?\351 . "%E9") ; 'e
7078 (?\352 . "%EA") ; ^e
7079 (?\356 . "%EE") ; ^i
7080 (?\364 . "%F4") ; ^o
7081 (?\371 . "%F9") ; `u
7082 (?\373 . "%FB") ; ^u
7083 (?\; . "%3B")
7084 (?? . "%3F")
7085 (?= . "%3D")
7086 (?+ . "%2B")
7088 "Association list of escapes for some characters problematic in links.
7089 This is the list that is used for internal purposes.")
7091 (defconst org-link-escape-chars-browser
7092 '((?\ . "%20")) ; 32 for the SPC char
7093 "Association list of escapes for some characters problematic in links.
7094 This is the list that is used before handing over to the browser.")
7096 (defun org-link-escape (text &optional table)
7097 "Escape characters in TEXT that are problematic for links."
7098 (setq table (or table org-link-escape-chars))
7099 (when text
7100 (let ((re (mapconcat (lambda (x) (regexp-quote
7101 (char-to-string (car x))))
7102 table "\\|")))
7103 (while (string-match re text)
7104 (setq text
7105 (replace-match
7106 (cdr (assoc (string-to-char (match-string 0 text))
7107 table))
7108 t t text)))
7109 text)))
7111 (defun org-link-unescape (text &optional table)
7112 "Reverse the action of `org-link-escape'."
7113 (setq table (or table org-link-escape-chars))
7114 (when text
7115 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7116 table "\\|")))
7117 (while (string-match re text)
7118 (setq text
7119 (replace-match
7120 (char-to-string (car (rassoc (match-string 0 text) table)))
7121 t t text)))
7122 text)))
7124 (defun org-xor (a b)
7125 "Exclusive or."
7126 (if a (not b) b))
7128 (defun org-fixup-message-id-for-http (s)
7129 "Replace special characters in a message id, so it can be used in an http query."
7130 (while (string-match "<" s)
7131 (setq s (replace-match "%3C" t t s)))
7132 (while (string-match ">" s)
7133 (setq s (replace-match "%3E" t t s)))
7134 (while (string-match "@" s)
7135 (setq s (replace-match "%40" t t s)))
7138 ;;;###autoload
7139 (defun org-insert-link-global ()
7140 "Insert a link like Org-mode does.
7141 This command can be called in any mode to insert a link in Org-mode syntax."
7142 (interactive)
7143 (org-load-modules-maybe)
7144 (org-run-like-in-org-mode 'org-insert-link))
7146 (defun org-insert-link (&optional complete-file link-location)
7147 "Insert a link. At the prompt, enter the link.
7149 Completion can be used to insert any of the link protocol prefixes like
7150 http or ftp in use.
7152 The history can be used to select a link previously stored with
7153 `org-store-link'. When the empty string is entered (i.e. if you just
7154 press RET at the prompt), the link defaults to the most recently
7155 stored link. As SPC triggers completion in the minibuffer, you need to
7156 use M-SPC or C-q SPC to force the insertion of a space character.
7158 You will also be prompted for a description, and if one is given, it will
7159 be displayed in the buffer instead of the link.
7161 If there is already a link at point, this command will allow you to edit link
7162 and description parts.
7164 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7165 be selected using completion. The path to the file will be relative to the
7166 current directory if the file is in the current directory or a subdirectory.
7167 Otherwise, the link will be the absolute path as completed in the minibuffer
7168 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7169 option `org-link-file-path-type'.
7171 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7172 the current directory or below.
7174 With three \\[universal-argument] prefixes, negate the meaning of
7175 `org-keep-stored-link-after-insertion'.
7177 If `org-make-link-description-function' is non-nil, this function will be
7178 called with the link target, and the result will be the default
7179 link description.
7181 If the LINK-LOCATION parameter is non-nil, this value will be
7182 used as the link location instead of reading one interactively."
7183 (interactive "P")
7184 (let* ((wcf (current-window-configuration))
7185 (region (if (org-region-active-p)
7186 (buffer-substring (region-beginning) (region-end))))
7187 (remove (and region (list (region-beginning) (region-end))))
7188 (desc region)
7189 tmphist ; byte-compile incorrectly complains about this
7190 (link link-location)
7191 entry file)
7192 (cond
7193 (link-location) ; specified by arg, just use it.
7194 ((org-in-regexp org-bracket-link-regexp 1)
7195 ;; We do have a link at point, and we are going to edit it.
7196 (setq remove (list (match-beginning 0) (match-end 0)))
7197 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7198 (setq link (read-string "Link: "
7199 (org-link-unescape
7200 (org-match-string-no-properties 1)))))
7201 ((or (org-in-regexp org-angle-link-re)
7202 (org-in-regexp org-plain-link-re))
7203 ;; Convert to bracket link
7204 (setq remove (list (match-beginning 0) (match-end 0))
7205 link (read-string "Link: "
7206 (org-remove-angle-brackets (match-string 0)))))
7207 ((member complete-file '((4) (16)))
7208 ;; Completing read for file names.
7209 (setq file (read-file-name "File: "))
7210 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7211 (pwd1 (file-name-as-directory (abbreviate-file-name
7212 (expand-file-name ".")))))
7213 (cond
7214 ((equal complete-file '(16))
7215 (setq link (org-make-link
7216 "file:"
7217 (abbreviate-file-name (expand-file-name file)))))
7218 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7219 (setq link (org-make-link "file:" (match-string 1 file))))
7220 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7221 (expand-file-name file))
7222 (setq link (org-make-link
7223 "file:" (match-string 1 (expand-file-name file)))))
7224 (t (setq link (org-make-link "file:" file))))))
7226 ;; Read link, with completion for stored links.
7227 (with-output-to-temp-buffer "*Org Links*"
7228 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7229 (when org-stored-links
7230 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7231 (princ (mapconcat
7232 (lambda (x)
7233 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7234 (reverse org-stored-links) "\n"))))
7235 (let ((cw (selected-window)))
7236 (select-window (get-buffer-window "*Org Links*"))
7237 (setq truncate-lines t)
7238 (org-fit-window-to-buffer)
7239 (select-window cw))
7240 ;; Fake a link history, containing the stored links.
7241 (setq tmphist (append (mapcar 'car org-stored-links)
7242 org-insert-link-history))
7243 (unwind-protect
7244 (setq link
7245 (let ((org-completion-use-ido nil))
7246 (org-completing-read
7247 "Link: "
7248 (append
7249 (mapcar (lambda (x) (list (concat (car x) ":")))
7250 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7251 (mapcar (lambda (x) (list (concat x ":")))
7252 org-link-types))
7253 nil nil nil
7254 'tmphist
7255 (or (car (car org-stored-links))))))
7256 (set-window-configuration wcf)
7257 (kill-buffer "*Org Links*"))
7258 (setq entry (assoc link org-stored-links))
7259 (or entry (push link org-insert-link-history))
7260 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7261 (not org-keep-stored-link-after-insertion))
7262 (setq org-stored-links (delq (assoc link org-stored-links)
7263 org-stored-links)))
7264 (setq desc (or desc (nth 1 entry)))))
7266 (if (string-match org-plain-link-re link)
7267 ;; URL-like link, normalize the use of angular brackets.
7268 (setq link (org-make-link (org-remove-angle-brackets link))))
7270 ;; Check if we are linking to the current file with a search option
7271 ;; If yes, simplify the link by using only the search option.
7272 (when (and buffer-file-name
7273 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7274 (let* ((path (match-string 1 link))
7275 (case-fold-search nil)
7276 (search (match-string 2 link)))
7277 (save-match-data
7278 (if (equal (file-truename buffer-file-name) (file-truename path))
7279 ;; We are linking to this same file, with a search option
7280 (setq link search)))))
7282 ;; Check if we can/should use a relative path. If yes, simplify the link
7283 (when (string-match "^file:\\(.*\\)" link)
7284 (let* ((path (match-string 1 link))
7285 (origpath path)
7286 (case-fold-search nil))
7287 (cond
7288 ((or (eq org-link-file-path-type 'absolute)
7289 (equal complete-file '(16)))
7290 (setq path (abbreviate-file-name (expand-file-name path))))
7291 ((eq org-link-file-path-type 'noabbrev)
7292 (setq path (expand-file-name path)))
7293 ((eq org-link-file-path-type 'relative)
7294 (setq path (file-relative-name path)))
7296 (save-match-data
7297 (if (string-match (concat "^" (regexp-quote
7298 (file-name-as-directory
7299 (expand-file-name "."))))
7300 (expand-file-name path))
7301 ;; We are linking a file with relative path name.
7302 (setq path (substring (expand-file-name path)
7303 (match-end 0)))
7304 (setq path (abbreviate-file-name (expand-file-name path)))))))
7305 (setq link (concat "file:" path))
7306 (if (equal desc origpath)
7307 (setq desc path))))
7309 (if org-make-link-description-function
7310 (setq desc (funcall org-make-link-description-function link desc)))
7312 (setq desc (read-string "Description: " desc))
7313 (unless (string-match "\\S-" desc) (setq desc nil))
7314 (if remove (apply 'delete-region remove))
7315 (insert (org-make-link-string link desc))))
7317 (defun org-completing-read (&rest args)
7318 "Completing-read with SPACE being a normal character."
7319 (let ((minibuffer-local-completion-map
7320 (copy-keymap minibuffer-local-completion-map)))
7321 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7322 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7323 (apply 'org-ido-completing-read args)))
7325 (defun org-completing-read-no-ido (&rest args)
7326 (let (org-completion-use-ido)
7327 (apply 'org-completing-read args)))
7329 (defun org-ido-completing-read (&rest args)
7330 "Completing-read using `ido-mode' speedups if available"
7331 (if (and org-completion-use-ido
7332 (fboundp 'ido-completing-read)
7333 (boundp 'ido-mode) ido-mode
7334 (listp (second args)))
7335 (let ((ido-enter-matching-directory nil))
7336 (apply 'ido-completing-read (concat (car args))
7337 (mapcar (lambda (x) (car x)) (nth 1 args))
7338 (cddr args)))
7339 (apply 'completing-read args)))
7341 (defun org-extract-attributes (s)
7342 "Extract the attributes cookie from a string and set as text property."
7343 (let (a attr (start 0) key value)
7344 (save-match-data
7345 (when (string-match "{{\\([^}]+\\)}}$" s)
7346 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7347 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7348 (setq key (match-string 1 a) value (match-string 2 a)
7349 start (match-end 0)
7350 attr (plist-put attr (intern key) value))))
7351 (org-add-props s nil 'org-attr attr))
7354 (defun org-extract-attributes-from-string (tag)
7355 (let (key value attr)
7356 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7357 (setq key (match-string 1 tag) value (match-string 2 tag)
7358 tag (replace-match "" t t tag)
7359 attr (plist-put attr (intern key) value)))
7360 (cons tag attr)))
7362 (defun org-attributes-to-string (plist)
7363 "Format a property list into an HTML attribute list."
7364 (let ((s "") key value)
7365 (while plist
7366 (setq key (pop plist) value (pop plist))
7367 (and value
7368 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7371 ;;; Opening/following a link
7373 (defvar org-link-search-failed nil)
7375 (defun org-next-link ()
7376 "Move forward to the next link.
7377 If the link is in hidden text, expose it."
7378 (interactive)
7379 (when (and org-link-search-failed (eq this-command last-command))
7380 (goto-char (point-min))
7381 (message "Link search wrapped back to beginning of buffer"))
7382 (setq org-link-search-failed nil)
7383 (let* ((pos (point))
7384 (ct (org-context))
7385 (a (assoc :link ct)))
7386 (if a (goto-char (nth 2 a)))
7387 (if (re-search-forward org-any-link-re nil t)
7388 (progn
7389 (goto-char (match-beginning 0))
7390 (if (org-invisible-p) (org-show-context)))
7391 (goto-char pos)
7392 (setq org-link-search-failed t)
7393 (error "No further link found"))))
7395 (defun org-previous-link ()
7396 "Move backward to the previous link.
7397 If the link is in hidden text, expose it."
7398 (interactive)
7399 (when (and org-link-search-failed (eq this-command last-command))
7400 (goto-char (point-max))
7401 (message "Link search wrapped back to end of buffer"))
7402 (setq org-link-search-failed nil)
7403 (let* ((pos (point))
7404 (ct (org-context))
7405 (a (assoc :link ct)))
7406 (if a (goto-char (nth 1 a)))
7407 (if (re-search-backward org-any-link-re nil t)
7408 (progn
7409 (goto-char (match-beginning 0))
7410 (if (org-invisible-p) (org-show-context)))
7411 (goto-char pos)
7412 (setq org-link-search-failed t)
7413 (error "No further link found"))))
7415 (defun org-translate-link (s)
7416 "Translate a link string if a translation function has been defined."
7417 (if (and org-link-translation-function
7418 (fboundp org-link-translation-function)
7419 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7420 (progn
7421 (setq s (funcall org-link-translation-function
7422 (match-string 1) (match-string 2)))
7423 (concat (car s) ":" (cdr s)))
7426 (defun org-translate-link-from-planner (type path)
7427 "Translate a link from Emacs Planner syntax so that Org can follow it.
7428 This is still an experimental function, your mileage may vary."
7429 (cond
7430 ((member type '("http" "https" "news" "ftp"))
7431 ;; standard Internet links are the same.
7432 nil)
7433 ((and (equal type "irc") (string-match "^//" path))
7434 ;; Planner has two / at the beginning of an irc link, we have 1.
7435 ;; We should have zero, actually....
7436 (setq path (substring path 1)))
7437 ((and (equal type "lisp") (string-match "^/" path))
7438 ;; Planner has a slash, we do not.
7439 (setq type "elisp" path (substring path 1)))
7440 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7441 ;; A typical message link. Planner has the id after the fina slash,
7442 ;; we separate it with a hash mark
7443 (setq path (concat (match-string 1 path) "#"
7444 (org-remove-angle-brackets (match-string 2 path)))))
7446 (cons type path))
7448 (defun org-find-file-at-mouse (ev)
7449 "Open file link or URL at mouse."
7450 (interactive "e")
7451 (mouse-set-point ev)
7452 (org-open-at-point 'in-emacs))
7454 (defun org-open-at-mouse (ev)
7455 "Open file link or URL at mouse."
7456 (interactive "e")
7457 (mouse-set-point ev)
7458 (if (eq major-mode 'org-agenda-mode)
7459 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7460 (org-open-at-point))
7462 (defvar org-window-config-before-follow-link nil
7463 "The window configuration before following a link.
7464 This is saved in case the need arises to restore it.")
7466 (defvar org-open-link-marker (make-marker)
7467 "Marker pointing to the location where `org-open-at-point; was called.")
7469 ;;;###autoload
7470 (defun org-open-at-point-global ()
7471 "Follow a link like Org-mode does.
7472 This command can be called in any mode to follow a link that has
7473 Org-mode syntax."
7474 (interactive)
7475 (org-run-like-in-org-mode 'org-open-at-point))
7477 ;;;###autoload
7478 (defun org-open-link-from-string (s &optional arg)
7479 "Open a link in the string S, as if it was in Org-mode."
7480 (interactive "sLink: \nP")
7481 (let ((reference-buffer (current-buffer)))
7482 (with-temp-buffer
7483 (let ((org-inhibit-startup t))
7484 (org-mode)
7485 (insert s)
7486 (goto-char (point-min))
7487 (org-open-at-point arg reference-buffer)))))
7489 (defun org-open-at-point (&optional in-emacs reference-buffer)
7490 "Open link at or after point.
7491 If there is no link at point, this function will search forward up to
7492 the end of the current line.
7493 Normally, files will be opened by an appropriate application. If the
7494 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7495 With a double prefix argument, try to open outside of Emacs, in the
7496 application the system uses for this file type."
7497 (interactive "P")
7498 (org-load-modules-maybe)
7499 (move-marker org-open-link-marker (point))
7500 (setq org-window-config-before-follow-link (current-window-configuration))
7501 (org-remove-occur-highlights nil nil t)
7502 (cond
7503 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7504 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7505 (org-footnote-action))
7507 (let (type path link line search (pos (point)))
7508 (catch 'match
7509 (save-excursion
7510 (skip-chars-forward "^]\n\r")
7511 (when (org-in-regexp org-bracket-link-regexp)
7512 (setq link (org-extract-attributes
7513 (org-link-unescape (org-match-string-no-properties 1))))
7514 (while (string-match " *\n *" link)
7515 (setq link (replace-match " " t t link)))
7516 (setq link (org-link-expand-abbrev link))
7517 (cond
7518 ((or (file-name-absolute-p link)
7519 (string-match "^\\.\\.?/" link))
7520 (setq type "file" path link))
7521 ((string-match org-link-re-with-space3 link)
7522 (setq type (match-string 1 link) path (match-string 2 link)))
7523 (t (setq type "thisfile" path link)))
7524 (throw 'match t)))
7526 (when (get-text-property (point) 'org-linked-text)
7527 (setq type "thisfile"
7528 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7529 (1+ (point)) (point))
7530 path (buffer-substring
7531 (previous-single-property-change pos 'org-linked-text)
7532 (next-single-property-change pos 'org-linked-text)))
7533 (throw 'match t))
7535 (save-excursion
7536 (when (or (org-in-regexp org-angle-link-re)
7537 (org-in-regexp org-plain-link-re))
7538 (setq type (match-string 1) path (match-string 2))
7539 (throw 'match t)))
7540 (save-excursion
7541 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7542 (setq type "tags"
7543 path (match-string 1))
7544 (while (string-match ":" path)
7545 (setq path (replace-match "+" t t path)))
7546 (throw 'match t)))
7547 (when (org-in-regexp "<\\([^><\n]+\\)>")
7548 (setq type "tree-match"
7549 path (match-string 1))
7550 (throw 'match t)))
7551 (unless path
7552 (error "No link found"))
7554 ;; switch back to reference buffer
7555 ;; needed when if called in a temporary buffer through
7556 ;; org-open-link-from-string
7557 (and reference-buffer (switch-to-buffer reference-buffer))
7559 ;; Remove any trailing spaces in path
7560 (if (string-match " +\\'" path)
7561 (setq path (replace-match "" t t path)))
7562 (if (and org-link-translation-function
7563 (fboundp org-link-translation-function))
7564 ;; Check if we need to translate the link
7565 (let ((tmp (funcall org-link-translation-function type path)))
7566 (setq type (car tmp) path (cdr tmp))))
7568 (cond
7570 ((assoc type org-link-protocols)
7571 (funcall (nth 1 (assoc type org-link-protocols)) path))
7573 ((equal type "mailto")
7574 (let ((cmd (car org-link-mailto-program))
7575 (args (cdr org-link-mailto-program)) args1
7576 (address path) (subject "") a)
7577 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7578 (setq address (match-string 1 path)
7579 subject (org-link-escape (match-string 2 path))))
7580 (while args
7581 (cond
7582 ((not (stringp (car args))) (push (pop args) args1))
7583 (t (setq a (pop args))
7584 (if (string-match "%a" a)
7585 (setq a (replace-match address t t a)))
7586 (if (string-match "%s" a)
7587 (setq a (replace-match subject t t a)))
7588 (push a args1))))
7589 (apply cmd (nreverse args1))))
7591 ((member type '("http" "https" "ftp" "news"))
7592 (browse-url (concat type ":" (org-link-escape
7593 path org-link-escape-chars-browser))))
7595 ((member type '("message"))
7596 (browse-url (concat type ":" path)))
7598 ((string= type "tags")
7599 (org-tags-view in-emacs path))
7600 ((string= type "thisfile")
7601 (if in-emacs
7602 (switch-to-buffer-other-window
7603 (org-get-buffer-for-internal-link (current-buffer)))
7604 (org-mark-ring-push))
7605 (let ((cmd `(org-link-search
7606 ,path
7607 ,(cond ((equal in-emacs '(4)) 'occur)
7608 ((equal in-emacs '(16)) 'org-occur)
7609 (t nil))
7610 ,pos)))
7611 (condition-case nil (eval cmd)
7612 (error (progn (widen) (eval cmd))))))
7614 ((string= type "tree-match")
7615 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7617 ((string= type "file")
7618 (if (string-match "::\\([0-9]+\\)\\'" path)
7619 (setq line (string-to-number (match-string 1 path))
7620 path (substring path 0 (match-beginning 0)))
7621 (if (string-match "::\\(.+\\)\\'" path)
7622 (setq search (match-string 1 path)
7623 path (substring path 0 (match-beginning 0)))))
7624 (if (string-match "[*?{]" (file-name-nondirectory path))
7625 (dired path)
7626 (org-open-file path in-emacs line search)))
7628 ((string= type "news")
7629 (require 'org-gnus)
7630 (org-gnus-follow-link path))
7632 ((string= type "shell")
7633 (let ((cmd path))
7634 (if (or (not org-confirm-shell-link-function)
7635 (funcall org-confirm-shell-link-function
7636 (format "Execute \"%s\" in shell? "
7637 (org-add-props cmd nil
7638 'face 'org-warning))))
7639 (progn
7640 (message "Executing %s" cmd)
7641 (shell-command cmd))
7642 (error "Abort"))))
7644 ((string= type "elisp")
7645 (let ((cmd path))
7646 (if (or (not org-confirm-elisp-link-function)
7647 (funcall org-confirm-elisp-link-function
7648 (format "Execute \"%s\" as elisp? "
7649 (org-add-props cmd nil
7650 'face 'org-warning))))
7651 (message "%s => %s" cmd
7652 (if (equal (string-to-char cmd) ?\()
7653 (eval (read cmd))
7654 (call-interactively (read cmd))))
7655 (error "Abort"))))
7658 (browse-url-at-point))))))
7659 (move-marker org-open-link-marker nil)
7660 (run-hook-with-args 'org-follow-link-hook))
7662 ;;;; Time estimates
7664 (defun org-get-effort (&optional pom)
7665 "Get the effort estimate for the current entry."
7666 (org-entry-get pom org-effort-property))
7668 ;;; File search
7670 (defvar org-create-file-search-functions nil
7671 "List of functions to construct the right search string for a file link.
7672 These functions are called in turn with point at the location to
7673 which the link should point.
7675 A function in the hook should first test if it would like to
7676 handle this file type, for example by checking the major-mode or
7677 the file extension. If it decides not to handle this file, it
7678 should just return nil to give other functions a chance. If it
7679 does handle the file, it must return the search string to be used
7680 when following the link. The search string will be part of the
7681 file link, given after a double colon, and `org-open-at-point'
7682 will automatically search for it. If special measures must be
7683 taken to make the search successful, another function should be
7684 added to the companion hook `org-execute-file-search-functions',
7685 which see.
7687 A function in this hook may also use `setq' to set the variable
7688 `description' to provide a suggestion for the descriptive text to
7689 be used for this link when it gets inserted into an Org-mode
7690 buffer with \\[org-insert-link].")
7692 (defvar org-execute-file-search-functions nil
7693 "List of functions to execute a file search triggered by a link.
7695 Functions added to this hook must accept a single argument, the
7696 search string that was part of the file link, the part after the
7697 double colon. The function must first check if it would like to
7698 handle this search, for example by checking the major-mode or the
7699 file extension. If it decides not to handle this search, it
7700 should just return nil to give other functions a chance. If it
7701 does handle the search, it must return a non-nil value to keep
7702 other functions from trying.
7704 Each function can access the current prefix argument through the
7705 variable `current-prefix-argument'. Note that a single prefix is
7706 used to force opening a link in Emacs, so it may be good to only
7707 use a numeric or double prefix to guide the search function.
7709 In case this is needed, a function in this hook can also restore
7710 the window configuration before `org-open-at-point' was called using:
7712 (set-window-configuration org-window-config-before-follow-link)")
7714 (defun org-link-search (s &optional type avoid-pos)
7715 "Search for a link search option.
7716 If S is surrounded by forward slashes, it is interpreted as a
7717 regular expression. In org-mode files, this will create an `org-occur'
7718 sparse tree. In ordinary files, `occur' will be used to list matches.
7719 If the current buffer is in `dired-mode', grep will be used to search
7720 in all files. If AVOID-POS is given, ignore matches near that position."
7721 (let ((case-fold-search t)
7722 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7723 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7724 (append '(("") (" ") ("\t") ("\n"))
7725 org-emphasis-alist)
7726 "\\|") "\\)"))
7727 (pos (point))
7728 (pre nil) (post nil)
7729 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7730 (cond
7731 ;; First check if there are any special
7732 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7733 ;; Now try the builtin stuff
7734 ((save-excursion
7735 (goto-char (point-min))
7736 (and
7737 (re-search-forward
7738 (concat "<<" (regexp-quote s0) ">>") nil t)
7739 (setq type 'dedicated
7740 pos (match-beginning 0))))
7741 ;; There is an exact target for this
7742 (goto-char pos))
7743 ((and (string-match "^(\\(.*\\))$" s0)
7744 (save-excursion
7745 (goto-char (point-min))
7746 (and
7747 (re-search-forward
7748 (concat "[^[]" (regexp-quote
7749 (format org-coderef-label-format
7750 (match-string 1 s0))))
7751 nil t)
7752 (setq type 'dedicated
7753 pos (1+ (match-beginning 0))))))
7754 ;; There is a coderef target for this
7755 (goto-char pos))
7756 ((string-match "^/\\(.*\\)/$" s)
7757 ;; A regular expression
7758 (cond
7759 ((org-mode-p)
7760 (org-occur (match-string 1 s)))
7761 ;;((eq major-mode 'dired-mode)
7762 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7763 (t (org-do-occur (match-string 1 s)))))
7765 ;; A normal search strings
7766 (when (equal (string-to-char s) ?*)
7767 ;; Anchor on headlines, post may include tags.
7768 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7769 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7770 s (substring s 1)))
7771 (remove-text-properties
7772 0 (length s)
7773 '(face nil mouse-face nil keymap nil fontified nil) s)
7774 ;; Make a series of regular expressions to find a match
7775 (setq words (org-split-string s "[ \n\r\t]+")
7777 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7778 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7779 "\\)" markers)
7780 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7781 re2a (concat "[ \t\r\n]" re2a_)
7782 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7783 re4 (concat "[^a-zA-Z_]" re4_)
7785 re1 (concat pre re2 post)
7786 re3 (concat pre (if pre re4_ re4) post)
7787 re5 (concat pre ".*" re4)
7788 re2 (concat pre re2)
7789 re2a (concat pre (if pre re2a_ re2a))
7790 re4 (concat pre (if pre re4_ re4))
7791 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7792 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7793 re5 "\\)"
7795 (cond
7796 ((eq type 'org-occur) (org-occur reall))
7797 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7798 (t (goto-char (point-min))
7799 (setq type 'fuzzy)
7800 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7801 (org-search-not-self 1 re1 nil t)
7802 (org-search-not-self 1 re2 nil t)
7803 (org-search-not-self 1 re2a nil t)
7804 (org-search-not-self 1 re3 nil t)
7805 (org-search-not-self 1 re4 nil t)
7806 (org-search-not-self 1 re5 nil t)
7808 (goto-char (match-beginning 1))
7809 (goto-char pos)
7810 (error "No match")))))
7812 ;; Normal string-search
7813 (goto-char (point-min))
7814 (if (search-forward s nil t)
7815 (goto-char (match-beginning 0))
7816 (error "No match"))))
7817 (and (org-mode-p) (org-show-context 'link-search))
7818 type))
7820 (defun org-search-not-self (group &rest args)
7821 "Execute `re-search-forward', but only accept matches that do not
7822 enclose the position of `org-open-link-marker'."
7823 (let ((m org-open-link-marker))
7824 (catch 'exit
7825 (while (apply 're-search-forward args)
7826 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7827 (goto-char (match-end group))
7828 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7829 (> (match-beginning 0) (marker-position m))
7830 (< (match-end 0) (marker-position m)))
7831 (save-match-data
7832 (or (not (org-in-regexp
7833 org-bracket-link-analytic-regexp 1))
7834 (not (match-end 4)) ; no description
7835 (and (<= (match-beginning 4) (point))
7836 (>= (match-end 4) (point))))))
7837 (throw 'exit (point))))))))
7839 (defun org-get-buffer-for-internal-link (buffer)
7840 "Return a buffer to be used for displaying the link target of internal links."
7841 (cond
7842 ((not org-display-internal-link-with-indirect-buffer)
7843 buffer)
7844 ((string-match "(Clone)$" (buffer-name buffer))
7845 (message "Buffer is already a clone, not making another one")
7846 ;; we also do not modify visibility in this case
7847 buffer)
7848 (t ; make a new indirect buffer for displaying the link
7849 (let* ((bn (buffer-name buffer))
7850 (ibn (concat bn "(Clone)"))
7851 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7852 (with-current-buffer ib (org-overview))
7853 ib))))
7855 (defun org-do-occur (regexp &optional cleanup)
7856 "Call the Emacs command `occur'.
7857 If CLEANUP is non-nil, remove the printout of the regular expression
7858 in the *Occur* buffer. This is useful if the regex is long and not useful
7859 to read."
7860 (occur regexp)
7861 (when cleanup
7862 (let ((cwin (selected-window)) win beg end)
7863 (when (setq win (get-buffer-window "*Occur*"))
7864 (select-window win))
7865 (goto-char (point-min))
7866 (when (re-search-forward "match[a-z]+" nil t)
7867 (setq beg (match-end 0))
7868 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7869 (setq end (1- (match-beginning 0)))))
7870 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7871 (goto-char (point-min))
7872 (select-window cwin))))
7874 ;;; The mark ring for links jumps
7876 (defvar org-mark-ring nil
7877 "Mark ring for positions before jumps in Org-mode.")
7878 (defvar org-mark-ring-last-goto nil
7879 "Last position in the mark ring used to go back.")
7880 ;; Fill and close the ring
7881 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7882 (loop for i from 1 to org-mark-ring-length do
7883 (push (make-marker) org-mark-ring))
7884 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7885 org-mark-ring)
7887 (defun org-mark-ring-push (&optional pos buffer)
7888 "Put the current position or POS into the mark ring and rotate it."
7889 (interactive)
7890 (setq pos (or pos (point)))
7891 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7892 (move-marker (car org-mark-ring)
7893 (or pos (point))
7894 (or buffer (current-buffer)))
7895 (message "%s"
7896 (substitute-command-keys
7897 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7899 (defun org-mark-ring-goto (&optional n)
7900 "Jump to the previous position in the mark ring.
7901 With prefix arg N, jump back that many stored positions. When
7902 called several times in succession, walk through the entire ring.
7903 Org-mode commands jumping to a different position in the current file,
7904 or to another Org-mode file, automatically push the old position
7905 onto the ring."
7906 (interactive "p")
7907 (let (p m)
7908 (if (eq last-command this-command)
7909 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7910 (setq p org-mark-ring))
7911 (setq org-mark-ring-last-goto p)
7912 (setq m (car p))
7913 (switch-to-buffer (marker-buffer m))
7914 (goto-char m)
7915 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7917 (defun org-remove-angle-brackets (s)
7918 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7919 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7921 (defun org-add-angle-brackets (s)
7922 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7923 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7925 (defun org-remove-double-quotes (s)
7926 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7927 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7930 ;;; Following specific links
7932 (defun org-follow-timestamp-link ()
7933 (cond
7934 ((org-at-date-range-p t)
7935 (let ((org-agenda-start-on-weekday)
7936 (t1 (match-string 1))
7937 (t2 (match-string 2)))
7938 (setq t1 (time-to-days (org-time-string-to-time t1))
7939 t2 (time-to-days (org-time-string-to-time t2)))
7940 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7941 ((org-at-timestamp-p t)
7942 (org-agenda-list nil (time-to-days (org-time-string-to-time
7943 (substring (match-string 1) 0 10)))
7945 (t (error "This should not happen"))))
7948 ;;; Following file links
7949 (defvar org-wait nil)
7950 (defun org-open-file (path &optional in-emacs line search)
7951 "Open the file at PATH.
7952 First, this expands any special file name abbreviations. Then the
7953 configuration variable `org-file-apps' is checked if it contains an
7954 entry for this file type, and if yes, the corresponding command is launched.
7956 If no application is found, Emacs simply visits the file.
7958 With optional prefix argument IN-EMACS, Emacs will visit the file.
7959 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7960 and o use an external application to visit the file.
7962 Optional LINE specifies a line to go to, optional SEARCH a string to
7963 search for. If LINE or SEARCH is given, the file will always be
7964 opened in Emacs.
7965 If the file does not exist, an error is thrown."
7966 (setq in-emacs (or in-emacs line search))
7967 (let* ((file (if (equal path "")
7968 buffer-file-name
7969 (substitute-in-file-name (expand-file-name path))))
7970 (apps (append org-file-apps (org-default-apps)))
7971 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7972 (dirp (if remp nil (file-directory-p file)))
7973 (file (if (and dirp org-open-directory-means-index-dot-org)
7974 (concat (file-name-as-directory file) "index.org")
7975 file))
7976 (a-m-a-p (assq 'auto-mode apps))
7977 (dfile (downcase file))
7978 (old-buffer (current-buffer))
7979 (old-pos (point))
7980 (old-mode major-mode)
7981 ext cmd)
7982 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7983 (setq ext (match-string 1 dfile))
7984 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7985 (setq ext (match-string 1 dfile))))
7986 (cond
7987 ((equal in-emacs '(16))
7988 (setq cmd (cdr (assoc 'system apps))))
7989 (in-emacs (setq cmd 'emacs))
7991 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7992 (and dirp (cdr (assoc 'directory apps)))
7993 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7994 'string-match)
7995 (cdr (assoc ext apps))
7996 (cdr (assoc t apps))))))
7997 (when (eq cmd 'system)
7998 (setq cmd (cdr (assoc 'system apps))))
7999 (when (eq cmd 'default)
8000 (setq cmd (cdr (assoc t apps))))
8001 (when (eq cmd 'mailcap)
8002 (require 'mailcap)
8003 (mailcap-parse-mailcaps)
8004 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8005 (command (mailcap-mime-info mime-type)))
8006 (if (stringp command)
8007 (setq cmd command)
8008 (setq cmd 'emacs))))
8009 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8010 (not (file-exists-p file))
8011 (not org-open-non-existing-files))
8012 (error "No such file: %s" file))
8013 (cond
8014 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8015 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8016 (while (string-match "['\"]%s['\"]" cmd)
8017 (setq cmd (replace-match "%s" t t cmd)))
8018 (while (string-match "%s" cmd)
8019 (setq cmd (replace-match
8020 (save-match-data
8021 (shell-quote-argument
8022 (convert-standard-filename file)))
8023 t t cmd)))
8024 (save-window-excursion
8025 (start-process-shell-command cmd nil cmd)
8026 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8028 ((or (stringp cmd)
8029 (eq cmd 'emacs))
8030 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8031 (widen)
8032 (if line (goto-line line)
8033 (if search (org-link-search search))))
8034 ((consp cmd)
8035 (let ((file (convert-standard-filename file)))
8036 (eval cmd)))
8037 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8038 (and (org-mode-p) (eq old-mode 'org-mode)
8039 (or (not (equal old-buffer (current-buffer)))
8040 (not (equal old-pos (point))))
8041 (org-mark-ring-push old-pos old-buffer))))
8043 (defun org-default-apps ()
8044 "Return the default applications for this operating system."
8045 (cond
8046 ((eq system-type 'darwin)
8047 org-file-apps-defaults-macosx)
8048 ((eq system-type 'windows-nt)
8049 org-file-apps-defaults-windowsnt)
8050 (t org-file-apps-defaults-gnu)))
8052 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8053 "Convert extensions to regular expressions in the cars of LIST.
8054 Also, weed out any non-string entries, because the return value is used
8055 only for regexp matching.
8056 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8057 point to the symbol `emacs', indicating that the file should
8058 be opened in Emacs."
8059 (append
8060 (delq nil
8061 (mapcar (lambda (x)
8062 (if (not (stringp (car x)))
8064 (if (string-match "\\W" (car x))
8066 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8067 list))
8068 (if add-auto-mode
8069 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8071 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8072 (defun org-file-remote-p (file)
8073 "Test whether FILE specifies a location on a remote system.
8074 Return non-nil if the location is indeed remote.
8076 For example, the filename \"/user@host:/foo\" specifies a location
8077 on the system \"/user@host:\"."
8078 (cond ((fboundp 'file-remote-p)
8079 (file-remote-p file))
8080 ((fboundp 'tramp-handle-file-remote-p)
8081 (tramp-handle-file-remote-p file))
8082 ((and (boundp 'ange-ftp-name-format)
8083 (string-match (car ange-ftp-name-format) file))
8085 (t nil)))
8088 ;;;; Refiling
8090 (defun org-get-org-file ()
8091 "Read a filename, with default directory `org-directory'."
8092 (let ((default (or org-default-notes-file remember-data-file)))
8093 (read-file-name (format "File name [%s]: " default)
8094 (file-name-as-directory org-directory)
8095 default)))
8097 (defun org-notes-order-reversed-p ()
8098 "Check if the current file should receive notes in reversed order."
8099 (cond
8100 ((not org-reverse-note-order) nil)
8101 ((eq t org-reverse-note-order) t)
8102 ((not (listp org-reverse-note-order)) nil)
8103 (t (catch 'exit
8104 (let ((all org-reverse-note-order)
8105 entry)
8106 (while (setq entry (pop all))
8107 (if (string-match (car entry) buffer-file-name)
8108 (throw 'exit (cdr entry))))
8109 nil)))))
8111 (defvar org-refile-target-table nil
8112 "The list of refile targets, created by `org-refile'.")
8114 (defvar org-agenda-new-buffers nil
8115 "Buffers created to visit agenda files.")
8117 (defun org-get-refile-targets (&optional default-buffer)
8118 "Produce a table with refile targets."
8119 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8120 targets txt re files f desc descre fast-path-p level)
8121 (message "Getting targets...")
8122 (with-current-buffer (or default-buffer (current-buffer))
8123 (while (setq entry (pop entries))
8124 (setq files (car entry) desc (cdr entry))
8125 (setq fast-path-p nil)
8126 (cond
8127 ((null files) (setq files (list (current-buffer))))
8128 ((eq files 'org-agenda-files)
8129 (setq files (org-agenda-files 'unrestricted)))
8130 ((and (symbolp files) (fboundp files))
8131 (setq files (funcall files)))
8132 ((and (symbolp files) (boundp files))
8133 (setq files (symbol-value files))))
8134 (if (stringp files) (setq files (list files)))
8135 (cond
8136 ((eq (car desc) :tag)
8137 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8138 ((eq (car desc) :todo)
8139 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8140 ((eq (car desc) :regexp)
8141 (setq descre (cdr desc)))
8142 ((eq (car desc) :level)
8143 (setq descre (concat "^\\*\\{" (number-to-string
8144 (if org-odd-levels-only
8145 (1- (* 2 (cdr desc)))
8146 (cdr desc)))
8147 "\\}[ \t]")))
8148 ((eq (car desc) :maxlevel)
8149 (setq fast-path-p t)
8150 (setq descre (concat "^\\*\\{1," (number-to-string
8151 (if org-odd-levels-only
8152 (1- (* 2 (cdr desc)))
8153 (cdr desc)))
8154 "\\}[ \t]")))
8155 (t (error "Bad refiling target description %s" desc)))
8156 (while (setq f (pop files))
8157 (save-excursion
8158 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8159 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8160 (setq f (expand-file-name f))
8161 (if (eq org-refile-use-outline-path 'file)
8162 (push (list (file-name-nondirectory f) f nil nil) targets))
8163 (save-excursion
8164 (save-restriction
8165 (widen)
8166 (goto-char (point-min))
8167 (while (re-search-forward descre nil t)
8168 (goto-char (point-at-bol))
8169 (when (looking-at org-complex-heading-regexp)
8170 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8171 txt (org-link-display-format (match-string 4))
8172 re (concat "^" (regexp-quote
8173 (buffer-substring (match-beginning 1)
8174 (match-end 4)))))
8175 (if (match-end 5) (setq re (concat re "[ \t]+"
8176 (regexp-quote
8177 (match-string 5)))))
8178 (setq re (concat re "[ \t]*$"))
8179 (when org-refile-use-outline-path
8180 (setq txt (mapconcat 'org-protect-slash
8181 (append
8182 (if (eq org-refile-use-outline-path 'file)
8183 (list (file-name-nondirectory
8184 (buffer-file-name (buffer-base-buffer))))
8185 (if (eq org-refile-use-outline-path 'full-file-path)
8186 (list (buffer-file-name (buffer-base-buffer)))))
8187 (org-get-outline-path fast-path-p level txt)
8188 (list txt))
8189 "/")))
8190 (push (list txt f re (point)) targets))
8191 (goto-char (point-at-eol))))))))
8192 (message "Getting targets...done")
8193 (nreverse targets))))
8195 (defun org-protect-slash (s)
8196 (while (string-match "/" s)
8197 (setq s (replace-match "\\" t t s)))
8200 (defvar org-olpa (make-vector 20 nil))
8202 (defun org-get-outline-path (&optional fastp level heading)
8203 "Return the outline path to the current entry, as a list."
8204 (if fastp
8205 (progn
8206 (if (> level 19)
8207 (error "Outline path failure, more than 19 levels."))
8208 (loop for i from level upto 19 do
8209 (aset org-olpa i nil))
8210 (prog1
8211 (delq nil (append org-olpa nil))
8212 (aset org-olpa level heading)))
8213 (let (rtn)
8214 (save-excursion
8215 (while (org-up-heading-safe)
8216 (when (looking-at org-complex-heading-regexp)
8217 (push (org-match-string-no-properties 4) rtn)))
8218 rtn))))
8220 (defvar org-refile-history nil
8221 "History for refiling operations.")
8223 (defun org-refile (&optional goto default-buffer)
8224 "Move the entry at point to another heading.
8225 The list of target headings is compiled using the information in
8226 `org-refile-targets', which see. This list is created before each use
8227 and will therefore always be up-to-date.
8229 At the target location, the entry is filed as a subitem of the target heading.
8230 Depending on `org-reverse-note-order', the new subitem will either be the
8231 first or the last subitem.
8233 If there is an active region, all entries in that region will be moved.
8234 However, the region must fulfil the requirement that the first heading
8235 is the first one sets the top-level of the moved text - at most siblings
8236 below it are allowed.
8238 With prefix arg GOTO, the command will only visit the target location,
8239 not actually move anything.
8240 With a double prefix `C-u C-u', go to the location where the last refiling
8241 operation has put the subtree."
8242 (interactive "P")
8243 (let* ((cbuf (current-buffer))
8244 (regionp (org-region-active-p))
8245 (region-start (and regionp (region-beginning)))
8246 (region-end (and regionp (region-end)))
8247 (region-length (and regionp (- region-end region-start)))
8248 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8249 pos it nbuf file re level reversed)
8250 (when regionp (goto-char region-start)
8251 (unless (org-kill-is-subtree-p
8252 (buffer-substring region-start region-end))
8253 (error "The region is not a (sequence of) subtree(s)")))
8254 (if (equal goto '(16))
8255 (org-refile-goto-last-stored)
8256 (when (setq it (org-refile-get-location
8257 (if goto "Goto: " "Refile to: ") default-buffer))
8258 (setq file (nth 1 it)
8259 re (nth 2 it)
8260 pos (nth 3 it))
8261 (if (and (not goto)
8263 (equal (buffer-file-name) file)
8264 (if regionp
8265 (and (>= pos region-start)
8266 (<= pos region-end))
8267 (and (>= pos (point))
8268 (< pos (save-excursion
8269 (org-end-of-subtree t t))))))
8270 (error "Cannot refile to position inside the tree or region"))
8272 (setq nbuf (or (find-buffer-visiting file)
8273 (find-file-noselect file)))
8274 (if goto
8275 (progn
8276 (switch-to-buffer nbuf)
8277 (goto-char pos)
8278 (org-show-context 'org-goto))
8279 (if regionp
8280 (progn
8281 (kill-new (buffer-substring region-start region-end))
8282 (org-save-markers-in-region region-start region-end))
8283 (org-copy-subtree 1 nil t))
8284 (save-excursion
8285 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8286 (find-file-noselect file))))
8287 (setq reversed (org-notes-order-reversed-p))
8288 (save-excursion
8289 (save-restriction
8290 (widen)
8291 (if pos
8292 (progn
8293 (goto-char pos)
8294 (looking-at outline-regexp)
8295 (setq level (org-get-valid-level (funcall outline-level) 1))
8296 (goto-char
8297 (if reversed
8298 (or (outline-next-heading) (point-max))
8299 (or (save-excursion (outline-get-next-sibling))
8300 (org-end-of-subtree t t)
8301 (point-max)))))
8302 (setq level 1)
8303 (if (not reversed)
8304 (goto-char (point-max))
8305 (goto-char (point-min))
8306 (or (outline-next-heading) (goto-char (point-max)))))
8307 (if (not (bolp)) (newline))
8308 (bookmark-set "org-refile-last-stored")
8309 (org-paste-subtree level))))
8310 (if regionp
8311 (delete-region (point) (+ (point) region-length))
8312 (org-cut-subtree))
8313 (setq org-markers-to-move nil)
8314 (message "Refiled to \"%s\"" (car it)))))))
8316 (defun org-refile-goto-last-stored ()
8317 "Go to the location where the last refile was stored."
8318 (interactive)
8319 (bookmark-jump "org-refile-last-stored")
8320 (message "This is the location of the last refile"))
8322 (defun org-refile-get-location (&optional prompt default-buffer)
8323 "Prompt the user for a refile location, using PROMPT."
8324 (let ((org-refile-targets org-refile-targets)
8325 (org-refile-use-outline-path org-refile-use-outline-path))
8326 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8327 (unless org-refile-target-table
8328 (error "No refile targets"))
8329 (let* ((cbuf (current-buffer))
8330 (partial-completion-mode nil)
8331 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8332 (cfunc (if (and org-refile-use-outline-path
8333 org-outline-path-complete-in-steps)
8334 'org-olpath-completing-read
8335 'org-ido-completing-read))
8336 (extra (if org-refile-use-outline-path "/" ""))
8337 (filename (and cfn (expand-file-name cfn)))
8338 (tbl (mapcar
8339 (lambda (x)
8340 (if (and (not (member org-refile-use-outline-path
8341 '(file full-file-path)))
8342 (not (equal filename (nth 1 x))))
8343 (cons (concat (car x) extra " ("
8344 (file-name-nondirectory (nth 1 x)) ")")
8345 (cdr x))
8346 (cons (concat (car x) extra) (cdr x))))
8347 org-refile-target-table))
8348 (completion-ignore-case t))
8349 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
8350 tbl)))
8352 (defun org-olpath-completing-read (prompt collection &rest args)
8353 "Read an outline path like a file name."
8354 (let ((thetable collection)
8355 (org-completion-use-ido nil)) ; does not work with ido.
8356 (apply
8357 'org-ido-completing-read prompt
8358 (lambda (string predicate &optional flag)
8359 (let (rtn r f (l (length string)))
8360 (cond
8361 ((eq flag nil)
8362 ;; try completion
8363 (try-completion string thetable))
8364 ((eq flag t)
8365 ;; all-completions
8366 (setq rtn (all-completions string thetable predicate))
8367 (mapcar
8368 (lambda (x)
8369 (setq r (substring x l))
8370 (if (string-match " ([^)]*)$" x)
8371 (setq f (match-string 0 x))
8372 (setq f ""))
8373 (if (string-match "/" r)
8374 (concat string (substring r 0 (match-end 0)) f)
8376 rtn))
8377 ((eq flag 'lambda)
8378 ;; exact match?
8379 (assoc string thetable)))
8381 args)))
8383 ;;;; Dynamic blocks
8385 (defun org-find-dblock (name)
8386 "Find the first dynamic block with name NAME in the buffer.
8387 If not found, stay at current position and return nil."
8388 (let (pos)
8389 (save-excursion
8390 (goto-char (point-min))
8391 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8392 nil t)
8393 (match-beginning 0))))
8394 (if pos (goto-char pos))
8395 pos))
8397 (defconst org-dblock-start-re
8398 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8399 "Matches the startline of a dynamic block, with parameters.")
8401 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8402 "Matches the end of a dynamic block.")
8404 (defun org-create-dblock (plist)
8405 "Create a dynamic block section, with parameters taken from PLIST.
8406 PLIST must contain a :name entry which is used as name of the block."
8407 (unless (bolp) (newline))
8408 (let ((name (plist-get plist :name)))
8409 (insert "#+BEGIN: " name)
8410 (while plist
8411 (if (eq (car plist) :name)
8412 (setq plist (cddr plist))
8413 (insert " " (prin1-to-string (pop plist)))))
8414 (insert "\n\n#+END:\n")
8415 (beginning-of-line -2)))
8417 (defun org-prepare-dblock ()
8418 "Prepare dynamic block for refresh.
8419 This empties the block, puts the cursor at the insert position and returns
8420 the property list including an extra property :name with the block name."
8421 (unless (looking-at org-dblock-start-re)
8422 (error "Not at a dynamic block"))
8423 (let* ((begdel (1+ (match-end 0)))
8424 (name (org-no-properties (match-string 1)))
8425 (params (append (list :name name)
8426 (read (concat "(" (match-string 3) ")")))))
8427 (unless (re-search-forward org-dblock-end-re nil t)
8428 (error "Dynamic block not terminated"))
8429 (setq params
8430 (append params
8431 (list :content (buffer-substring
8432 begdel (match-beginning 0)))))
8433 (delete-region begdel (match-beginning 0))
8434 (goto-char begdel)
8435 (open-line 1)
8436 params))
8438 (defun org-map-dblocks (&optional command)
8439 "Apply COMMAND to all dynamic blocks in the current buffer.
8440 If COMMAND is not given, use `org-update-dblock'."
8441 (let ((cmd (or command 'org-update-dblock))
8442 pos)
8443 (save-excursion
8444 (goto-char (point-min))
8445 (while (re-search-forward org-dblock-start-re nil t)
8446 (goto-char (setq pos (match-beginning 0)))
8447 (condition-case nil
8448 (funcall cmd)
8449 (error (message "Error during update of dynamic block")))
8450 (goto-char pos)
8451 (unless (re-search-forward org-dblock-end-re nil t)
8452 (error "Dynamic block not terminated"))))))
8454 (defun org-dblock-update (&optional arg)
8455 "User command for updating dynamic blocks.
8456 Update the dynamic block at point. With prefix ARG, update all dynamic
8457 blocks in the buffer."
8458 (interactive "P")
8459 (if arg
8460 (org-update-all-dblocks)
8461 (or (looking-at org-dblock-start-re)
8462 (org-beginning-of-dblock))
8463 (org-update-dblock)))
8465 (defun org-update-dblock ()
8466 "Update the dynamic block at point
8467 This means to empty the block, parse for parameters and then call
8468 the correct writing function."
8469 (save-window-excursion
8470 (let* ((pos (point))
8471 (line (org-current-line))
8472 (params (org-prepare-dblock))
8473 (name (plist-get params :name))
8474 (cmd (intern (concat "org-dblock-write:" name))))
8475 (message "Updating dynamic block `%s' at line %d..." name line)
8476 (funcall cmd params)
8477 (message "Updating dynamic block `%s' at line %d...done" name line)
8478 (goto-char pos))))
8480 (defun org-beginning-of-dblock ()
8481 "Find the beginning of the dynamic block at point.
8482 Error if there is no such block at point."
8483 (let ((pos (point))
8484 beg)
8485 (end-of-line 1)
8486 (if (and (re-search-backward org-dblock-start-re nil t)
8487 (setq beg (match-beginning 0))
8488 (re-search-forward org-dblock-end-re nil t)
8489 (> (match-end 0) pos))
8490 (goto-char beg)
8491 (goto-char pos)
8492 (error "Not in a dynamic block"))))
8494 (defun org-update-all-dblocks ()
8495 "Update all dynamic blocks in the buffer.
8496 This function can be used in a hook."
8497 (when (org-mode-p)
8498 (org-map-dblocks 'org-update-dblock)))
8501 ;;;; Completion
8503 (defconst org-additional-option-like-keywords
8504 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8505 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8506 "BEGIN_EXAMPLE" "END_EXAMPLE"
8507 "BEGIN_QUOTE" "END_QUOTE"
8508 "BEGIN_VERSE" "END_VERSE"
8509 "BEGIN_CENTER" "END_CENTER"
8510 "BEGIN_SRC" "END_SRC"
8511 "CATEGORY" "COLUMNS"
8512 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8514 (defcustom org-structure-template-alist
8516 ("s" "#+begin_src ?\n\n#+end_src"
8517 "<src lang=\"?\">\n\n</src>")
8518 ("e" "#+begin_example\n?\n#+end_example"
8519 "<example>\n?\n</example>")
8520 ("q" "#+begin_quote\n?\n#+end_quote"
8521 "<quote>\n?\n</quote>")
8522 ("v" "#+begin_verse\n?\n#+end_verse"
8523 "<verse>\n?\n/verse>")
8524 ("c" "#+begin_center\n?\n#+end_center"
8525 "<center>\n?\n/center>")
8526 ("l" "#+begin_latex\n?\n#+end_latex"
8527 "<literal style=\"latex\">\n?\n</literal>")
8528 ("L" "#+latex: "
8529 "<literal style=\"latex\">?</literal>")
8530 ("h" "#+begin_html\n?\n#+end_html"
8531 "<literal style=\"html\">\n?\n</literal>")
8532 ("H" "#+html: "
8533 "<literal style=\"html\">?</literal>")
8534 ("a" "#+begin_ascii\n?\n#+end_ascii")
8535 ("A" "#+ascii: ")
8536 ("i" "#+include %file ?"
8537 "<include file=%file markup=\"?\">")
8539 "Structure completion elements.
8540 This is a list of abbreviation keys and values. The value gets inserted
8541 it you type @samp{.} followed by the key and then the completion key,
8542 usually `M-TAB'. %file will be replaced by a file name after prompting
8543 for the file using completion.
8544 There are two templates for each key, the first uses the original Org syntax,
8545 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8546 the default when the /org-mtags.el/ module has been loaded. See also the
8547 variable `org-mtags-prefer-muse-templates'.
8548 This is an experimental feature, it is undecided if it is going to stay in."
8549 :group 'org-completion
8550 :type '(repeat
8551 (string :tag "Key")
8552 (string :tag "Template")
8553 (string :tag "Muse Template")))
8555 (defun org-try-structure-completion ()
8556 "Try to complete a structure template before point.
8557 This looks for strings like \"<e\" on an otherwise empty line and
8558 expands them."
8559 (let ((l (buffer-substring (point-at-bol) (point)))
8561 (when (and (looking-at "[ \t]*$")
8562 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8563 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8564 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8565 (match-beginning 1)) a)
8566 t)))
8568 (defun org-complete-expand-structure-template (start cell)
8569 "Expand a structure template."
8570 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8571 (rpl (nth (if musep 2 1) cell)))
8572 (delete-region start (point))
8573 (when (string-match "\\`#\\+" rpl)
8574 (cond
8575 ((bolp))
8576 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8577 (delete-region (point-at-bol) (point)))
8578 (t (newline))))
8579 (setq start (point))
8580 (if (string-match "%file" rpl)
8581 (setq rpl (replace-match
8582 (concat
8583 "\""
8584 (save-match-data
8585 (abbreviate-file-name (read-file-name "Include file: ")))
8586 "\"")
8587 t t rpl)))
8588 (insert rpl)
8589 (if (re-search-backward "\\?" start t) (delete-char 1))))
8592 (defun org-complete (&optional arg)
8593 "Perform completion on word at point.
8594 At the beginning of a headline, this completes TODO keywords as given in
8595 `org-todo-keywords'.
8596 If the current word is preceded by a backslash, completes the TeX symbols
8597 that are supported for HTML support.
8598 If the current word is preceded by \"#+\", completes special words for
8599 setting file options.
8600 In the line after \"#+STARTUP:, complete valid keywords.\"
8601 At all other locations, this simply calls the value of
8602 `org-completion-fallback-command'."
8603 (interactive "P")
8604 (org-without-partial-completion
8605 (catch 'exit
8606 (let* ((a nil)
8607 (end (point))
8608 (beg1 (save-excursion
8609 (skip-chars-backward (org-re "[:alnum:]_@"))
8610 (point)))
8611 (beg (save-excursion
8612 (skip-chars-backward "a-zA-Z0-9_:$")
8613 (point)))
8614 (confirm (lambda (x) (stringp (car x))))
8615 (searchhead (equal (char-before beg) ?*))
8616 (struct
8617 (when (and (member (char-before beg1) '(?. ?<))
8618 (setq a (assoc (buffer-substring beg1 (point))
8619 org-structure-template-alist)))
8620 (org-complete-expand-structure-template (1- beg1) a)
8621 (throw 'exit t)))
8622 (tag (and (equal (char-before beg1) ?:)
8623 (equal (char-after (point-at-bol)) ?*)))
8624 (prop (and (equal (char-before beg1) ?:)
8625 (not (equal (char-after (point-at-bol)) ?*))))
8626 (texp (equal (char-before beg) ?\\))
8627 (link (equal (char-before beg) ?\[))
8628 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8629 beg)
8630 "#+"))
8631 (startup (string-match "^#\\+STARTUP:.*"
8632 (buffer-substring (point-at-bol) (point))))
8633 (completion-ignore-case opt)
8634 (type nil)
8635 (tbl nil)
8636 (table (cond
8637 (opt
8638 (setq type :opt)
8639 (require 'org-exp)
8640 (append
8641 (mapcar
8642 (lambda (x)
8643 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8644 (cons (match-string 2 x) (match-string 1 x)))
8645 (org-split-string (org-get-current-options) "\n"))
8646 (mapcar 'list org-additional-option-like-keywords)))
8647 (startup
8648 (setq type :startup)
8649 org-startup-options)
8650 (link (append org-link-abbrev-alist-local
8651 org-link-abbrev-alist))
8652 (texp
8653 (setq type :tex)
8654 org-html-entities)
8655 ((string-match "\\`\\*+[ \t]+\\'"
8656 (buffer-substring (point-at-bol) beg))
8657 (setq type :todo)
8658 (mapcar 'list org-todo-keywords-1))
8659 (searchhead
8660 (setq type :searchhead)
8661 (save-excursion
8662 (goto-char (point-min))
8663 (while (re-search-forward org-todo-line-regexp nil t)
8664 (push (list
8665 (org-make-org-heading-search-string
8666 (match-string 3) t))
8667 tbl)))
8668 tbl)
8669 (tag (setq type :tag beg beg1)
8670 (or org-tag-alist (org-get-buffer-tags)))
8671 (prop (setq type :prop beg beg1)
8672 (mapcar 'list (org-buffer-property-keys nil t t)))
8673 (t (progn
8674 (call-interactively org-completion-fallback-command)
8675 (throw 'exit nil)))))
8676 (pattern (buffer-substring-no-properties beg end))
8677 (completion (try-completion pattern table confirm)))
8678 (cond ((eq completion t)
8679 (if (not (assoc (upcase pattern) table))
8680 (message "Already complete")
8681 (if (and (equal type :opt)
8682 (not (member (car (assoc (upcase pattern) table))
8683 org-additional-option-like-keywords)))
8684 (insert (substring (cdr (assoc (upcase pattern) table))
8685 (length pattern)))
8686 (if (memq type '(:tag :prop)) (insert ":")))))
8687 ((null completion)
8688 (message "Can't find completion for \"%s\"" pattern)
8689 (ding))
8690 ((not (string= pattern completion))
8691 (delete-region beg end)
8692 (if (string-match " +$" completion)
8693 (setq completion (replace-match "" t t completion)))
8694 (insert completion)
8695 (if (get-buffer-window "*Completions*")
8696 (delete-window (get-buffer-window "*Completions*")))
8697 (if (assoc completion table)
8698 (if (eq type :todo) (insert " ")
8699 (if (memq type '(:tag :prop)) (insert ":"))))
8700 (if (and (equal type :opt) (assoc completion table))
8701 (message "%s" (substitute-command-keys
8702 "Press \\[org-complete] again to insert example settings"))))
8704 (message "Making completion list...")
8705 (let ((list (sort (all-completions pattern table confirm)
8706 'string<)))
8707 (with-output-to-temp-buffer "*Completions*"
8708 (condition-case nil
8709 ;; Protection needed for XEmacs and emacs 21
8710 (display-completion-list list pattern)
8711 (error (display-completion-list list)))))
8712 (message "Making completion list...%s" "done")))))))
8714 ;;;; TODO, DEADLINE, Comments
8716 (defun org-toggle-comment ()
8717 "Change the COMMENT state of an entry."
8718 (interactive)
8719 (save-excursion
8720 (org-back-to-heading)
8721 (let (case-fold-search)
8722 (if (looking-at (concat outline-regexp
8723 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8724 (replace-match "" t t nil 1)
8725 (if (looking-at outline-regexp)
8726 (progn
8727 (goto-char (match-end 0))
8728 (insert org-comment-string " ")))))))
8730 (defvar org-last-todo-state-is-todo nil
8731 "This is non-nil when the last TODO state change led to a TODO state.
8732 If the last change removed the TODO tag or switched to DONE, then
8733 this is nil.")
8735 (defvar org-setting-tags nil) ; dynamically skipped
8737 (defun org-parse-local-options (string var)
8738 "Parse STRING for startup setting relevant for variable VAR."
8739 (let ((rtn (symbol-value var))
8740 e opts)
8741 (save-match-data
8742 (if (or (not string) (not (string-match "\\S-" string)))
8744 (setq opts (delq nil (mapcar (lambda (x)
8745 (setq e (assoc x org-startup-options))
8746 (if (eq (nth 1 e) var) e nil))
8747 (org-split-string string "[ \t]+"))))
8748 (if (not opts)
8750 (setq rtn nil)
8751 (while (setq e (pop opts))
8752 (if (not (nth 3 e))
8753 (setq rtn (nth 2 e))
8754 (if (not (listp rtn)) (setq rtn nil))
8755 (push (nth 2 e) rtn)))
8756 rtn)))))
8758 (defvar org-todo-setup-filter-hook nil
8759 "Hook for functions that pre-filter todo specs.
8761 Each function takes a todo spec and returns either `nil' or the spec
8762 transformed into canonical form." )
8764 (defvar org-todo-get-default-hook nil
8765 "Hook for functions that get a default item for todo.
8767 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8768 `nil' or a string to be used for the todo mark." )
8770 (defvar org-agenda-headline-snapshot-before-repeat)
8771 (defun org-todo (&optional arg)
8772 "Change the TODO state of an item.
8773 The state of an item is given by a keyword at the start of the heading,
8774 like
8775 *** TODO Write paper
8776 *** DONE Call mom
8778 The different keywords are specified in the variable `org-todo-keywords'.
8779 By default the available states are \"TODO\" and \"DONE\".
8780 So for this example: when the item starts with TODO, it is changed to DONE.
8781 When it starts with DONE, the DONE is removed. And when neither TODO nor
8782 DONE are present, add TODO at the beginning of the heading.
8784 With C-u prefix arg, use completion to determine the new state.
8785 With numeric prefix arg, switch to that state.
8786 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8787 With a tripple C-u prefix, circumvent any state blocking.
8789 For calling through lisp, arg is also interpreted in the following way:
8790 'none -> empty state
8791 \"\"(empty string) -> switch to empty state
8792 'done -> switch to DONE
8793 'nextset -> switch to the next set of keywords
8794 'previousset -> switch to the previous set of keywords
8795 \"WAITING\" -> switch to the specified keyword, but only if it
8796 really is a member of `org-todo-keywords'."
8797 (interactive "P")
8798 (if (equal arg '(16)) (setq arg 'nextset))
8799 (let ((org-blocker-hook org-blocker-hook)
8800 (case-fold-search nil))
8801 (when (equal arg '(64))
8802 (setq arg nil org-blocker-hook nil))
8803 (save-excursion
8804 (catch 'exit
8805 (org-back-to-heading)
8806 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8807 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
8808 (looking-at " *"))
8809 (let* ((match-data (match-data))
8810 (startpos (point-at-bol))
8811 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8812 (org-log-done org-log-done)
8813 (org-log-repeat org-log-repeat)
8814 (org-todo-log-states org-todo-log-states)
8815 (this (match-string 1))
8816 (hl-pos (match-beginning 0))
8817 (head (org-get-todo-sequence-head this))
8818 (ass (assoc head org-todo-kwd-alist))
8819 (interpret (nth 1 ass))
8820 (done-word (nth 3 ass))
8821 (final-done-word (nth 4 ass))
8822 (last-state (or this ""))
8823 (completion-ignore-case t)
8824 (member (member this org-todo-keywords-1))
8825 (tail (cdr member))
8826 (state (cond
8827 ((and org-todo-key-trigger
8828 (or (and (equal arg '(4))
8829 (eq org-use-fast-todo-selection 'prefix))
8830 (and (not arg) org-use-fast-todo-selection
8831 (not (eq org-use-fast-todo-selection
8832 'prefix)))))
8833 ;; Use fast selection
8834 (org-fast-todo-selection))
8835 ((and (equal arg '(4))
8836 (or (not org-use-fast-todo-selection)
8837 (not org-todo-key-trigger)))
8838 ;; Read a state with completion
8839 (org-ido-completing-read
8840 "State: " (mapcar (lambda(x) (list x))
8841 org-todo-keywords-1)
8842 nil t))
8843 ((eq arg 'right)
8844 (if this
8845 (if tail (car tail) nil)
8846 (car org-todo-keywords-1)))
8847 ((eq arg 'left)
8848 (if (equal member org-todo-keywords-1)
8850 (if this
8851 (nth (- (length org-todo-keywords-1)
8852 (length tail) 2)
8853 org-todo-keywords-1)
8854 (org-last org-todo-keywords-1))))
8855 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8856 (setq arg nil))) ; hack to fall back to cycling
8857 (arg
8858 ;; user or caller requests a specific state
8859 (cond
8860 ((equal arg "") nil)
8861 ((eq arg 'none) nil)
8862 ((eq arg 'done) (or done-word (car org-done-keywords)))
8863 ((eq arg 'nextset)
8864 (or (car (cdr (member head org-todo-heads)))
8865 (car org-todo-heads)))
8866 ((eq arg 'previousset)
8867 (let ((org-todo-heads (reverse org-todo-heads)))
8868 (or (car (cdr (member head org-todo-heads)))
8869 (car org-todo-heads))))
8870 ((car (member arg org-todo-keywords-1)))
8871 ((nth (1- (prefix-numeric-value arg))
8872 org-todo-keywords-1))))
8873 ((null member) (or head (car org-todo-keywords-1)))
8874 ((equal this final-done-word) nil) ;; -> make empty
8875 ((null tail) nil) ;; -> first entry
8876 ((memq interpret '(type priority))
8877 (if (eq this-command last-command)
8878 (car tail)
8879 (if (> (length tail) 0)
8880 (or done-word (car org-done-keywords))
8881 nil)))
8883 (car tail))))
8884 (state (or
8885 (run-hook-with-args-until-success
8886 'org-todo-get-default-hook state last-state)
8887 state))
8888 (next (if state (concat " " state " ") " "))
8889 (change-plist (list :type 'todo-state-change :from this :to state
8890 :position startpos))
8891 dolog now-done-p)
8892 (when org-blocker-hook
8893 (setq org-last-todo-state-is-todo
8894 (not (member this org-done-keywords)))
8895 (unless (save-excursion
8896 (save-match-data
8897 (run-hook-with-args-until-failure
8898 'org-blocker-hook change-plist)))
8899 (if (interactive-p)
8900 (error "TODO state change from %s to %s blocked" this state)
8901 ;; fail silently
8902 (message "TODO state change from %s to %s blocked" this state)
8903 (throw 'exit nil))))
8904 (store-match-data match-data)
8905 (replace-match next t t)
8906 (unless (pos-visible-in-window-p hl-pos)
8907 (message "TODO state changed to %s" (org-trim next)))
8908 (unless head
8909 (setq head (org-get-todo-sequence-head state)
8910 ass (assoc head org-todo-kwd-alist)
8911 interpret (nth 1 ass)
8912 done-word (nth 3 ass)
8913 final-done-word (nth 4 ass)))
8914 (when (memq arg '(nextset previousset))
8915 (message "Keyword-Set %d/%d: %s"
8916 (- (length org-todo-sets) -1
8917 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8918 (length org-todo-sets)
8919 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8920 (setq org-last-todo-state-is-todo
8921 (not (member state org-done-keywords)))
8922 (setq now-done-p (and (member state org-done-keywords)
8923 (not (member this org-done-keywords))))
8924 (and logging (org-local-logging logging))
8925 (when (and (or org-todo-log-states org-log-done)
8926 (not (memq arg '(nextset previousset))))
8927 ;; we need to look at recording a time and note
8928 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8929 (nth 2 (assoc this org-todo-log-states))))
8930 (when (and state
8931 (member state org-not-done-keywords)
8932 (not (member this org-not-done-keywords)))
8933 ;; This is now a todo state and was not one before
8934 ;; If there was a CLOSED time stamp, get rid of it.
8935 (org-add-planning-info nil nil 'closed))
8936 (when (and now-done-p org-log-done)
8937 ;; It is now done, and it was not done before
8938 (org-add-planning-info 'closed (org-current-time))
8939 (if (and (not dolog) (eq 'note org-log-done))
8940 (org-add-log-setup 'done state this 'findpos 'note)))
8941 (when (and state dolog)
8942 ;; This is a non-nil state, and we need to log it
8943 (org-add-log-setup 'state state this 'findpos dolog)))
8944 ;; Fixup tag positioning
8945 (org-todo-trigger-tag-changes state)
8946 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8947 (when org-provide-todo-statistics
8948 (org-update-parent-todo-statistics))
8949 (run-hooks 'org-after-todo-state-change-hook)
8950 (if (and arg (not (member state org-done-keywords)))
8951 (setq head (org-get-todo-sequence-head state)))
8952 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8953 ;; Do we need to trigger a repeat?
8954 (when now-done-p
8955 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8956 ;; This is for the agenda, take a snapshot of the headline.
8957 (save-match-data
8958 (setq org-agenda-headline-snapshot-before-repeat
8959 (org-get-heading))))
8960 (org-auto-repeat-maybe state))
8961 ;; Fixup cursor location if close to the keyword
8962 (if (and (outline-on-heading-p)
8963 (not (bolp))
8964 (save-excursion (beginning-of-line 1)
8965 (looking-at org-todo-line-regexp))
8966 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8967 (progn
8968 (goto-char (or (match-end 2) (match-end 1)))
8969 (and (looking-at " ") (just-one-space))))
8970 (when org-trigger-hook
8971 (save-excursion
8972 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8974 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
8975 "Block turning an entry into a TODO, using the hierarchy.
8976 This checks whether the current task should be blocked from state
8977 changes. Such blocking occurs when:
8979 1. The task has children which are not all in a completed state.
8981 2. A task has a parent with the property :ORDERED:, and there
8982 are siblings prior to the current task with incomplete
8983 status.
8985 3. The parent of the task is blocked because it has siblings that should
8986 be done first, or is child of a block grandparent TODO entry."
8988 (catch 'dont-block
8989 ;; If this is not a todo state change, or if this entry is already DONE,
8990 ;; do not block
8991 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8992 (member (plist-get change-plist :from)
8993 (cons 'done org-done-keywords))
8994 (member (plist-get change-plist :to)
8995 (cons 'todo org-not-done-keywords)))
8996 (throw 'dont-block t))
8997 ;; If this task has children, and any are undone, it's blocked
8998 (save-excursion
8999 (org-back-to-heading t)
9000 (let ((this-level (funcall outline-level)))
9001 (outline-next-heading)
9002 (let ((child-level (funcall outline-level)))
9003 (while (and (not (eobp))
9004 (> child-level this-level))
9005 ;; this todo has children, check whether they are all
9006 ;; completed
9007 (if (and (not (org-entry-is-done-p))
9008 (org-entry-is-todo-p))
9009 (throw 'dont-block nil))
9010 (outline-next-heading)
9011 (setq child-level (funcall outline-level))))))
9012 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9013 ;; any previous siblings are undone, it's blocked
9014 (save-excursion
9015 (org-back-to-heading t)
9016 (let* ((pos (point))
9017 (parent-pos (and (org-up-heading-safe) (point))))
9018 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9019 (when (and (org-entry-get (point) "ORDERED")
9020 (forward-line 1)
9021 (re-search-forward org-not-done-heading-regexp pos t))
9022 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9023 ;; Search further up the hierarchy, to see if an anchestor is blocked
9024 (while t
9025 (goto-char parent-pos)
9026 (if (not (looking-at org-not-done-heading-regexp))
9027 (throw 'dont-block t)) ; do not block, parent is not a TODO
9028 (setq pos (point))
9029 (setq parent-pos (and (org-up-heading-safe) (point)))
9030 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9031 (when (and (org-entry-get (point) "ORDERED")
9032 (forward-line 1)
9033 (re-search-forward org-not-done-heading-regexp pos t))
9034 (throw 'dont-block nil))))))) ; block, older sibling not done.
9036 (defcustom org-track-ordered-property-with-tag nil
9037 "Should the ORDERED property also be shown as a tag?
9038 The ORDERED property decides if an entry should require subtasks to be
9039 completed in sequence. Since a property is not very visible, setting
9040 this option means that toggling the ORDERED property with the command
9041 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9042 not relevant for the behavior, but it makes things more visible.
9044 Note that toggling the tag with tags commands will not change the property
9045 and therefore not influence behavior!
9047 This can be t, meaning the tag ORDERED should be used, It can also be a
9048 string to select a different tag for this task."
9049 :group 'org-todo
9050 :type '(choice
9051 (const :tag "No tracking" nil)
9052 (const :tag "Track with ORDERED tag" t)
9053 (string :tag "Use other tag")))
9055 (defun org-toggle-ordered-property ()
9056 "Toggle the ORDERED property of the current entry.
9057 For better visibility, you can track the value of this property with a tag.
9058 See variable `org-track-ordered-property-with-tag'."
9059 (interactive)
9060 (let* ((t1 org-track-ordered-property-with-tag)
9061 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9062 (save-excursion
9063 (org-back-to-heading)
9064 (if (org-entry-get nil "ORDERED")
9065 (progn
9066 (org-delete-property "ORDERED")
9067 (and tag (org-toggle-tag tag 'off))
9068 (message "Subtasks can be completed in arbitrary order"))
9069 (org-entry-put nil "ORDERED" "t")
9070 (and tag (org-toggle-tag tag 'on))
9071 (message "Subtasks must be completed in sequence")))))
9073 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9074 (defun org-block-todo-from-checkboxes (change-plist)
9075 "Block turning an entry into a TODO, using checkboxes.
9076 This checks whether the current task should be blocked from state
9077 changes because there are uncheckd boxes in this entry."
9078 (catch 'dont-block
9079 ;; If this is not a todo state change, or if this entry is already DONE,
9080 ;; do not block
9081 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9082 (member (plist-get change-plist :from)
9083 (cons 'done org-done-keywords))
9084 (member (plist-get change-plist :to)
9085 (cons 'todo org-not-done-keywords)))
9086 (throw 'dont-block t))
9087 ;; If this task has checkboxes that are not checked, it's blocked
9088 (save-excursion
9089 (org-back-to-heading t)
9090 (let ((beg (point)) end)
9091 (outline-next-heading)
9092 (setq end (point))
9093 (goto-char beg)
9094 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9095 end t)
9096 (progn
9097 (if (boundp 'org-blocked-by-checkboxes)
9098 (setq org-blocked-by-checkboxes t))
9099 (throw 'dont-block nil)))))
9100 t)) ; do not block
9102 (defun org-update-parent-todo-statistics ()
9103 "Update any statistics cookie in the parent of the current headline."
9104 (interactive)
9105 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9106 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9107 (catch 'exit
9108 (save-excursion
9109 (setq level (org-up-heading-safe))
9110 (unless level
9111 (throw 'exit nil))
9112 (while (re-search-forward box-re (point-at-eol) t)
9113 (setq cnt-all 0 cnt-done 0 cookie-present t)
9114 (setq is-percent (match-end 2))
9115 (save-match-data
9116 (unless (outline-next-heading) (throw 'exit nil))
9117 (while (looking-at org-todo-line-regexp)
9118 (setq kwd (match-string 2))
9119 (and kwd (setq cnt-all (1+ cnt-all)))
9120 (and (member kwd org-done-keywords)
9121 (setq cnt-done (1+ cnt-done)))
9122 (condition-case nil
9123 (org-forward-same-level 1)
9124 (error (end-of-line 1)))))
9125 (replace-match
9126 (if is-percent
9127 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9128 (format "[%d/%d]" cnt-done cnt-all))))
9129 (when cookie-present
9130 (run-hook-with-args 'org-after-todo-statistics-hook
9131 cnt-done (- cnt-all cnt-done)))))))
9133 (defvar org-after-todo-statistics-hook nil
9134 "Hook that is called after a TODO statistics cookie has been updated.
9135 Each function is called with two arguments: the number of not-done entries
9136 and the number of done entries.
9138 For example, the following function, when added to this hook, will switch
9139 an entry to DONE when all children are done, and back to TODO when new
9140 entries are set to a TODO status. Note that this hook is only called
9141 when there is a statistics cookie in the headline!
9143 (defun org-summary-todo (n-done n-not-done)
9144 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9145 (let (org-log-done org-log-states) ; turn off logging
9146 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9149 (defun org-todo-trigger-tag-changes (state)
9150 "Apply the changes defined in `org-todo-state-tags-triggers'."
9151 (let ((l org-todo-state-tags-triggers)
9152 changes)
9153 (when (or (not state) (equal state ""))
9154 (setq changes (append changes (cdr (assoc "" l)))))
9155 (when (and (stringp state) (> (length state) 0))
9156 (setq changes (append changes (cdr (assoc state l)))))
9157 (when (member state org-not-done-keywords)
9158 (setq changes (append changes (cdr (assoc 'todo l)))))
9159 (when (member state org-done-keywords)
9160 (setq changes (append changes (cdr (assoc 'done l)))))
9161 (dolist (c changes)
9162 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9164 (defun org-local-logging (value)
9165 "Get logging settings from a property VALUE."
9166 (let* (words w a)
9167 ;; directly set the variables, they are already local.
9168 (setq org-log-done nil
9169 org-log-repeat nil
9170 org-todo-log-states nil)
9171 (setq words (org-split-string value))
9172 (while (setq w (pop words))
9173 (cond
9174 ((setq a (assoc w org-startup-options))
9175 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9176 (set (nth 1 a) (nth 2 a))))
9177 ((setq a (org-extract-log-state-settings w))
9178 (and (member (car a) org-todo-keywords-1)
9179 (push a org-todo-log-states)))))))
9181 (defun org-get-todo-sequence-head (kwd)
9182 "Return the head of the TODO sequence to which KWD belongs.
9183 If KWD is not set, check if there is a text property remembering the
9184 right sequence."
9185 (let (p)
9186 (cond
9187 ((not kwd)
9188 (or (get-text-property (point-at-bol) 'org-todo-head)
9189 (progn
9190 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9191 nil (point-at-eol)))
9192 (get-text-property p 'org-todo-head))))
9193 ((not (member kwd org-todo-keywords-1))
9194 (car org-todo-keywords-1))
9195 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9197 (defun org-fast-todo-selection ()
9198 "Fast TODO keyword selection with single keys.
9199 Returns the new TODO keyword, or nil if no state change should occur."
9200 (let* ((fulltable org-todo-key-alist)
9201 (done-keywords org-done-keywords) ;; needed for the faces.
9202 (maxlen (apply 'max (mapcar
9203 (lambda (x)
9204 (if (stringp (car x)) (string-width (car x)) 0))
9205 fulltable)))
9206 (expert nil)
9207 (fwidth (+ maxlen 3 1 3))
9208 (ncol (/ (- (window-width) 4) fwidth))
9209 tg cnt e c tbl
9210 groups ingroup)
9211 (save-excursion
9212 (save-window-excursion
9213 (if expert
9214 (set-buffer (get-buffer-create " *Org todo*"))
9215 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9216 (erase-buffer)
9217 (org-set-local 'org-done-keywords done-keywords)
9218 (setq tbl fulltable cnt 0)
9219 (while (setq e (pop tbl))
9220 (cond
9221 ((equal e '(:startgroup))
9222 (push '() groups) (setq ingroup t)
9223 (when (not (= cnt 0))
9224 (setq cnt 0)
9225 (insert "\n"))
9226 (insert "{ "))
9227 ((equal e '(:endgroup))
9228 (setq ingroup nil cnt 0)
9229 (insert "}\n"))
9230 ((equal e '(:newline))
9231 (when (not (= cnt 0))
9232 (setq cnt 0)
9233 (insert "\n")
9234 (setq e (car tbl))
9235 (while (equal (car tbl) '(:newline))
9236 (insert "\n")
9237 (setq tbl (cdr tbl)))))
9239 (setq tg (car e) c (cdr e))
9240 (if ingroup (push tg (car groups)))
9241 (setq tg (org-add-props tg nil 'face
9242 (org-get-todo-face tg)))
9243 (if (and (= cnt 0) (not ingroup)) (insert " "))
9244 (insert "[" c "] " tg (make-string
9245 (- fwidth 4 (length tg)) ?\ ))
9246 (when (= (setq cnt (1+ cnt)) ncol)
9247 (insert "\n")
9248 (if ingroup (insert " "))
9249 (setq cnt 0)))))
9250 (insert "\n")
9251 (goto-char (point-min))
9252 (if (not expert) (org-fit-window-to-buffer))
9253 (message "[a-z..]:Set [SPC]:clear")
9254 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9255 (cond
9256 ((or (= c ?\C-g)
9257 (and (= c ?q) (not (rassoc c fulltable))))
9258 (setq quit-flag t))
9259 ((= c ?\ ) nil)
9260 ((setq e (rassoc c fulltable) tg (car e))
9262 (t (setq quit-flag t)))))))
9264 (defun org-entry-is-todo-p ()
9265 (member (org-get-todo-state) org-not-done-keywords))
9267 (defun org-entry-is-done-p ()
9268 (member (org-get-todo-state) org-done-keywords))
9270 (defun org-get-todo-state ()
9271 (save-excursion
9272 (org-back-to-heading t)
9273 (and (looking-at org-todo-line-regexp)
9274 (match-end 2)
9275 (match-string 2))))
9277 (defun org-at-date-range-p (&optional inactive-ok)
9278 "Is the cursor inside a date range?"
9279 (interactive)
9280 (save-excursion
9281 (catch 'exit
9282 (let ((pos (point)))
9283 (skip-chars-backward "^[<\r\n")
9284 (skip-chars-backward "<[")
9285 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9286 (>= (match-end 0) pos)
9287 (throw 'exit t))
9288 (skip-chars-backward "^<[\r\n")
9289 (skip-chars-backward "<[")
9290 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9291 (>= (match-end 0) pos)
9292 (throw 'exit t)))
9293 nil)))
9295 (defun org-get-repeat ()
9296 "Check if there is a deadline/schedule with repeater in this entry."
9297 (save-match-data
9298 (save-excursion
9299 (org-back-to-heading t)
9300 (if (re-search-forward
9301 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9302 (match-string 1)))))
9304 (defvar org-last-changed-timestamp)
9305 (defvar org-last-inserted-timestamp)
9306 (defvar org-log-post-message)
9307 (defvar org-log-note-purpose)
9308 (defvar org-log-note-how)
9309 (defvar org-log-note-extra)
9310 (defun org-auto-repeat-maybe (done-word)
9311 "Check if the current headline contains a repeated deadline/schedule.
9312 If yes, set TODO state back to what it was and change the base date
9313 of repeating deadline/scheduled time stamps to new date.
9314 This function is run automatically after each state change to a DONE state."
9315 ;; last-state is dynamically scoped into this function
9316 (let* ((repeat (org-get-repeat))
9317 (aa (assoc last-state org-todo-kwd-alist))
9318 (interpret (nth 1 aa))
9319 (head (nth 2 aa))
9320 (whata '(("d" . day) ("m" . month) ("y" . year)))
9321 (msg "Entry repeats: ")
9322 (org-log-done nil)
9323 (org-todo-log-states nil)
9324 (nshiftmax 10) (nshift 0)
9325 re type n what ts time)
9326 (when repeat
9327 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9328 (org-todo (if (eq interpret 'type) last-state head))
9329 (when org-log-repeat
9330 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9331 (memq 'org-add-log-note post-command-hook))
9332 ;; OK, we are already setup for some record
9333 (if (eq org-log-repeat 'note)
9334 ;; make sure we take a note, not only a time stamp
9335 (setq org-log-note-how 'note))
9336 ;; Set up for taking a record
9337 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9338 last-state
9339 'findpos org-log-repeat)))
9340 (org-back-to-heading t)
9341 (org-add-planning-info nil nil 'closed)
9342 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9343 org-deadline-time-regexp "\\)\\|\\("
9344 org-ts-regexp "\\)"))
9345 (while (re-search-forward
9346 re (save-excursion (outline-next-heading) (point)) t)
9347 (setq type (if (match-end 1) org-scheduled-string
9348 (if (match-end 3) org-deadline-string "Plain:"))
9349 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9350 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9351 (setq n (string-to-number (match-string 2 ts))
9352 what (match-string 3 ts))
9353 (if (equal what "w") (setq n (* n 7) what "d"))
9354 ;; Preparation, see if we need to modify the start date for the change
9355 (when (match-end 1)
9356 (setq time (save-match-data (org-time-string-to-time ts)))
9357 (cond
9358 ((equal (match-string 1 ts) ".")
9359 ;; Shift starting date to today
9360 (org-timestamp-change
9361 (- (time-to-days (current-time)) (time-to-days time))
9362 'day))
9363 ((equal (match-string 1 ts) "+")
9364 (while (or (= nshift 0)
9365 (<= (time-to-days time) (time-to-days (current-time))))
9366 (when (= (incf nshift) nshiftmax)
9367 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9368 (error "Abort")))
9369 (org-timestamp-change n (cdr (assoc what whata)))
9370 (org-at-timestamp-p t)
9371 (setq ts (match-string 1))
9372 (setq time (save-match-data (org-time-string-to-time ts))))
9373 (org-timestamp-change (- n) (cdr (assoc what whata)))
9374 ;; rematch, so that we have everything in place for the real shift
9375 (org-at-timestamp-p t)
9376 (setq ts (match-string 1))
9377 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9378 (org-timestamp-change n (cdr (assoc what whata)))
9379 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9380 (setq org-log-post-message msg)
9381 (message "%s" msg))))
9383 (defun org-show-todo-tree (arg)
9384 "Make a compact tree which shows all headlines marked with TODO.
9385 The tree will show the lines where the regexp matches, and all higher
9386 headlines above the match.
9387 With a \\[universal-argument] prefix, also show the DONE entries.
9388 With a numeric prefix N, construct a sparse tree for the Nth element
9389 of `org-todo-keywords-1'."
9390 (interactive "P")
9391 (let ((case-fold-search nil)
9392 (kwd-re
9393 (cond ((null arg) org-not-done-regexp)
9394 ((equal arg '(4))
9395 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9396 (mapcar 'list org-todo-keywords-1))))
9397 (concat "\\("
9398 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9399 "\\)\\>")))
9400 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9401 (regexp-quote (nth (1- (prefix-numeric-value arg))
9402 org-todo-keywords-1)))
9403 (t (error "Invalid prefix argument: %s" arg)))))
9404 (message "%d TODO entries found"
9405 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9407 (defun org-deadline (&optional remove time)
9408 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9409 With argument REMOVE, remove any deadline from the item.
9410 When TIME is set, it should be an internal time specification, and the
9411 scheduling will use the corresponding date."
9412 (interactive "P")
9413 (if remove
9414 (progn
9415 (org-remove-timestamp-with-keyword org-deadline-string)
9416 (message "Item no longer has a deadline."))
9417 (if (org-get-repeat)
9418 (error "Cannot change deadline on task with repeater, please do that by hand")
9419 (org-add-planning-info 'deadline time 'closed)
9420 (message "Deadline on %s" org-last-inserted-timestamp))))
9422 (defun org-schedule (&optional remove time)
9423 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9424 With argument REMOVE, remove any scheduling date from the item.
9425 When TIME is set, it should be an internal time specification, and the
9426 scheduling will use the corresponding date."
9427 (interactive "P")
9428 (if remove
9429 (progn
9430 (org-remove-timestamp-with-keyword org-scheduled-string)
9431 (message "Item is no longer scheduled."))
9432 (if (org-get-repeat)
9433 (error "Cannot reschedule task with repeater, please do that by hand")
9434 (org-add-planning-info 'scheduled time 'closed)
9435 (message "Scheduled to %s" org-last-inserted-timestamp))))
9437 (defun org-get-scheduled-time (pom &optional inherit)
9438 "Get the scheduled time as a time tuple, of a format suitable
9439 for calling org-schedule with, or if there is no scheduling,
9440 returns nil."
9441 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9442 (when time
9443 (apply 'encode-time (org-parse-time-string time)))))
9445 (defun org-get-deadline-time (pom &optional inherit)
9446 "Get the deadine as a time tuple, of a format suitable for
9447 calling org-deadlin with, or if there is no scheduling, returns
9448 nil."
9449 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9450 (when time
9451 (apply 'encode-time (org-parse-time-string time)))))
9453 (defun org-remove-timestamp-with-keyword (keyword)
9454 "Remove all time stamps with KEYWORD in the current entry."
9455 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9456 beg)
9457 (save-excursion
9458 (org-back-to-heading t)
9459 (setq beg (point))
9460 (org-end-of-subtree t t)
9461 (while (re-search-backward re beg t)
9462 (replace-match "")
9463 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9464 (equal (char-before) ?\ ))
9465 (backward-delete-char 1)
9466 (if (string-match "^[ \t]*$" (buffer-substring
9467 (point-at-bol) (point-at-eol)))
9468 (delete-region (point-at-bol)
9469 (min (point-max) (1+ (point-at-eol))))))))))
9471 (defun org-add-planning-info (what &optional time &rest remove)
9472 "Insert new timestamp with keyword in the line directly after the headline.
9473 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9474 If non is given, the user is prompted for a date.
9475 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9476 be removed."
9477 (interactive)
9478 (let (org-time-was-given org-end-time-was-given ts
9479 end default-time default-input)
9481 (catch 'exit
9482 (when (and (not time) (memq what '(scheduled deadline)))
9483 ;; Try to get a default date/time from existing timestamp
9484 (save-excursion
9485 (org-back-to-heading t)
9486 (setq end (save-excursion (outline-next-heading) (point)))
9487 (when (re-search-forward (if (eq what 'scheduled)
9488 org-scheduled-time-regexp
9489 org-deadline-time-regexp)
9490 end t)
9491 (setq ts (match-string 1)
9492 default-time
9493 (apply 'encode-time (org-parse-time-string ts))
9494 default-input (and ts (org-get-compact-tod ts))))))
9495 (when what
9496 ;; If necessary, get the time from the user
9497 (setq time (or time (org-read-date nil 'to-time nil nil
9498 default-time default-input))))
9500 (when (and org-insert-labeled-timestamps-at-point
9501 (member what '(scheduled deadline)))
9502 (insert
9503 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9504 (org-insert-time-stamp time org-time-was-given
9505 nil nil nil (list org-end-time-was-given))
9506 (setq what nil))
9507 (save-excursion
9508 (save-restriction
9509 (let (col list elt ts buffer-invisibility-spec)
9510 (org-back-to-heading t)
9511 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9512 (goto-char (match-end 1))
9513 (setq col (current-column))
9514 (goto-char (match-end 0))
9515 (if (eobp) (insert "\n") (forward-char 1))
9516 (when (and (not what)
9517 (not (looking-at
9518 (concat "[ \t]*"
9519 org-keyword-time-not-clock-regexp))))
9520 ;; Nothing to add, nothing to remove...... :-)
9521 (throw 'exit nil))
9522 (if (and (not (looking-at outline-regexp))
9523 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9524 "[^\r\n]*"))
9525 (not (equal (match-string 1) org-clock-string)))
9526 (narrow-to-region (match-beginning 0) (match-end 0))
9527 (insert-before-markers "\n")
9528 (backward-char 1)
9529 (narrow-to-region (point) (point))
9530 (and org-adapt-indentation (org-indent-to-column col)))
9531 ;; Check if we have to remove something.
9532 (setq list (cons what remove))
9533 (while list
9534 (setq elt (pop list))
9535 (goto-char (point-min))
9536 (when (or (and (eq elt 'scheduled)
9537 (re-search-forward org-scheduled-time-regexp nil t))
9538 (and (eq elt 'deadline)
9539 (re-search-forward org-deadline-time-regexp nil t))
9540 (and (eq elt 'closed)
9541 (re-search-forward org-closed-time-regexp nil t)))
9542 (replace-match "")
9543 (if (looking-at "--+<[^>]+>") (replace-match ""))
9544 (if (looking-at " +") (replace-match ""))))
9545 (goto-char (point-max))
9546 (when what
9547 (insert
9548 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9549 (cond ((eq what 'scheduled) org-scheduled-string)
9550 ((eq what 'deadline) org-deadline-string)
9551 ((eq what 'closed) org-closed-string))
9552 " ")
9553 (setq ts (org-insert-time-stamp
9554 time
9555 (or org-time-was-given
9556 (and (eq what 'closed) org-log-done-with-time))
9557 (eq what 'closed)
9558 nil nil (list org-end-time-was-given)))
9559 (end-of-line 1))
9560 (goto-char (point-min))
9561 (widen)
9562 (if (and (looking-at "[ \t]+\n")
9563 (equal (char-before) ?\n))
9564 (delete-region (1- (point)) (point-at-eol)))
9565 ts))))))
9567 (defvar org-log-note-marker (make-marker))
9568 (defvar org-log-note-purpose nil)
9569 (defvar org-log-note-state nil)
9570 (defvar org-log-note-previous-state nil)
9571 (defvar org-log-note-how nil)
9572 (defvar org-log-note-extra nil)
9573 (defvar org-log-note-window-configuration nil)
9574 (defvar org-log-note-return-to (make-marker))
9575 (defvar org-log-post-message nil
9576 "Message to be displayed after a log note has been stored.
9577 The auto-repeater uses this.")
9579 (defun org-add-note ()
9580 "Add a note to the current entry.
9581 This is done in the same way as adding a state change note."
9582 (interactive)
9583 (org-add-log-setup 'note nil nil 'findpos nil))
9585 (defvar org-property-end-re)
9586 (defun org-add-log-setup (&optional purpose state prev-state
9587 findpos how &optional extra)
9588 "Set up the post command hook to take a note.
9589 If this is about to TODO state change, the new state is expected in STATE.
9590 When FINDPOS is non-nil, find the correct position for the note in
9591 the current entry. If not, assume that it can be inserted at point.
9592 HOW is an indicator what kind of note should be created.
9593 EXTRA is additional text that will be inserted into the notes buffer."
9594 (let ((drawer (cond ((stringp org-log-into-drawer)
9595 org-log-into-drawer)
9596 (org-log-into-drawer "LOGBOOK")
9597 (t nil))))
9598 (save-restriction
9599 (save-excursion
9600 (when findpos
9601 (org-back-to-heading t)
9602 (narrow-to-region (point) (save-excursion
9603 (outline-next-heading) (point)))
9604 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9605 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9606 "[^\r\n]*\\)?"))
9607 (goto-char (match-end 0))
9608 (cond
9609 (drawer
9610 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9611 nil t)
9612 (progn
9613 (goto-char (match-end 0))
9614 (or org-log-states-order-reversed
9615 (and (re-search-forward org-property-end-re nil t)
9616 (goto-char (1- (match-beginning 0))))))
9617 (insert "\n:" drawer ":\n:END:")
9618 (beginning-of-line 0)
9619 (org-indent-line-function)
9620 (beginning-of-line 2)
9621 (org-indent-line-function)
9622 (end-of-line 0)))
9623 ((and org-log-state-notes-insert-after-drawers
9624 (save-excursion
9625 (forward-line) (looking-at org-drawer-regexp)))
9626 (forward-line)
9627 (while (looking-at org-drawer-regexp)
9628 (goto-char (match-end 0))
9629 (re-search-forward org-property-end-re (point-max) t)
9630 (forward-line))
9631 (forward-line -1)))
9632 (unless org-log-states-order-reversed
9633 (and (= (char-after) ?\n) (forward-char 1))
9634 (org-skip-over-state-notes)
9635 (skip-chars-backward " \t\n\r")))
9636 (move-marker org-log-note-marker (point))
9637 (setq org-log-note-purpose purpose
9638 org-log-note-state state
9639 org-log-note-previous-state prev-state
9640 org-log-note-how how
9641 org-log-note-extra extra)
9642 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9644 (defun org-skip-over-state-notes ()
9645 "Skip past the list of State notes in an entry."
9646 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9647 (while (looking-at "[ \t]*- State")
9648 (condition-case nil
9649 (org-next-item)
9650 (error (org-end-of-item)))))
9652 (defun org-add-log-note (&optional purpose)
9653 "Pop up a window for taking a note, and add this note later at point."
9654 (remove-hook 'post-command-hook 'org-add-log-note)
9655 (setq org-log-note-window-configuration (current-window-configuration))
9656 (delete-other-windows)
9657 (move-marker org-log-note-return-to (point))
9658 (switch-to-buffer (marker-buffer org-log-note-marker))
9659 (goto-char org-log-note-marker)
9660 (org-switch-to-buffer-other-window "*Org Note*")
9661 (erase-buffer)
9662 (if (memq org-log-note-how '(time state))
9663 (let (current-prefix-arg) (org-store-log-note))
9664 (let ((org-inhibit-startup t)) (org-mode))
9665 (insert (format "# Insert note for %s.
9666 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9667 (cond
9668 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9669 ((eq org-log-note-purpose 'done) "closed todo item")
9670 ((eq org-log-note-purpose 'state)
9671 (format "state change from \"%s\" to \"%s\""
9672 (or org-log-note-previous-state "")
9673 (or org-log-note-state "")))
9674 ((eq org-log-note-purpose 'note)
9675 "this entry")
9676 (t (error "This should not happen")))))
9677 (if org-log-note-extra (insert org-log-note-extra))
9678 (org-set-local 'org-finish-function 'org-store-log-note)))
9680 (defvar org-note-abort nil) ; dynamically scoped
9681 (defun org-store-log-note ()
9682 "Finish taking a log note, and insert it to where it belongs."
9683 (let ((txt (buffer-string))
9684 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9685 lines ind)
9686 (kill-buffer (current-buffer))
9687 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9688 (setq txt (replace-match "" t t txt)))
9689 (if (string-match "\\s-+\\'" txt)
9690 (setq txt (replace-match "" t t txt)))
9691 (setq lines (org-split-string txt "\n"))
9692 (when (and note (string-match "\\S-" note))
9693 (setq note
9694 (org-replace-escapes
9695 note
9696 (list (cons "%u" (user-login-name))
9697 (cons "%U" user-full-name)
9698 (cons "%t" (format-time-string
9699 (org-time-stamp-format 'long 'inactive)
9700 (current-time)))
9701 (cons "%s" (if org-log-note-state
9702 (concat "\"" org-log-note-state "\"")
9703 ""))
9704 (cons "%S" (if org-log-note-previous-state
9705 (concat "\"" org-log-note-previous-state "\"")
9706 "\"\"")))))
9707 (if lines (setq note (concat note " \\\\")))
9708 (push note lines))
9709 (when (or current-prefix-arg org-note-abort)
9710 (when org-log-into-drawer
9711 (org-remove-empty-drawer-at
9712 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
9713 org-log-note-marker))
9714 (setq lines nil))
9715 (when lines
9716 (save-excursion
9717 (set-buffer (marker-buffer org-log-note-marker))
9718 (save-excursion
9719 (goto-char org-log-note-marker)
9720 (move-marker org-log-note-marker nil)
9721 (end-of-line 1)
9722 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9723 (insert "- " (pop lines))
9724 (org-indent-line-function)
9725 (beginning-of-line 1)
9726 (looking-at "[ \t]*")
9727 (setq ind (concat (match-string 0) " "))
9728 (end-of-line 1)
9729 (while lines (insert "\n" ind (pop lines)))
9730 (message "Note stored")
9731 (org-back-to-heading t)
9732 (org-cycle-hide-drawers 'children)))))
9733 (set-window-configuration org-log-note-window-configuration)
9734 (with-current-buffer (marker-buffer org-log-note-return-to)
9735 (goto-char org-log-note-return-to))
9736 (move-marker org-log-note-return-to nil)
9737 (and org-log-post-message (message "%s" org-log-post-message)))
9739 (defun org-remove-empty-drawer-at (drawer pos)
9740 "Remove an emptyr DARWER drawer at position POS.
9741 POS may also be a marker."
9742 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
9743 (save-excursion
9744 (save-restriction
9745 (widen)
9746 (goto-char pos)
9747 (if (org-in-regexp
9748 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
9749 (replace-match ""))))))
9751 (defun org-sparse-tree (&optional arg)
9752 "Create a sparse tree, prompt for the details.
9753 This command can create sparse trees. You first need to select the type
9754 of match used to create the tree:
9756 t Show entries with a specific TODO keyword.
9757 m Show entries selected by a tags/property match.
9758 p Enter a property name and its value (both with completion on existing
9759 names/values) and show entries with that property.
9760 r Show entries matching a regular expression.
9761 d Show deadlines due within `org-deadline-warning-days'.
9762 b Show deadlines and scheduled items before a date.
9763 a Show deadlines and scheduled items after a date."
9764 (interactive "P")
9765 (let (ans kwd value)
9766 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
9767 (setq ans (read-char-exclusive))
9768 (cond
9769 ((equal ans ?d)
9770 (call-interactively 'org-check-deadlines))
9771 ((equal ans ?b)
9772 (call-interactively 'org-check-before-date))
9773 ((equal ans ?a)
9774 (call-interactively 'org-check-after-date))
9775 ((equal ans ?t)
9776 (org-show-todo-tree '(4)))
9777 ((member ans '(?T ?m))
9778 (call-interactively 'org-match-sparse-tree))
9779 ((member ans '(?p ?P))
9780 (setq kwd (org-ido-completing-read "Property: "
9781 (mapcar 'list (org-buffer-property-keys))))
9782 (setq value (org-ido-completing-read "Value: "
9783 (mapcar 'list (org-property-values kwd))))
9784 (unless (string-match "\\`{.*}\\'" value)
9785 (setq value (concat "\"" value "\"")))
9786 (org-match-sparse-tree arg (concat kwd "=" value)))
9787 ((member ans '(?r ?R ?/))
9788 (call-interactively 'org-occur))
9789 (t (error "No such sparse tree command \"%c\"" ans)))))
9791 (defvar org-occur-highlights nil
9792 "List of overlays used for occur matches.")
9793 (make-variable-buffer-local 'org-occur-highlights)
9794 (defvar org-occur-parameters nil
9795 "Parameters of the active org-occur calls.
9796 This is a list, each call to org-occur pushes as cons cell,
9797 containing the regular expression and the callback, onto the list.
9798 The list can contain several entries if `org-occur' has been called
9799 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9800 will only contain one set of parameters. When the highlights are
9801 removed (for example with `C-c C-c', or with the next edit (depending
9802 on `org-remove-highlights-with-change'), this variable is emptied
9803 as well.")
9804 (make-variable-buffer-local 'org-occur-parameters)
9806 (defun org-occur (regexp &optional keep-previous callback)
9807 "Make a compact tree which shows all matches of REGEXP.
9808 The tree will show the lines where the regexp matches, and all higher
9809 headlines above the match. It will also show the heading after the match,
9810 to make sure editing the matching entry is easy.
9811 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9812 call to `org-occur' will be kept, to allow stacking of calls to this
9813 command.
9814 If CALLBACK is non-nil, it is a function which is called to confirm
9815 that the match should indeed be shown."
9816 (interactive "sRegexp: \nP")
9817 (unless keep-previous
9818 (org-remove-occur-highlights nil nil t))
9819 (push (cons regexp callback) org-occur-parameters)
9820 (let ((cnt 0))
9821 (save-excursion
9822 (goto-char (point-min))
9823 (if (or (not keep-previous) ; do not want to keep
9824 (not org-occur-highlights)) ; no previous matches
9825 ;; hide everything
9826 (org-overview))
9827 (while (re-search-forward regexp nil t)
9828 (when (or (not callback)
9829 (save-match-data (funcall callback)))
9830 (setq cnt (1+ cnt))
9831 (when org-highlight-sparse-tree-matches
9832 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9833 (org-show-context 'occur-tree))))
9834 (when org-remove-highlights-with-change
9835 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9836 nil 'local))
9837 (unless org-sparse-tree-open-archived-trees
9838 (org-hide-archived-subtrees (point-min) (point-max)))
9839 (run-hooks 'org-occur-hook)
9840 (if (interactive-p)
9841 (message "%d match(es) for regexp %s" cnt regexp))
9842 cnt))
9844 (defun org-show-context (&optional key)
9845 "Make sure point and context and visible.
9846 How much context is shown depends upon the variables
9847 `org-show-hierarchy-above', `org-show-following-heading'. and
9848 `org-show-siblings'."
9849 (let ((heading-p (org-on-heading-p t))
9850 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9851 (following-p (org-get-alist-option org-show-following-heading key))
9852 (entry-p (org-get-alist-option org-show-entry-below key))
9853 (siblings-p (org-get-alist-option org-show-siblings key)))
9854 (catch 'exit
9855 ;; Show heading or entry text
9856 (if (and heading-p (not entry-p))
9857 (org-flag-heading nil) ; only show the heading
9858 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9859 (org-show-hidden-entry))) ; show entire entry
9860 (when following-p
9861 ;; Show next sibling, or heading below text
9862 (save-excursion
9863 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9864 (org-flag-heading nil))))
9865 (when siblings-p (org-show-siblings))
9866 (when hierarchy-p
9867 ;; show all higher headings, possibly with siblings
9868 (save-excursion
9869 (while (and (condition-case nil
9870 (progn (org-up-heading-all 1) t)
9871 (error nil))
9872 (not (bobp)))
9873 (org-flag-heading nil)
9874 (when siblings-p (org-show-siblings))))))))
9876 (defun org-reveal (&optional siblings)
9877 "Show current entry, hierarchy above it, and the following headline.
9878 This can be used to show a consistent set of context around locations
9879 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9880 not t for the search context.
9882 With optional argument SIBLINGS, on each level of the hierarchy all
9883 siblings are shown. This repairs the tree structure to what it would
9884 look like when opened with hierarchical calls to `org-cycle'."
9885 (interactive "P")
9886 (let ((org-show-hierarchy-above t)
9887 (org-show-following-heading t)
9888 (org-show-siblings (if siblings t org-show-siblings)))
9889 (org-show-context nil)))
9891 (defun org-highlight-new-match (beg end)
9892 "Highlight from BEG to END and mark the highlight is an occur headline."
9893 (let ((ov (org-make-overlay beg end)))
9894 (org-overlay-put ov 'face 'secondary-selection)
9895 (push ov org-occur-highlights)))
9897 (defun org-remove-occur-highlights (&optional beg end noremove)
9898 "Remove the occur highlights from the buffer.
9899 BEG and END are ignored. If NOREMOVE is nil, remove this function
9900 from the `before-change-functions' in the current buffer."
9901 (interactive)
9902 (unless org-inhibit-highlight-removal
9903 (mapc 'org-delete-overlay org-occur-highlights)
9904 (setq org-occur-highlights nil)
9905 (setq org-occur-parameters nil)
9906 (unless noremove
9907 (remove-hook 'before-change-functions
9908 'org-remove-occur-highlights 'local))))
9910 ;;;; Priorities
9912 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9913 "Regular expression matching the priority indicator.")
9915 (defvar org-remove-priority-next-time nil)
9917 (defun org-priority-up ()
9918 "Increase the priority of the current item."
9919 (interactive)
9920 (org-priority 'up))
9922 (defun org-priority-down ()
9923 "Decrease the priority of the current item."
9924 (interactive)
9925 (org-priority 'down))
9927 (defun org-priority (&optional action)
9928 "Change the priority of an item by ARG.
9929 ACTION can be `set', `up', `down', or a character."
9930 (interactive)
9931 (setq action (or action 'set))
9932 (let (current new news have remove)
9933 (save-excursion
9934 (org-back-to-heading t)
9935 (if (looking-at org-priority-regexp)
9936 (setq current (string-to-char (match-string 2))
9937 have t)
9938 (setq current org-default-priority))
9939 (cond
9940 ((or (eq action 'set)
9941 (if (featurep 'xemacs) (characterp action) (integerp action)))
9942 (if (not (eq action 'set))
9943 (setq new action)
9944 (message "Priority %c-%c, SPC to remove: "
9945 org-highest-priority org-lowest-priority)
9946 (setq new (read-char-exclusive)))
9947 (if (and (= (upcase org-highest-priority) org-highest-priority)
9948 (= (upcase org-lowest-priority) org-lowest-priority))
9949 (setq new (upcase new)))
9950 (cond ((equal new ?\ ) (setq remove t))
9951 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9952 (error "Priority must be between `%c' and `%c'"
9953 org-highest-priority org-lowest-priority))))
9954 ((eq action 'up)
9955 (if (and (not have) (eq last-command this-command))
9956 (setq new org-lowest-priority)
9957 (setq new (if (and org-priority-start-cycle-with-default (not have))
9958 org-default-priority (1- current)))))
9959 ((eq action 'down)
9960 (if (and (not have) (eq last-command this-command))
9961 (setq new org-highest-priority)
9962 (setq new (if (and org-priority-start-cycle-with-default (not have))
9963 org-default-priority (1+ current)))))
9964 (t (error "Invalid action")))
9965 (if (or (< (upcase new) org-highest-priority)
9966 (> (upcase new) org-lowest-priority))
9967 (setq remove t))
9968 (setq news (format "%c" new))
9969 (if have
9970 (if remove
9971 (replace-match "" t t nil 1)
9972 (replace-match news t t nil 2))
9973 (if remove
9974 (error "No priority cookie found in line")
9975 (looking-at org-todo-line-regexp)
9976 (if (match-end 2)
9977 (progn
9978 (goto-char (match-end 2))
9979 (insert " [#" news "]"))
9980 (goto-char (match-beginning 3))
9981 (insert "[#" news "] ")))))
9982 (org-preserve-lc (org-set-tags nil 'align))
9983 (if remove
9984 (message "Priority removed")
9985 (message "Priority of current item set to %s" news))))
9988 (defun org-get-priority (s)
9989 "Find priority cookie and return priority."
9990 (save-match-data
9991 (if (not (string-match org-priority-regexp s))
9992 (* 1000 (- org-lowest-priority org-default-priority))
9993 (* 1000 (- org-lowest-priority
9994 (string-to-char (match-string 2 s)))))))
9996 ;;;; Tags
9998 (defvar org-agenda-archives-mode)
9999 (defvar org-map-continue-from nil
10000 "Position from where mapping should continue.
10001 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10003 (defvar org-scanner-tags nil
10004 "The current tag list while the tags scanner is running.")
10005 (defvar org-trust-scanner-tags nil
10006 "Should `org-get-tags-at' use the tags fro the scanner.
10007 This is for internal dynamical scoping only.
10008 When this is non-nil, the function `org-get-tags-at' will return the value
10009 of `org-scanner-tags' instead of building the list by itself. This
10010 can lead to large speed-ups when the tags scanner is used in a file with
10011 many entries, and when the list of tags is retrieved, for example to
10012 obtain a list of properties. Building the tags list for each entry in such
10013 a file becomes an N^2 operation - but with this variable set, it scales
10014 as N.")
10016 (defun org-scan-tags (action matcher &optional todo-only)
10017 "Scan headline tags with inheritance and produce output ACTION.
10019 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10020 or `agenda' to produce an entry list for an agenda view. It can also be
10021 a Lisp form or a function that should be called at each matched headline, in
10022 this case the return value is a list of all return values from these calls.
10024 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10025 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10026 only lines with a TODO keyword are included in the output."
10027 (require 'org-agenda)
10028 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10029 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10030 (org-re
10031 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10032 (props (list 'face 'default
10033 'done-face 'org-agenda-done
10034 'undone-face 'default
10035 'mouse-face 'highlight
10036 'org-not-done-regexp org-not-done-regexp
10037 'org-todo-regexp org-todo-regexp
10038 'keymap org-agenda-keymap
10039 'help-echo
10040 (format "mouse-2 or RET jump to org file %s"
10041 (abbreviate-file-name
10042 (or (buffer-file-name (buffer-base-buffer))
10043 (buffer-name (buffer-base-buffer)))))))
10044 (case-fold-search nil)
10045 (org-map-continue-from nil)
10046 lspos tags tags-list
10047 (tags-alist (list (cons 0 org-file-tags)))
10048 (llast 0) rtn rtn1 level category i txt
10049 todo marker entry priority)
10050 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10051 (setq action (list 'lambda nil action)))
10052 (save-excursion
10053 (goto-char (point-min))
10054 (when (eq action 'sparse-tree)
10055 (org-overview)
10056 (org-remove-occur-highlights))
10057 (while (re-search-forward re nil t)
10058 (catch :skip
10059 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10060 tags (if (match-end 4) (org-match-string-no-properties 4)))
10061 (goto-char (setq lspos (1+ (match-beginning 0))))
10062 (setq level (org-reduced-level (funcall outline-level))
10063 category (org-get-category))
10064 (setq i llast llast level)
10065 ;; remove tag lists from same and sublevels
10066 (while (>= i level)
10067 (when (setq entry (assoc i tags-alist))
10068 (setq tags-alist (delete entry tags-alist)))
10069 (setq i (1- i)))
10070 ;; add the next tags
10071 (when tags
10072 (setq tags (org-split-string tags ":")
10073 tags-alist
10074 (cons (cons level tags) tags-alist)))
10075 ;; compile tags for current headline
10076 (setq tags-list
10077 (if org-use-tag-inheritance
10078 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10079 tags)
10080 org-scanner-tags tags-list)
10081 (when org-use-tag-inheritance
10082 (setcdr (car tags-alist)
10083 (mapcar (lambda (x)
10084 (setq x (copy-sequence x))
10085 (org-add-prop-inherited x))
10086 (cdar tags-alist))))
10087 (when (and tags org-use-tag-inheritance
10088 (or (not (eq t org-use-tag-inheritance))
10089 org-tags-exclude-from-inheritance))
10090 ;; selective inheritance, remove uninherited ones
10091 (setcdr (car tags-alist)
10092 (org-remove-uniherited-tags (cdar tags-alist))))
10093 (when (and (or (not todo-only)
10094 (and (member todo org-not-done-keywords)
10095 (or (not org-agenda-tags-todo-honor-ignore-options)
10096 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10097 (let ((case-fold-search t)) (eval matcher))
10099 (not (member org-archive-tag tags-list))
10100 ;; we have an archive tag, should we use this anyway?
10101 (or (not org-agenda-skip-archived-trees)
10102 (and (eq action 'agenda) org-agenda-archives-mode))))
10103 (unless (eq action 'sparse-tree) (org-agenda-skip))
10105 ;; select this headline
10107 (cond
10108 ((eq action 'sparse-tree)
10109 (and org-highlight-sparse-tree-matches
10110 (org-get-heading) (match-end 0)
10111 (org-highlight-new-match
10112 (match-beginning 0) (match-beginning 1)))
10113 (org-show-context 'tags-tree))
10114 ((eq action 'agenda)
10115 (setq txt (org-format-agenda-item
10117 (concat
10118 (if (eq org-tags-match-list-sublevels 'indented)
10119 (make-string (1- level) ?.) "")
10120 (org-get-heading))
10121 category
10122 tags-list
10124 priority (org-get-priority txt))
10125 (goto-char lspos)
10126 (setq marker (org-agenda-new-marker))
10127 (org-add-props txt props
10128 'org-marker marker 'org-hd-marker marker 'org-category category
10129 'todo-state todo
10130 'priority priority 'type "tagsmatch")
10131 (push txt rtn))
10132 ((functionp action)
10133 (setq org-map-continue-from nil)
10134 (save-excursion
10135 (setq rtn1 (funcall action))
10136 (push rtn1 rtn)))
10137 (t (error "Invalid action")))
10139 ;; if we are to skip sublevels, jump to end of subtree
10140 (unless org-tags-match-list-sublevels
10141 (org-end-of-subtree t)
10142 (backward-char 1))))
10143 ;; Get the correct position from where to continue
10144 (if org-map-continue-from
10145 (goto-char org-map-continue-from)
10146 (and (= (point) lspos) (end-of-line 1)))))
10147 (when (and (eq action 'sparse-tree)
10148 (not org-sparse-tree-open-archived-trees))
10149 (org-hide-archived-subtrees (point-min) (point-max)))
10150 (nreverse rtn)))
10152 (defun org-remove-uniherited-tags (tags)
10153 "Remove all tags that are not inherited from the list TAGS."
10154 (cond
10155 ((eq org-use-tag-inheritance t)
10156 (if org-tags-exclude-from-inheritance
10157 (org-delete-all org-tags-exclude-from-inheritance tags)
10158 tags))
10159 ((not org-use-tag-inheritance) nil)
10160 ((stringp org-use-tag-inheritance)
10161 (delq nil (mapcar
10162 (lambda (x)
10163 (if (and (string-match org-use-tag-inheritance x)
10164 (not (member x org-tags-exclude-from-inheritance)))
10165 x nil))
10166 tags)))
10167 ((listp org-use-tag-inheritance)
10168 (delq nil (mapcar
10169 (lambda (x)
10170 (if (member x org-use-tag-inheritance) x nil))
10171 tags)))))
10173 (defvar todo-only) ;; dynamically scoped
10175 (defun org-match-sparse-tree (&optional todo-only match)
10176 "Create a sparse tree according to tags string MATCH.
10177 MATCH can contain positive and negative selection of tags, like
10178 \"+WORK+URGENT-WITHBOSS\".
10179 If optional argument TODO-ONLY is non-nil, only select lines that are
10180 also TODO lines."
10181 (interactive "P")
10182 (org-prepare-agenda-buffers (list (current-buffer)))
10183 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10185 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10187 (defvar org-cached-props nil)
10188 (defun org-cached-entry-get (pom property)
10189 (if (or (eq t org-use-property-inheritance)
10190 (and (stringp org-use-property-inheritance)
10191 (string-match org-use-property-inheritance property))
10192 (and (listp org-use-property-inheritance)
10193 (member property org-use-property-inheritance)))
10194 ;; Caching is not possible, check it directly
10195 (org-entry-get pom property 'inherit)
10196 ;; Get all properties, so that we can do complicated checks easily
10197 (cdr (assoc property (or org-cached-props
10198 (setq org-cached-props
10199 (org-entry-properties pom)))))))
10201 (defun org-global-tags-completion-table (&optional files)
10202 "Return the list of all tags in all agenda buffer/files."
10203 (save-excursion
10204 (org-uniquify
10205 (delq nil
10206 (apply 'append
10207 (mapcar
10208 (lambda (file)
10209 (set-buffer (find-file-noselect file))
10210 (append (org-get-buffer-tags)
10211 (mapcar (lambda (x) (if (stringp (car-safe x))
10212 (list (car-safe x)) nil))
10213 org-tag-alist)))
10214 (if (and files (car files))
10215 files
10216 (org-agenda-files))))))))
10218 (defun org-make-tags-matcher (match)
10219 "Create the TAGS//TODO matcher form for the selection string MATCH."
10220 ;; todo-only is scoped dynamically into this function, and the function
10221 ;; may change it if the matcher asks for it.
10222 (unless match
10223 ;; Get a new match request, with completion
10224 (let ((org-last-tags-completion-table
10225 (org-global-tags-completion-table)))
10226 (setq match (org-completing-read-no-ido
10227 "Match: " 'org-tags-completion-function nil nil nil
10228 'org-tags-history))))
10230 ;; Parse the string and create a lisp form
10231 (let ((match0 match)
10232 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10233 minus tag mm
10234 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10235 orterms term orlist re-p str-p level-p level-op time-p
10236 prop-p pn pv po cat-p gv rest)
10237 (if (string-match "/+" match)
10238 ;; match contains also a todo-matching request
10239 (progn
10240 (setq tagsmatch (substring match 0 (match-beginning 0))
10241 todomatch (substring match (match-end 0)))
10242 (if (string-match "^!" todomatch)
10243 (setq todo-only t todomatch (substring todomatch 1)))
10244 (if (string-match "^\\s-*$" todomatch)
10245 (setq todomatch nil)))
10246 ;; only matching tags
10247 (setq tagsmatch match todomatch nil))
10249 ;; Make the tags matcher
10250 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10251 (setq tagsmatcher t)
10252 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10253 (while (setq term (pop orterms))
10254 (while (and (equal (substring term -1) "\\") orterms)
10255 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10256 (while (string-match re term)
10257 (setq rest (substring term (match-end 0))
10258 minus (and (match-end 1)
10259 (equal (match-string 1 term) "-"))
10260 tag (match-string 2 term)
10261 re-p (equal (string-to-char tag) ?{)
10262 level-p (match-end 4)
10263 prop-p (match-end 5)
10264 mm (cond
10265 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10266 (level-p
10267 (setq level-op (org-op-to-function (match-string 3 term)))
10268 `(,level-op level ,(string-to-number
10269 (match-string 4 term))))
10270 (prop-p
10271 (setq pn (match-string 5 term)
10272 po (match-string 6 term)
10273 pv (match-string 7 term)
10274 cat-p (equal pn "CATEGORY")
10275 re-p (equal (string-to-char pv) ?{)
10276 str-p (equal (string-to-char pv) ?\")
10277 time-p (save-match-data
10278 (string-match "^\"[[<].*[]>]\"$" pv))
10279 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10280 (if time-p (setq pv (org-matcher-time pv)))
10281 (setq po (org-op-to-function po (if time-p 'time str-p)))
10282 (cond
10283 ((equal pn "CATEGORY")
10284 (setq gv '(get-text-property (point) 'org-category)))
10285 ((equal pn "TODO")
10286 (setq gv 'todo))
10288 (setq gv `(org-cached-entry-get nil ,pn))))
10289 (if re-p
10290 (if (eq po 'org<>)
10291 `(not (string-match ,pv (or ,gv "")))
10292 `(string-match ,pv (or ,gv "")))
10293 (if str-p
10294 `(,po (or ,gv "") ,pv)
10295 `(,po (string-to-number (or ,gv ""))
10296 ,(string-to-number pv) ))))
10297 (t `(member ,tag tags-list)))
10298 mm (if minus (list 'not mm) mm)
10299 term rest)
10300 (push mm tagsmatcher))
10301 (push (if (> (length tagsmatcher) 1)
10302 (cons 'and tagsmatcher)
10303 (car tagsmatcher))
10304 orlist)
10305 (setq tagsmatcher nil))
10306 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10307 (setq tagsmatcher
10308 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10309 ;; Make the todo matcher
10310 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10311 (setq todomatcher t)
10312 (setq orterms (org-split-string todomatch "|") orlist nil)
10313 (while (setq term (pop orterms))
10314 (while (string-match re term)
10315 (setq minus (and (match-end 1)
10316 (equal (match-string 1 term) "-"))
10317 kwd (match-string 2 term)
10318 re-p (equal (string-to-char kwd) ?{)
10319 term (substring term (match-end 0))
10320 mm (if re-p
10321 `(string-match ,(substring kwd 1 -1) todo)
10322 (list 'equal 'todo kwd))
10323 mm (if minus (list 'not mm) mm))
10324 (push mm todomatcher))
10325 (push (if (> (length todomatcher) 1)
10326 (cons 'and todomatcher)
10327 (car todomatcher))
10328 orlist)
10329 (setq todomatcher nil))
10330 (setq todomatcher (if (> (length orlist) 1)
10331 (cons 'or orlist) (car orlist))))
10333 ;; Return the string and lisp forms of the matcher
10334 (setq matcher (if todomatcher
10335 (list 'and tagsmatcher todomatcher)
10336 tagsmatcher))
10337 (cons match0 matcher)))
10339 (defun org-op-to-function (op &optional stringp)
10340 "Turn an operator into the appropriate function."
10341 (setq op
10342 (cond
10343 ((equal op "<" ) '(< string< org-time<))
10344 ((equal op ">" ) '(> org-string> org-time>))
10345 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10346 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10347 ((member op '("=" "==")) '(= string= org-time=))
10348 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10349 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10351 (defun org<> (a b) (not (= a b)))
10352 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10353 (defun org-string>= (a b) (not (string< a b)))
10354 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10355 (defun org-string<> (a b) (not (string= a b)))
10356 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10357 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10358 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10359 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10360 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10361 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10362 (defun org-2ft (s)
10363 "Convert S to a floating point time.
10364 If S is already a number, just return it. If it is a string, parse
10365 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10366 (cond
10367 ((numberp s) s)
10368 ((stringp s)
10369 (condition-case nil
10370 (float-time (apply 'encode-time (org-parse-time-string s)))
10371 (error 0.)))
10372 (t 0.)))
10374 (defun org-time-today ()
10375 "Time in seconds today at 0:00.
10376 Returns the float number of seconds since the beginning of the
10377 epoch to the beginning of today (00:00)."
10378 (float-time (apply 'encode-time
10379 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10381 (defun org-matcher-time (s)
10382 "Interpret a time comparison value."
10383 (save-match-data
10384 (cond
10385 ((string= s "<now>") (float-time))
10386 ((string= s "<today>") (org-time-today))
10387 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10388 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10389 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10390 (+ (org-time-today)
10391 (* (string-to-number (match-string 1 s))
10392 (cdr (assoc (match-string 2 s)
10393 '(("d" . 86400.0) ("w" . 604800.0)
10394 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10395 (t (org-2ft s)))))
10397 (defun org-match-any-p (re list)
10398 "Does re match any element of list?"
10399 (setq list (mapcar (lambda (x) (string-match re x)) list))
10400 (delq nil list))
10402 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10403 (defvar org-tags-overlay (org-make-overlay 1 1))
10404 (org-detach-overlay org-tags-overlay)
10406 (defun org-get-local-tags-at (&optional pos)
10407 "Get a list of tags defined in the current headline."
10408 (org-get-tags-at pos 'local))
10410 (defun org-get-local-tags ()
10411 "Get a list of tags defined in the current headline."
10412 (org-get-tags-at nil 'local))
10414 (defun org-get-tags-at (&optional pos local)
10415 "Get a list of all headline tags applicable at POS.
10416 POS defaults to point. If tags are inherited, the list contains
10417 the targets in the same sequence as the headlines appear, i.e.
10418 the tags of the current headline come last.
10419 When LOCAL is non-nil, only return tags from the current headline,
10420 ignore inherited ones."
10421 (interactive)
10422 (if (and org-trust-scanner-tags
10423 (or (not pos) (equal pos (point)))
10424 (not local))
10425 org-scanner-tags
10426 (let (tags ltags lastpos parent)
10427 (save-excursion
10428 (save-restriction
10429 (widen)
10430 (goto-char (or pos (point)))
10431 (save-match-data
10432 (catch 'done
10433 (condition-case nil
10434 (progn
10435 (org-back-to-heading t)
10436 (while (not (equal lastpos (point)))
10437 (setq lastpos (point))
10438 (when (looking-at
10439 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10440 (setq ltags (org-split-string
10441 (org-match-string-no-properties 1) ":"))
10442 (when parent
10443 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10444 (setq tags (append
10445 (if parent
10446 (org-remove-uniherited-tags ltags)
10447 ltags)
10448 tags)))
10449 (or org-use-tag-inheritance (throw 'done t))
10450 (if local (throw 'done t))
10451 (org-up-heading-all 1)
10452 (setq parent t)))
10453 (error nil)))))
10454 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10456 (defun org-add-prop-inherited (s)
10457 (add-text-properties 0 (length s) '(inherited t) s)
10460 (defun org-toggle-tag (tag &optional onoff)
10461 "Toggle the tag TAG for the current line.
10462 If ONOFF is `on' or `off', don't toggle but set to this state."
10463 (let (res current)
10464 (save-excursion
10465 (org-back-to-heading t)
10466 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10467 (point-at-eol) t)
10468 (progn
10469 (setq current (match-string 1))
10470 (replace-match ""))
10471 (setq current ""))
10472 (setq current (nreverse (org-split-string current ":")))
10473 (cond
10474 ((eq onoff 'on)
10475 (setq res t)
10476 (or (member tag current) (push tag current)))
10477 ((eq onoff 'off)
10478 (or (not (member tag current)) (setq current (delete tag current))))
10479 (t (if (member tag current)
10480 (setq current (delete tag current))
10481 (setq res t)
10482 (push tag current))))
10483 (end-of-line 1)
10484 (if current
10485 (progn
10486 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10487 (org-set-tags nil t))
10488 (delete-horizontal-space))
10489 (run-hooks 'org-after-tags-change-hook))
10490 res))
10492 (defun org-align-tags-here (to-col)
10493 ;; Assumes that this is a headline
10494 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10495 (beginning-of-line 1)
10496 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10497 (< pos (match-beginning 2)))
10498 (progn
10499 (setq tags-l (- (match-end 2) (match-beginning 2)))
10500 (goto-char (match-beginning 1))
10501 (insert " ")
10502 (delete-region (point) (1+ (match-beginning 2)))
10503 (setq ncol (max (1+ (current-column))
10504 (1+ col)
10505 (if (> to-col 0)
10506 to-col
10507 (- (abs to-col) tags-l))))
10508 (setq p (point))
10509 (insert (make-string (- ncol (current-column)) ?\ ))
10510 (setq ncol (current-column))
10511 (when indent-tabs-mode (tabify p (point-at-eol)))
10512 (org-move-to-column (min ncol col) t))
10513 (goto-char pos))))
10515 (defun org-set-tags-command (&optional arg just-align)
10516 "Call the set-tags command for the current entry."
10517 (interactive "P")
10518 (if (org-on-heading-p)
10519 (org-set-tags arg just-align)
10520 (save-excursion
10521 (org-back-to-heading t)
10522 (org-set-tags arg just-align))))
10524 (defun org-set-tags (&optional arg just-align)
10525 "Set the tags for the current headline.
10526 With prefix ARG, realign all tags in headings in the current buffer."
10527 (interactive "P")
10528 (let* ((re (concat "^" outline-regexp))
10529 (current (org-get-tags-string))
10530 (col (current-column))
10531 (org-setting-tags t)
10532 table current-tags inherited-tags ; computed below when needed
10533 tags p0 c0 c1 rpl)
10534 (if arg
10535 (save-excursion
10536 (goto-char (point-min))
10537 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10538 (while (re-search-forward re nil t)
10539 (org-set-tags nil t)
10540 (end-of-line 1)))
10541 (message "All tags realigned to column %d" org-tags-column))
10542 (if just-align
10543 (setq tags current)
10544 ;; Get a new set of tags from the user
10545 (save-excursion
10546 (setq table (append org-tag-persistent-alist
10547 (or org-tag-alist (org-get-buffer-tags)))
10548 org-last-tags-completion-table table
10549 current-tags (org-split-string current ":")
10550 inherited-tags (nreverse
10551 (nthcdr (length current-tags)
10552 (nreverse (org-get-tags-at))))
10553 tags
10554 (if (or (eq t org-use-fast-tag-selection)
10555 (and org-use-fast-tag-selection
10556 (delq nil (mapcar 'cdr table))))
10557 (org-fast-tag-selection
10558 current-tags inherited-tags table
10559 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10560 (let ((org-add-colon-after-tag-completion t))
10561 (org-trim
10562 (org-without-partial-completion
10563 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10564 nil nil current 'org-tags-history)))))))
10565 (while (string-match "[-+&]+" tags)
10566 ;; No boolean logic, just a list
10567 (setq tags (replace-match ":" t t tags))))
10569 (if (string-match "\\`[\t ]*\\'" tags)
10570 (setq tags "")
10571 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10572 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10574 ;; Insert new tags at the correct column
10575 (beginning-of-line 1)
10576 (cond
10577 ((and (equal current "") (equal tags "")))
10578 ((re-search-forward
10579 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10580 (point-at-eol) t)
10581 (if (equal tags "")
10582 (setq rpl "")
10583 (goto-char (match-beginning 0))
10584 (setq c0 (current-column) p0 (point)
10585 c1 (max (1+ c0) (if (> org-tags-column 0)
10586 org-tags-column
10587 (- (- org-tags-column) (length tags))))
10588 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10589 (replace-match rpl t t)
10590 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10591 tags)
10592 (t (error "Tags alignment failed")))
10593 (org-move-to-column col)
10594 (unless just-align
10595 (run-hooks 'org-after-tags-change-hook)))))
10597 (defun org-change-tag-in-region (beg end tag off)
10598 "Add or remove TAG for each entry in the region.
10599 This works in the agenda, and also in an org-mode buffer."
10600 (interactive
10601 (list (region-beginning) (region-end)
10602 (let ((org-last-tags-completion-table
10603 (if (org-mode-p)
10604 (org-get-buffer-tags)
10605 (org-global-tags-completion-table))))
10606 (org-ido-completing-read
10607 "Tag: " 'org-tags-completion-function nil nil nil
10608 'org-tags-history))
10609 (progn
10610 (message "[s]et or [r]emove? ")
10611 (equal (read-char-exclusive) ?r))))
10612 (if (fboundp 'deactivate-mark) (deactivate-mark))
10613 (let ((agendap (equal major-mode 'org-agenda-mode))
10614 l1 l2 m buf pos newhead (cnt 0))
10615 (goto-char end)
10616 (setq l2 (1- (org-current-line)))
10617 (goto-char beg)
10618 (setq l1 (org-current-line))
10619 (loop for l from l1 to l2 do
10620 (goto-line l)
10621 (setq m (get-text-property (point) 'org-hd-marker))
10622 (when (or (and (org-mode-p) (org-on-heading-p))
10623 (and agendap m))
10624 (setq buf (if agendap (marker-buffer m) (current-buffer))
10625 pos (if agendap m (point)))
10626 (with-current-buffer buf
10627 (save-excursion
10628 (save-restriction
10629 (goto-char pos)
10630 (setq cnt (1+ cnt))
10631 (org-toggle-tag tag (if off 'off 'on))
10632 (setq newhead (org-get-heading)))))
10633 (and agendap (org-agenda-change-all-lines newhead m))))
10634 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10636 (defun org-tags-completion-function (string predicate &optional flag)
10637 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10638 (confirm (lambda (x) (stringp (car x)))))
10639 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10640 (setq s1 (match-string 1 string)
10641 s2 (match-string 2 string))
10642 (setq s1 "" s2 string))
10643 (cond
10644 ((eq flag nil)
10645 ;; try completion
10646 (setq rtn (try-completion s2 ctable confirm))
10647 (if (stringp rtn)
10648 (setq rtn
10649 (concat s1 s2 (substring rtn (length s2))
10650 (if (and org-add-colon-after-tag-completion
10651 (assoc rtn ctable))
10652 ":" ""))))
10653 rtn)
10654 ((eq flag t)
10655 ;; all-completions
10656 (all-completions s2 ctable confirm)
10658 ((eq flag 'lambda)
10659 ;; exact match?
10660 (assoc s2 ctable)))
10663 (defun org-fast-tag-insert (kwd tags face &optional end)
10664 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10665 (insert (format "%-12s" (concat kwd ":"))
10666 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10667 (or end "")))
10669 (defun org-fast-tag-show-exit (flag)
10670 (save-excursion
10671 (goto-line 3)
10672 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10673 (replace-match ""))
10674 (when flag
10675 (end-of-line 1)
10676 (org-move-to-column (- (window-width) 19) t)
10677 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10679 (defun org-set-current-tags-overlay (current prefix)
10680 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10681 (if (featurep 'xemacs)
10682 (org-overlay-display org-tags-overlay (concat prefix s)
10683 'secondary-selection)
10684 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10685 (org-overlay-display org-tags-overlay (concat prefix s)))))
10687 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10688 "Fast tag selection with single keys.
10689 CURRENT is the current list of tags in the headline, INHERITED is the
10690 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10691 possibly with grouping information. TODO-TABLE is a similar table with
10692 TODO keywords, should these have keys assigned to them.
10693 If the keys are nil, a-z are automatically assigned.
10694 Returns the new tags string, or nil to not change the current settings."
10695 (let* ((fulltable (append table todo-table))
10696 (maxlen (apply 'max (mapcar
10697 (lambda (x)
10698 (if (stringp (car x)) (string-width (car x)) 0))
10699 fulltable)))
10700 (buf (current-buffer))
10701 (expert (eq org-fast-tag-selection-single-key 'expert))
10702 (buffer-tags nil)
10703 (fwidth (+ maxlen 3 1 3))
10704 (ncol (/ (- (window-width) 4) fwidth))
10705 (i-face 'org-done)
10706 (c-face 'org-todo)
10707 tg cnt e c char c1 c2 ntable tbl rtn
10708 ov-start ov-end ov-prefix
10709 (exit-after-next org-fast-tag-selection-single-key)
10710 (done-keywords org-done-keywords)
10711 groups ingroup)
10712 (save-excursion
10713 (beginning-of-line 1)
10714 (if (looking-at
10715 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10716 (setq ov-start (match-beginning 1)
10717 ov-end (match-end 1)
10718 ov-prefix "")
10719 (setq ov-start (1- (point-at-eol))
10720 ov-end (1+ ov-start))
10721 (skip-chars-forward "^\n\r")
10722 (setq ov-prefix
10723 (concat
10724 (buffer-substring (1- (point)) (point))
10725 (if (> (current-column) org-tags-column)
10727 (make-string (- org-tags-column (current-column)) ?\ ))))))
10728 (org-move-overlay org-tags-overlay ov-start ov-end)
10729 (save-window-excursion
10730 (if expert
10731 (set-buffer (get-buffer-create " *Org tags*"))
10732 (delete-other-windows)
10733 (split-window-vertically)
10734 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10735 (erase-buffer)
10736 (org-set-local 'org-done-keywords done-keywords)
10737 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10738 (org-fast-tag-insert "Current" current c-face "\n\n")
10739 (org-fast-tag-show-exit exit-after-next)
10740 (org-set-current-tags-overlay current ov-prefix)
10741 (setq tbl fulltable char ?a cnt 0)
10742 (while (setq e (pop tbl))
10743 (cond
10744 ((equal e '(:startgroup))
10745 (push '() groups) (setq ingroup t)
10746 (when (not (= cnt 0))
10747 (setq cnt 0)
10748 (insert "\n"))
10749 (insert "{ "))
10750 ((equal e '(:endgroup))
10751 (setq ingroup nil cnt 0)
10752 (insert "}\n"))
10753 ((equal e '(:newline))
10754 (when (not (= cnt 0))
10755 (setq cnt 0)
10756 (insert "\n")
10757 (setq e (car tbl))
10758 (while (equal (car tbl) '(:newline))
10759 (insert "\n")
10760 (setq tbl (cdr tbl)))))
10762 (setq tg (car e) c2 nil)
10763 (if (cdr e)
10764 (setq c (cdr e))
10765 ;; automatically assign a character.
10766 (setq c1 (string-to-char
10767 (downcase (substring
10768 tg (if (= (string-to-char tg) ?@) 1 0)))))
10769 (if (or (rassoc c1 ntable) (rassoc c1 table))
10770 (while (or (rassoc char ntable) (rassoc char table))
10771 (setq char (1+ char)))
10772 (setq c2 c1))
10773 (setq c (or c2 char)))
10774 (if ingroup (push tg (car groups)))
10775 (setq tg (org-add-props tg nil 'face
10776 (cond
10777 ((not (assoc tg table))
10778 (org-get-todo-face tg))
10779 ((member tg current) c-face)
10780 ((member tg inherited) i-face)
10781 (t nil))))
10782 (if (and (= cnt 0) (not ingroup)) (insert " "))
10783 (insert "[" c "] " tg (make-string
10784 (- fwidth 4 (length tg)) ?\ ))
10785 (push (cons tg c) ntable)
10786 (when (= (setq cnt (1+ cnt)) ncol)
10787 (insert "\n")
10788 (if ingroup (insert " "))
10789 (setq cnt 0)))))
10790 (setq ntable (nreverse ntable))
10791 (insert "\n")
10792 (goto-char (point-min))
10793 (if (not expert) (org-fit-window-to-buffer))
10794 (setq rtn
10795 (catch 'exit
10796 (while t
10797 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10798 (if groups " [!] no groups" " [!]groups")
10799 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10800 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10801 (cond
10802 ((= c ?\r) (throw 'exit t))
10803 ((= c ?!)
10804 (setq groups (not groups))
10805 (goto-char (point-min))
10806 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10807 ((= c ?\C-c)
10808 (if (not expert)
10809 (org-fast-tag-show-exit
10810 (setq exit-after-next (not exit-after-next)))
10811 (setq expert nil)
10812 (delete-other-windows)
10813 (split-window-vertically)
10814 (org-switch-to-buffer-other-window " *Org tags*")
10815 (org-fit-window-to-buffer)))
10816 ((or (= c ?\C-g)
10817 (and (= c ?q) (not (rassoc c ntable))))
10818 (org-detach-overlay org-tags-overlay)
10819 (setq quit-flag t))
10820 ((= c ?\ )
10821 (setq current nil)
10822 (if exit-after-next (setq exit-after-next 'now)))
10823 ((= c ?\t)
10824 (condition-case nil
10825 (setq tg (org-ido-completing-read
10826 "Tag: "
10827 (or buffer-tags
10828 (with-current-buffer buf
10829 (org-get-buffer-tags)))))
10830 (quit (setq tg "")))
10831 (when (string-match "\\S-" tg)
10832 (add-to-list 'buffer-tags (list tg))
10833 (if (member tg current)
10834 (setq current (delete tg current))
10835 (push tg current)))
10836 (if exit-after-next (setq exit-after-next 'now)))
10837 ((setq e (rassoc c todo-table) tg (car e))
10838 (with-current-buffer buf
10839 (save-excursion (org-todo tg)))
10840 (if exit-after-next (setq exit-after-next 'now)))
10841 ((setq e (rassoc c ntable) tg (car e))
10842 (if (member tg current)
10843 (setq current (delete tg current))
10844 (loop for g in groups do
10845 (if (member tg g)
10846 (mapc (lambda (x)
10847 (setq current (delete x current)))
10848 g)))
10849 (push tg current))
10850 (if exit-after-next (setq exit-after-next 'now))))
10852 ;; Create a sorted list
10853 (setq current
10854 (sort current
10855 (lambda (a b)
10856 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10857 (if (eq exit-after-next 'now) (throw 'exit t))
10858 (goto-char (point-min))
10859 (beginning-of-line 2)
10860 (delete-region (point) (point-at-eol))
10861 (org-fast-tag-insert "Current" current c-face)
10862 (org-set-current-tags-overlay current ov-prefix)
10863 (while (re-search-forward
10864 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10865 (setq tg (match-string 1))
10866 (add-text-properties
10867 (match-beginning 1) (match-end 1)
10868 (list 'face
10869 (cond
10870 ((member tg current) c-face)
10871 ((member tg inherited) i-face)
10872 (t (get-text-property (match-beginning 1) 'face))))))
10873 (goto-char (point-min)))))
10874 (org-detach-overlay org-tags-overlay)
10875 (if rtn
10876 (mapconcat 'identity current ":")
10877 nil))))
10879 (defun org-get-tags-string ()
10880 "Get the TAGS string in the current headline."
10881 (unless (org-on-heading-p t)
10882 (error "Not on a heading"))
10883 (save-excursion
10884 (beginning-of-line 1)
10885 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10886 (org-match-string-no-properties 1)
10887 "")))
10889 (defun org-get-tags ()
10890 "Get the list of tags specified in the current headline."
10891 (org-split-string (org-get-tags-string) ":"))
10893 (defun org-get-buffer-tags ()
10894 "Get a table of all tags used in the buffer, for completion."
10895 (let (tags)
10896 (save-excursion
10897 (goto-char (point-min))
10898 (while (re-search-forward
10899 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10900 (when (equal (char-after (point-at-bol 0)) ?*)
10901 (mapc (lambda (x) (add-to-list 'tags x))
10902 (org-split-string (org-match-string-no-properties 1) ":")))))
10903 (mapcar 'list tags)))
10905 ;;;; The mapping API
10907 ;;;###autoload
10908 (defun org-map-entries (func &optional match scope &rest skip)
10909 "Call FUNC at each headline selected by MATCH in SCOPE.
10911 FUNC is a function or a lisp form. The function will be called without
10912 arguments, with the cursor positioned at the beginning of the headline.
10913 The return values of all calls to the function will be collected and
10914 returned as a list.
10916 The call to FUNC will be wrapped into a save-excursion form, so FUNC
10917 does not need to preserve point. After evaluaton, the cursor will be
10918 moved to the end of the line (presumably of the headline of the
10919 processed entry) and search continues from there. Under some
10920 circumstances, this may not produce the wanted results. For example,
10921 if you have removed (e.g. archived) the current (sub)tree it could
10922 mean that the next entry will be skipped entirely. In such cases, you
10923 can specify the position from where search should continue by making
10924 FUNC set the variable `org-map-continue-from' to the desired buffer
10925 position.
10927 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10928 Only headlines that are matched by this query will be considered during
10929 the iteration. When MATCH is nil or t, all headlines will be
10930 visited by the iteration.
10932 SCOPE determines the scope of this command. It can be any of:
10934 nil The current buffer, respecting the restriction if any
10935 tree The subtree started with the entry at point
10936 file The current buffer, without restriction
10937 file-with-archives
10938 The current buffer, and any archives associated with it
10939 agenda All agenda files
10940 agenda-with-archives
10941 All agenda files with any archive files associated with them
10942 \(file1 file2 ...)
10943 If this is a list, all files in the list will be scanned
10945 The remaining args are treated as settings for the skipping facilities of
10946 the scanner. The following items can be given here:
10948 archive skip trees with the archive tag.
10949 comment skip trees with the COMMENT keyword
10950 function or Emacs Lisp form:
10951 will be used as value for `org-agenda-skip-function', so whenever
10952 the the function returns t, FUNC will not be called for that
10953 entry and search will continue from the point where the
10954 function leaves it.
10956 If your function needs to retrieve the tags including inherited tags
10957 at the *current* entry, you can use the value of the variable
10958 `org-scanner-tags' which will be much faster than getting the value
10959 with `org-get-tags-at'. If your function gets properties with
10960 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
10961 to t around the call to `org-entry-properties' to get the same speedup.
10962 Note that if your function moves around to retrieve tags and properties at
10963 a *different* entry, you cannot use these techniques."
10964 (let* ((org-agenda-archives-mode nil) ; just to make sure
10965 (org-agenda-skip-archived-trees (memq 'archive skip))
10966 (org-agenda-skip-comment-trees (memq 'comment skip))
10967 (org-agenda-skip-function
10968 (car (org-delete-all '(comment archive) skip)))
10969 (org-tags-match-list-sublevels t)
10970 matcher file res
10971 org-todo-keywords-for-agenda
10972 org-done-keywords-for-agenda
10973 org-todo-keyword-alist-for-agenda
10974 org-tag-alist-for-agenda)
10976 (cond
10977 ((eq match t) (setq matcher t))
10978 ((eq match nil) (setq matcher t))
10979 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10981 (save-excursion
10982 (save-restriction
10983 (when (eq scope 'tree)
10984 (org-back-to-heading t)
10985 (org-narrow-to-subtree)
10986 (setq scope nil))
10988 (if (not scope)
10989 (progn
10990 (org-prepare-agenda-buffers
10991 (list (buffer-file-name (current-buffer))))
10992 (setq res (org-scan-tags func matcher)))
10993 ;; Get the right scope
10994 (cond
10995 ((and scope (listp scope) (symbolp (car scope)))
10996 (setq scope (eval scope)))
10997 ((eq scope 'agenda)
10998 (setq scope (org-agenda-files t)))
10999 ((eq scope 'agenda-with-archives)
11000 (setq scope (org-agenda-files t))
11001 (setq scope (org-add-archive-files scope)))
11002 ((eq scope 'file)
11003 (setq scope (list (buffer-file-name))))
11004 ((eq scope 'file-with-archives)
11005 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11006 (org-prepare-agenda-buffers scope)
11007 (while (setq file (pop scope))
11008 (with-current-buffer (org-find-base-buffer-visiting file)
11009 (save-excursion
11010 (save-restriction
11011 (widen)
11012 (goto-char (point-min))
11013 (setq res (append res (org-scan-tags func matcher))))))))))
11014 res))
11016 ;;;; Properties
11018 ;;; Setting and retrieving properties
11020 (defconst org-special-properties
11021 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11022 "TIMESTAMP" "TIMESTAMP_IA")
11023 "The special properties valid in Org-mode.
11025 These are properties that are not defined in the property drawer,
11026 but in some other way.")
11028 (defconst org-default-properties
11029 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
11030 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11031 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11032 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
11033 "Some properties that are used by Org-mode for various purposes.
11034 Being in this list makes sure that they are offered for completion.")
11036 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11037 "Regular expression matching the first line of a property drawer.")
11039 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11040 "Regular expression matching the first line of a property drawer.")
11042 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11043 "Regular expression matching the first line of a property drawer.")
11045 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11046 "Regular expression matching the first line of a property drawer.")
11048 (defconst org-property-drawer-re
11049 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11050 org-property-end-re "\\)\n?")
11051 "Matches an entire property drawer.")
11053 (defconst org-clock-drawer-re
11054 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11055 org-property-end-re "\\)\n?")
11056 "Matches an entire clock drawer.")
11058 (defun org-property-action ()
11059 "Do an action on properties."
11060 (interactive)
11061 (let (c)
11062 (org-at-property-p)
11063 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11064 (setq c (read-char-exclusive))
11065 (cond
11066 ((equal c ?s)
11067 (call-interactively 'org-set-property))
11068 ((equal c ?d)
11069 (call-interactively 'org-delete-property))
11070 ((equal c ?D)
11071 (call-interactively 'org-delete-property-globally))
11072 ((equal c ?c)
11073 (call-interactively 'org-compute-property-at-point))
11074 (t (error "No such property action %c" c)))))
11076 (defun org-at-property-p ()
11077 "Is the cursor in a property line?"
11078 ;; FIXME: Does not check if we are actually in the drawer.
11079 ;; FIXME: also returns true on any drawers.....
11080 ;; This is used by C-c C-c for property action.
11081 (save-excursion
11082 (beginning-of-line 1)
11083 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11085 (defun org-get-property-block (&optional beg end force)
11086 "Return the (beg . end) range of the body of the property drawer.
11087 BEG and END can be beginning and end of subtree, if not given
11088 they will be found.
11089 If the drawer does not exist and FORCE is non-nil, create the drawer."
11090 (catch 'exit
11091 (save-excursion
11092 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11093 (end (or end (progn (outline-next-heading) (point)))))
11094 (goto-char beg)
11095 (if (re-search-forward org-property-start-re end t)
11096 (setq beg (1+ (match-end 0)))
11097 (if force
11098 (save-excursion
11099 (org-insert-property-drawer)
11100 (setq end (progn (outline-next-heading) (point))))
11101 (throw 'exit nil))
11102 (goto-char beg)
11103 (if (re-search-forward org-property-start-re end t)
11104 (setq beg (1+ (match-end 0)))))
11105 (if (re-search-forward org-property-end-re end t)
11106 (setq end (match-beginning 0))
11107 (or force (throw 'exit nil))
11108 (goto-char beg)
11109 (setq end beg)
11110 (org-indent-line-function)
11111 (insert ":END:\n"))
11112 (cons beg end)))))
11114 (defun org-entry-properties (&optional pom which)
11115 "Get all properties of the entry at point-or-marker POM.
11116 This includes the TODO keyword, the tags, time strings for deadline,
11117 scheduled, and clocking, and any additional properties defined in the
11118 entry. The return value is an alist, keys may occur multiple times
11119 if the property key was used several times.
11120 POM may also be nil, in which case the current entry is used.
11121 If WHICH is nil or `all', get all properties. If WHICH is
11122 `special' or `standard', only get that subclass."
11123 (setq which (or which 'all))
11124 (org-with-point-at pom
11125 (let ((clockstr (substring org-clock-string 0 -1))
11126 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11127 beg end range props sum-props key value string clocksum)
11128 (save-excursion
11129 (when (condition-case nil
11130 (and (org-mode-p) (org-back-to-heading t))
11131 (error nil))
11132 (setq beg (point))
11133 (setq sum-props (get-text-property (point) 'org-summaries))
11134 (setq clocksum (get-text-property (point) :org-clock-minutes))
11135 (outline-next-heading)
11136 (setq end (point))
11137 (when (memq which '(all special))
11138 ;; Get the special properties, like TODO and tags
11139 (goto-char beg)
11140 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11141 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11142 (when (looking-at org-priority-regexp)
11143 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11144 (when (and (setq value (org-get-tags-string))
11145 (string-match "\\S-" value))
11146 (push (cons "TAGS" value) props))
11147 (when (setq value (org-get-tags-at))
11148 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11149 props))
11150 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11151 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11152 string (if (equal key clockstr)
11153 (org-no-properties
11154 (org-trim
11155 (buffer-substring
11156 (match-beginning 3) (goto-char (point-at-eol)))))
11157 (substring (org-match-string-no-properties 3) 1 -1)))
11158 (unless key
11159 (if (= (char-after (match-beginning 3)) ?\[)
11160 (setq key "TIMESTAMP_IA")
11161 (setq key "TIMESTAMP")))
11162 (when (or (equal key clockstr) (not (assoc key props)))
11163 (push (cons key string) props)))
11167 (when (memq which '(all standard))
11168 ;; Get the standard properties, like :PROP: ...
11169 (setq range (org-get-property-block beg end))
11170 (when range
11171 (goto-char (car range))
11172 (while (re-search-forward
11173 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11174 (cdr range) t)
11175 (setq key (org-match-string-no-properties 1)
11176 value (org-trim (or (org-match-string-no-properties 2) "")))
11177 (unless (member key excluded)
11178 (push (cons key (or value "")) props)))))
11179 (if clocksum
11180 (push (cons "CLOCKSUM"
11181 (org-columns-number-to-string (/ (float clocksum) 60.)
11182 'add_times))
11183 props))
11184 (unless (assoc "CATEGORY" props)
11185 (setq value (or (org-get-category)
11186 (progn (org-refresh-category-properties)
11187 (org-get-category))))
11188 (push (cons "CATEGORY" value) props))
11189 (append sum-props (nreverse props)))))))
11191 (defun org-entry-get (pom property &optional inherit)
11192 "Get value of PROPERTY for entry at point-or-marker POM.
11193 If INHERIT is non-nil and the entry does not have the property,
11194 then also check higher levels of the hierarchy.
11195 If INHERIT is the symbol `selective', use inheritance only if the setting
11196 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11197 If the property is present but empty, the return value is the empty string.
11198 If the property is not present at all, nil is returned."
11199 (org-with-point-at pom
11200 (if (and inherit (if (eq inherit 'selective)
11201 (org-property-inherit-p property)
11203 (org-entry-get-with-inheritance property)
11204 (if (member property org-special-properties)
11205 ;; We need a special property. Use brute force, get all properties.
11206 (cdr (assoc property (org-entry-properties nil 'special)))
11207 (let ((range (org-get-property-block)))
11208 (if (and range
11209 (goto-char (car range))
11210 (re-search-forward
11211 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11212 (cdr range) t))
11213 ;; Found the property, return it.
11214 (if (match-end 1)
11215 (org-match-string-no-properties 1)
11216 "")))))))
11218 (defun org-property-or-variable-value (var &optional inherit)
11219 "Check if there is a property fixing the value of VAR.
11220 If yes, return this value. If not, return the current value of the variable."
11221 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11222 (if (and prop (stringp prop) (string-match "\\S-" prop))
11223 (read prop)
11224 (symbol-value var))))
11226 (defun org-entry-delete (pom property)
11227 "Delete the property PROPERTY from entry at point-or-marker POM."
11228 (org-with-point-at pom
11229 (if (member property org-special-properties)
11230 nil ; cannot delete these properties.
11231 (let ((range (org-get-property-block)))
11232 (if (and range
11233 (goto-char (car range))
11234 (re-search-forward
11235 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11236 (cdr range) t))
11237 (progn
11238 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11240 nil)))))
11242 ;; Multi-values properties are properties that contain multiple values
11243 ;; These values are assumed to be single words, separated by whitespace.
11244 (defun org-entry-add-to-multivalued-property (pom property value)
11245 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11246 (let* ((old (org-entry-get pom property))
11247 (values (and old (org-split-string old "[ \t]"))))
11248 (setq value (org-entry-protect-space value))
11249 (unless (member value values)
11250 (setq values (cons value values))
11251 (org-entry-put pom property
11252 (mapconcat 'identity values " ")))))
11254 (defun org-entry-remove-from-multivalued-property (pom property value)
11255 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11256 (let* ((old (org-entry-get pom property))
11257 (values (and old (org-split-string old "[ \t]"))))
11258 (setq value (org-entry-protect-space value))
11259 (when (member value values)
11260 (setq values (delete value values))
11261 (org-entry-put pom property
11262 (mapconcat 'identity values " ")))))
11264 (defun org-entry-member-in-multivalued-property (pom property value)
11265 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11266 (let* ((old (org-entry-get pom property))
11267 (values (and old (org-split-string old "[ \t]"))))
11268 (setq value (org-entry-protect-space value))
11269 (member value values)))
11271 (defun org-entry-get-multivalued-property (pom property)
11272 "Return a list of values in a multivalued property."
11273 (let* ((value (org-entry-get pom property))
11274 (values (and value (org-split-string value "[ \t]"))))
11275 (mapcar 'org-entry-restore-space values)))
11277 (defun org-entry-put-multivalued-property (pom property &rest values)
11278 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11279 VALUES should be a list of strings. Spaces will be protected."
11280 (org-entry-put pom property
11281 (mapconcat 'org-entry-protect-space values " "))
11282 (let* ((value (org-entry-get pom property))
11283 (values (and value (org-split-string value "[ \t]"))))
11284 (mapcar 'org-entry-restore-space values)))
11286 (defun org-entry-protect-space (s)
11287 "Protect spaces and newline in string S."
11288 (while (string-match " " s)
11289 (setq s (replace-match "%20" t t s)))
11290 (while (string-match "\n" s)
11291 (setq s (replace-match "%0A" t t s)))
11294 (defun org-entry-restore-space (s)
11295 "Restore spaces and newline in string S."
11296 (while (string-match "%20" s)
11297 (setq s (replace-match " " t t s)))
11298 (while (string-match "%0A" s)
11299 (setq s (replace-match "\n" t t s)))
11302 (defvar org-entry-property-inherited-from (make-marker)
11303 "Marker pointing to the entry from where a property was inherited.
11304 Each call to `org-entry-get-with-inheritance' will set this marker to the
11305 location of the entry where the inheritance search matched. If there was
11306 no match, the marker will point nowhere.
11307 Note that also `org-entry-get' calls this function, if the INHERIT flag
11308 is set.")
11310 (defun org-entry-get-with-inheritance (property)
11311 "Get entry property, and search higher levels if not present."
11312 (move-marker org-entry-property-inherited-from nil)
11313 (let (tmp)
11314 (save-excursion
11315 (save-restriction
11316 (widen)
11317 (catch 'ex
11318 (while t
11319 (when (setq tmp (org-entry-get nil property))
11320 (org-back-to-heading t)
11321 (move-marker org-entry-property-inherited-from (point))
11322 (throw 'ex tmp))
11323 (or (org-up-heading-safe) (throw 'ex nil)))))
11324 (or tmp
11325 (cdr (assoc property org-file-properties))
11326 (cdr (assoc property org-global-properties))
11327 (cdr (assoc property org-global-properties-fixed))))))
11329 (defun org-entry-put (pom property value)
11330 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11331 (org-with-point-at pom
11332 (org-back-to-heading t)
11333 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11334 range)
11335 (cond
11336 ((equal property "TODO")
11337 (when (and (stringp value) (string-match "\\S-" value)
11338 (not (member value org-todo-keywords-1)))
11339 (error "\"%s\" is not a valid TODO state" value))
11340 (if (or (not value)
11341 (not (string-match "\\S-" value)))
11342 (setq value 'none))
11343 (org-todo value)
11344 (org-set-tags nil 'align))
11345 ((equal property "PRIORITY")
11346 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11347 (string-to-char value) ?\ ))
11348 (org-set-tags nil 'align))
11349 ((equal property "SCHEDULED")
11350 (if (re-search-forward org-scheduled-time-regexp end t)
11351 (cond
11352 ((eq value 'earlier) (org-timestamp-change -1 'day))
11353 ((eq value 'later) (org-timestamp-change 1 'day))
11354 (t (call-interactively 'org-schedule)))
11355 (call-interactively 'org-schedule)))
11356 ((equal property "DEADLINE")
11357 (if (re-search-forward org-deadline-time-regexp end t)
11358 (cond
11359 ((eq value 'earlier) (org-timestamp-change -1 'day))
11360 ((eq value 'later) (org-timestamp-change 1 'day))
11361 (t (call-interactively 'org-deadline)))
11362 (call-interactively 'org-deadline)))
11363 ((member property org-special-properties)
11364 (error "The %s property can not yet be set with `org-entry-put'"
11365 property))
11366 (t ; a non-special property
11367 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11368 (setq range (org-get-property-block beg end 'force))
11369 (goto-char (car range))
11370 (if (re-search-forward
11371 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11372 (progn
11373 (delete-region (match-beginning 1) (match-end 1))
11374 (goto-char (match-beginning 1)))
11375 (goto-char (cdr range))
11376 (insert "\n")
11377 (backward-char 1)
11378 (org-indent-line-function)
11379 (insert ":" property ":"))
11380 (and value (insert " " value))
11381 (org-indent-line-function)))))))
11383 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11384 "Get all property keys in the current buffer.
11385 With INCLUDE-SPECIALS, also list the special properties that reflect things
11386 like tags and TODO state.
11387 With INCLUDE-DEFAULTS, also include properties that has special meaning
11388 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11389 With INCLUDE-COLUMNS, also include property names given in COLUMN
11390 formats in the current buffer."
11391 (let (rtn range cfmt s p)
11392 (save-excursion
11393 (save-restriction
11394 (widen)
11395 (goto-char (point-min))
11396 (while (re-search-forward org-property-start-re nil t)
11397 (setq range (org-get-property-block))
11398 (goto-char (car range))
11399 (while (re-search-forward
11400 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11401 (cdr range) t)
11402 (add-to-list 'rtn (org-match-string-no-properties 1)))
11403 (outline-next-heading))))
11405 (when include-specials
11406 (setq rtn (append org-special-properties rtn)))
11408 (when include-defaults
11409 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11411 (when include-columns
11412 (save-excursion
11413 (save-restriction
11414 (widen)
11415 (goto-char (point-min))
11416 (while (re-search-forward
11417 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11418 nil t)
11419 (setq cfmt (match-string 2) s 0)
11420 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11421 cfmt s)
11422 (setq s (match-end 0)
11423 p (match-string 1 cfmt))
11424 (unless (or (equal p "ITEM")
11425 (member p org-special-properties))
11426 (add-to-list 'rtn (match-string 1 cfmt))))))))
11428 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11430 (defun org-property-values (key)
11431 "Return a list of all values of property KEY."
11432 (save-excursion
11433 (save-restriction
11434 (widen)
11435 (goto-char (point-min))
11436 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11437 values)
11438 (while (re-search-forward re nil t)
11439 (add-to-list 'values (org-trim (match-string 1))))
11440 (delete "" values)))))
11442 (defun org-insert-property-drawer ()
11443 "Insert a property drawer into the current entry."
11444 (interactive)
11445 (org-back-to-heading t)
11446 (looking-at outline-regexp)
11447 (let ((indent (- (match-end 0)(match-beginning 0)))
11448 (beg (point))
11449 (re (concat "^[ \t]*" org-keyword-time-regexp))
11450 end hiddenp)
11451 (outline-next-heading)
11452 (setq end (point))
11453 (goto-char beg)
11454 (while (re-search-forward re end t))
11455 (setq hiddenp (org-invisible-p))
11456 (end-of-line 1)
11457 (and (equal (char-after) ?\n) (forward-char 1))
11458 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11459 (if (member (match-string 1) '("CLOCK:" ":END:"))
11460 ;; just skip this line
11461 (beginning-of-line 2)
11462 ;; Drawer start, find the end
11463 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11464 (beginning-of-line 1)))
11465 (org-skip-over-state-notes)
11466 (skip-chars-backward " \t\n\r")
11467 (if (eq (char-before) ?*) (forward-char 1))
11468 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11469 (beginning-of-line 0)
11470 (org-indent-to-column indent)
11471 (beginning-of-line 2)
11472 (org-indent-to-column indent)
11473 (beginning-of-line 0)
11474 (if hiddenp
11475 (save-excursion
11476 (org-back-to-heading t)
11477 (hide-entry))
11478 (org-flag-drawer t))))
11480 (defun org-set-property (property value)
11481 "In the current entry, set PROPERTY to VALUE.
11482 When called interactively, this will prompt for a property name, offering
11483 completion on existing and default properties. And then it will prompt
11484 for a value, offering completion either on allowed values (via an inherited
11485 xxx_ALL property) or on existing values in other instances of this property
11486 in the current file."
11487 (interactive
11488 (let* ((completion-ignore-case t)
11489 (keys (org-buffer-property-keys nil t t))
11490 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11491 (prop (if (member prop0 keys)
11492 prop0
11493 (or (cdr (assoc (downcase prop0)
11494 (mapcar (lambda (x) (cons (downcase x) x))
11495 keys)))
11496 prop0)))
11497 (cur (org-entry-get nil prop))
11498 (allowed (org-property-get-allowed-values nil prop 'table))
11499 (existing (mapcar 'list (org-property-values prop)))
11500 (val (if allowed
11501 (org-completing-read "Value: " allowed nil 'req-match)
11502 (let (org-completion-use-ido)
11503 (org-completing-read
11504 (concat "Value" (if (and cur (string-match "\\S-" cur))
11505 (concat "[" cur "]") "")
11506 ": ")
11507 existing nil nil "" nil cur)))))
11508 (list prop (if (equal val "") cur val))))
11509 (unless (equal (org-entry-get nil property) value)
11510 (org-entry-put nil property value)))
11512 (defun org-delete-property (property)
11513 "In the current entry, delete PROPERTY."
11514 (interactive
11515 (let* ((completion-ignore-case t)
11516 (prop (org-ido-completing-read
11517 "Property: " (org-entry-properties nil 'standard))))
11518 (list prop)))
11519 (message "Property %s %s" property
11520 (if (org-entry-delete nil property)
11521 "deleted"
11522 "was not present in the entry")))
11524 (defun org-delete-property-globally (property)
11525 "Remove PROPERTY globally, from all entries."
11526 (interactive
11527 (let* ((completion-ignore-case t)
11528 (prop (org-ido-completing-read
11529 "Globally remove property: "
11530 (mapcar 'list (org-buffer-property-keys)))))
11531 (list prop)))
11532 (save-excursion
11533 (save-restriction
11534 (widen)
11535 (goto-char (point-min))
11536 (let ((cnt 0))
11537 (while (re-search-forward
11538 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11539 nil t)
11540 (setq cnt (1+ cnt))
11541 (replace-match ""))
11542 (message "Property \"%s\" removed from %d entries" property cnt)))))
11544 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11546 (defun org-compute-property-at-point ()
11547 "Compute the property at point.
11548 This looks for an enclosing column format, extracts the operator and
11549 then applies it to the property in the column format's scope."
11550 (interactive)
11551 (unless (org-at-property-p)
11552 (error "Not at a property"))
11553 (let ((prop (org-match-string-no-properties 2)))
11554 (org-columns-get-format-and-top-level)
11555 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11556 (error "No operator defined for property %s" prop))
11557 (org-columns-compute prop)))
11559 (defun org-property-get-allowed-values (pom property &optional table)
11560 "Get allowed values for the property PROPERTY.
11561 When TABLE is non-nil, return an alist that can directly be used for
11562 completion."
11563 (let (vals)
11564 (cond
11565 ((equal property "TODO")
11566 (setq vals (org-with-point-at pom
11567 (append org-todo-keywords-1 '("")))))
11568 ((equal property "PRIORITY")
11569 (let ((n org-lowest-priority))
11570 (while (>= n org-highest-priority)
11571 (push (char-to-string n) vals)
11572 (setq n (1- n)))))
11573 ((member property org-special-properties))
11575 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11577 (when (and vals (string-match "\\S-" vals))
11578 (setq vals (car (read-from-string (concat "(" vals ")"))))
11579 (setq vals (mapcar (lambda (x)
11580 (cond ((stringp x) x)
11581 ((numberp x) (number-to-string x))
11582 ((symbolp x) (symbol-name x))
11583 (t "???")))
11584 vals)))))
11585 (if table (mapcar 'list vals) vals)))
11587 (defun org-property-previous-allowed-value (&optional previous)
11588 "Switch to the next allowed value for this property."
11589 (interactive)
11590 (org-property-next-allowed-value t))
11592 (defun org-property-next-allowed-value (&optional previous)
11593 "Switch to the next allowed value for this property."
11594 (interactive)
11595 (unless (org-at-property-p)
11596 (error "Not at a property"))
11597 (let* ((key (match-string 2))
11598 (value (match-string 3))
11599 (allowed (or (org-property-get-allowed-values (point) key)
11600 (and (member value '("[ ]" "[-]" "[X]"))
11601 '("[ ]" "[X]"))))
11602 nval)
11603 (unless allowed
11604 (error "Allowed values for this property have not been defined"))
11605 (if previous (setq allowed (reverse allowed)))
11606 (if (member value allowed)
11607 (setq nval (car (cdr (member value allowed)))))
11608 (setq nval (or nval (car allowed)))
11609 (if (equal nval value)
11610 (error "Only one allowed value for this property"))
11611 (org-at-property-p)
11612 (replace-match (concat " :" key ": " nval) t t)
11613 (org-indent-line-function)
11614 (beginning-of-line 1)
11615 (skip-chars-forward " \t")))
11617 (defun org-find-entry-with-id (ident)
11618 "Locate the entry that contains the ID property with exact value IDENT.
11619 IDENT can be a string, a symbol or a number, this function will search for
11620 the string representation of it.
11621 Return the position where this entry starts, or nil if there is no such entry."
11622 (interactive "sID: ")
11623 (let ((id (cond
11624 ((stringp ident) ident)
11625 ((symbol-name ident) (symbol-name ident))
11626 ((numberp ident) (number-to-string ident))
11627 (t (error "IDENT %s must be a string, symbol or number" ident))))
11628 (case-fold-search nil))
11629 (save-excursion
11630 (save-restriction
11631 (widen)
11632 (goto-char (point-min))
11633 (when (re-search-forward
11634 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11635 nil t)
11636 (org-back-to-heading)
11637 (point))))))
11639 ;;;; Timestamps
11641 (defvar org-last-changed-timestamp nil)
11642 (defvar org-last-inserted-timestamp nil
11643 "The last time stamp inserted with `org-insert-time-stamp'.")
11644 (defvar org-time-was-given) ; dynamically scoped parameter
11645 (defvar org-end-time-was-given) ; dynamically scoped parameter
11646 (defvar org-ts-what) ; dynamically scoped parameter
11648 (defun org-time-stamp (arg &optional inactive)
11649 "Prompt for a date/time and insert a time stamp.
11650 If the user specifies a time like HH:MM, or if this command is called
11651 with a prefix argument, the time stamp will contain date and time.
11652 Otherwise, only the date will be included. All parts of a date not
11653 specified by the user will be filled in from the current date/time.
11654 So if you press just return without typing anything, the time stamp
11655 will represent the current date/time. If there is already a timestamp
11656 at the cursor, it will be modified."
11657 (interactive "P")
11658 (let* ((ts nil)
11659 (default-time
11660 ;; Default time is either today, or, when entering a range,
11661 ;; the range start.
11662 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11663 (save-excursion
11664 (re-search-backward
11665 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11666 (- (point) 20) t)))
11667 (apply 'encode-time (org-parse-time-string (match-string 1)))
11668 (current-time)))
11669 (default-input (and ts (org-get-compact-tod ts)))
11670 org-time-was-given org-end-time-was-given time)
11671 (cond
11672 ((and (org-at-timestamp-p t)
11673 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11674 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11675 (insert "--")
11676 (setq time (let ((this-command this-command))
11677 (org-read-date arg 'totime nil nil
11678 default-time default-input)))
11679 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11680 ((org-at-timestamp-p t)
11681 (setq time (let ((this-command this-command))
11682 (org-read-date arg 'totime nil nil default-time default-input)))
11683 (when (org-at-timestamp-p t) ; just to get the match data
11684 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11685 (replace-match "")
11686 (setq org-last-changed-timestamp
11687 (org-insert-time-stamp
11688 time (or org-time-was-given arg)
11689 inactive nil nil (list org-end-time-was-given))))
11690 (message "Timestamp updated"))
11692 (setq time (let ((this-command this-command))
11693 (org-read-date arg 'totime nil nil default-time default-input)))
11694 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11695 nil nil (list org-end-time-was-given))))))
11697 ;; FIXME: can we use this for something else, like computing time differences?
11698 (defun org-get-compact-tod (s)
11699 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11700 (let* ((t1 (match-string 1 s))
11701 (h1 (string-to-number (match-string 2 s)))
11702 (m1 (string-to-number (match-string 3 s)))
11703 (t2 (and (match-end 4) (match-string 5 s)))
11704 (h2 (and t2 (string-to-number (match-string 6 s))))
11705 (m2 (and t2 (string-to-number (match-string 7 s))))
11706 dh dm)
11707 (if (not t2)
11709 (setq dh (- h2 h1) dm (- m2 m1))
11710 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11711 (concat t1 "+" (number-to-string dh)
11712 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11714 (defun org-time-stamp-inactive (&optional arg)
11715 "Insert an inactive time stamp.
11716 An inactive time stamp is enclosed in square brackets instead of angle
11717 brackets. It is inactive in the sense that it does not trigger agenda entries,
11718 does not link to the calendar and cannot be changed with the S-cursor keys.
11719 So these are more for recording a certain time/date."
11720 (interactive "P")
11721 (org-time-stamp arg 'inactive))
11723 (defvar org-date-ovl (org-make-overlay 1 1))
11724 (org-overlay-put org-date-ovl 'face 'org-warning)
11725 (org-detach-overlay org-date-ovl)
11727 (defvar org-ans1) ; dynamically scoped parameter
11728 (defvar org-ans2) ; dynamically scoped parameter
11730 (defvar org-plain-time-of-day-regexp) ; defined below
11732 (defvar org-overriding-default-time nil) ; dynamically scoped
11733 (defvar org-read-date-overlay nil)
11734 (defvar org-dcst nil) ; dynamically scoped
11735 (defvar org-read-date-history nil)
11737 (defun org-read-date (&optional with-time to-time from-string prompt
11738 default-time default-input)
11739 "Read a date, possibly a time, and make things smooth for the user.
11740 The prompt will suggest to enter an ISO date, but you can also enter anything
11741 which will at least partially be understood by `parse-time-string'.
11742 Unrecognized parts of the date will default to the current day, month, year,
11743 hour and minute. If this command is called to replace a timestamp at point,
11744 of to enter the second timestamp of a range, the default time is taken from the
11745 existing stamp. For example,
11746 3-2-5 --> 2003-02-05
11747 feb 15 --> currentyear-02-15
11748 sep 12 9 --> 2009-09-12
11749 12:45 --> today 12:45
11750 22 sept 0:34 --> currentyear-09-22 0:34
11751 12 --> currentyear-currentmonth-12
11752 Fri --> nearest Friday (today or later)
11753 etc.
11755 Furthermore you can specify a relative date by giving, as the *first* thing
11756 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11757 change in days weeks, months, years.
11758 With a single plus or minus, the date is relative to today. With a double
11759 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11760 +4d --> four days from today
11761 +4 --> same as above
11762 +2w --> two weeks from today
11763 ++5 --> five days from default date
11765 The function understands only English month and weekday abbreviations,
11766 but this can be configured with the variables `parse-time-months' and
11767 `parse-time-weekdays'.
11769 While prompting, a calendar is popped up - you can also select the
11770 date with the mouse (button 1). The calendar shows a period of three
11771 months. To scroll it to other months, use the keys `>' and `<'.
11772 If you don't like the calendar, turn it off with
11773 \(setq org-read-date-popup-calendar nil)
11775 With optional argument TO-TIME, the date will immediately be converted
11776 to an internal time.
11777 With an optional argument WITH-TIME, the prompt will suggest to also
11778 insert a time. Note that when WITH-TIME is not set, you can still
11779 enter a time, and this function will inform the calling routine about
11780 this change. The calling routine may then choose to change the format
11781 used to insert the time stamp into the buffer to include the time.
11782 With optional argument FROM-STRING, read from this string instead from
11783 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11784 the time/date that is used for everything that is not specified by the
11785 user."
11786 (require 'parse-time)
11787 (let* ((org-time-stamp-rounding-minutes
11788 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11789 (org-dcst org-display-custom-times)
11790 (ct (org-current-time))
11791 (def (or org-overriding-default-time default-time ct))
11792 (defdecode (decode-time def))
11793 (dummy (progn
11794 (when (< (nth 2 defdecode) org-extend-today-until)
11795 (setcar (nthcdr 2 defdecode) -1)
11796 (setcar (nthcdr 1 defdecode) 59)
11797 (setq def (apply 'encode-time defdecode)
11798 defdecode (decode-time def)))))
11799 (calendar-move-hook nil)
11800 (calendar-view-diary-initially-flag nil)
11801 (view-diary-entries-initially nil)
11802 (calendar-view-holidays-initially-flag nil)
11803 (view-calendar-holidays-initially nil)
11804 (timestr (format-time-string
11805 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11806 (prompt (concat (if prompt (concat prompt " ") "")
11807 (format "Date+time [%s]: " timestr)))
11808 ans (org-ans0 "") org-ans1 org-ans2 final)
11810 (cond
11811 (from-string (setq ans from-string))
11812 (org-read-date-popup-calendar
11813 (save-excursion
11814 (save-window-excursion
11815 (calendar)
11816 (calendar-forward-day (- (time-to-days def)
11817 (calendar-absolute-from-gregorian
11818 (calendar-current-date))))
11819 (org-eval-in-calendar nil t)
11820 (let* ((old-map (current-local-map))
11821 (map (copy-keymap calendar-mode-map))
11822 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11823 (org-defkey map (kbd "RET") 'org-calendar-select)
11824 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11825 'org-calendar-select-mouse)
11826 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11827 'org-calendar-select-mouse)
11828 (org-defkey minibuffer-local-map [(meta shift left)]
11829 (lambda () (interactive)
11830 (org-eval-in-calendar '(calendar-backward-month 1))))
11831 (org-defkey minibuffer-local-map [(meta shift right)]
11832 (lambda () (interactive)
11833 (org-eval-in-calendar '(calendar-forward-month 1))))
11834 (org-defkey minibuffer-local-map [(meta shift up)]
11835 (lambda () (interactive)
11836 (org-eval-in-calendar '(calendar-backward-year 1))))
11837 (org-defkey minibuffer-local-map [(meta shift down)]
11838 (lambda () (interactive)
11839 (org-eval-in-calendar '(calendar-forward-year 1))))
11840 (org-defkey minibuffer-local-map [(shift up)]
11841 (lambda () (interactive)
11842 (org-eval-in-calendar '(calendar-backward-week 1))))
11843 (org-defkey minibuffer-local-map [(shift down)]
11844 (lambda () (interactive)
11845 (org-eval-in-calendar '(calendar-forward-week 1))))
11846 (org-defkey minibuffer-local-map [(shift left)]
11847 (lambda () (interactive)
11848 (org-eval-in-calendar '(calendar-backward-day 1))))
11849 (org-defkey minibuffer-local-map [(shift right)]
11850 (lambda () (interactive)
11851 (org-eval-in-calendar '(calendar-forward-day 1))))
11852 (org-defkey minibuffer-local-map ">"
11853 (lambda () (interactive)
11854 (org-eval-in-calendar '(scroll-calendar-left 1))))
11855 (org-defkey minibuffer-local-map "<"
11856 (lambda () (interactive)
11857 (org-eval-in-calendar '(scroll-calendar-right 1))))
11858 (run-hooks 'org-read-date-minibuffer-setup-hook)
11859 (unwind-protect
11860 (progn
11861 (use-local-map map)
11862 (add-hook 'post-command-hook 'org-read-date-display)
11863 (setq org-ans0 (read-string prompt default-input
11864 'org-read-date-history nil))
11865 ;; org-ans0: from prompt
11866 ;; org-ans1: from mouse click
11867 ;; org-ans2: from calendar motion
11868 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11869 (remove-hook 'post-command-hook 'org-read-date-display)
11870 (use-local-map old-map)
11871 (when org-read-date-overlay
11872 (org-delete-overlay org-read-date-overlay)
11873 (setq org-read-date-overlay nil)))))))
11875 (t ; Naked prompt only
11876 (unwind-protect
11877 (setq ans (read-string prompt default-input
11878 'org-read-date-history timestr))
11879 (when org-read-date-overlay
11880 (org-delete-overlay org-read-date-overlay)
11881 (setq org-read-date-overlay nil)))))
11883 (setq final (org-read-date-analyze ans def defdecode))
11885 (if to-time
11886 (apply 'encode-time final)
11887 (if (and (boundp 'org-time-was-given) org-time-was-given)
11888 (format "%04d-%02d-%02d %02d:%02d"
11889 (nth 5 final) (nth 4 final) (nth 3 final)
11890 (nth 2 final) (nth 1 final))
11891 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11892 (defvar def)
11893 (defvar defdecode)
11894 (defvar with-time)
11895 (defun org-read-date-display ()
11896 "Display the current date prompt interpretation in the minibuffer."
11897 (when org-read-date-display-live
11898 (when org-read-date-overlay
11899 (org-delete-overlay org-read-date-overlay))
11900 (let ((p (point)))
11901 (end-of-line 1)
11902 (while (not (equal (buffer-substring
11903 (max (point-min) (- (point) 4)) (point))
11904 " "))
11905 (insert " "))
11906 (goto-char p))
11907 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11908 " " (or org-ans1 org-ans2)))
11909 (org-end-time-was-given nil)
11910 (f (org-read-date-analyze ans def defdecode))
11911 (fmts (if org-dcst
11912 org-time-stamp-custom-formats
11913 org-time-stamp-formats))
11914 (fmt (if (or with-time
11915 (and (boundp 'org-time-was-given) org-time-was-given))
11916 (cdr fmts)
11917 (car fmts)))
11918 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11919 (when (and org-end-time-was-given
11920 (string-match org-plain-time-of-day-regexp txt))
11921 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11922 org-end-time-was-given
11923 (substring txt (match-end 0)))))
11924 (setq org-read-date-overlay
11925 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11926 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11928 (defun org-read-date-analyze (ans def defdecode)
11929 "Analyse the combined answer of the date prompt."
11930 ;; FIXME: cleanup and comment
11931 (let (delta deltan deltaw deltadef year month day
11932 hour minute second wday pm h2 m2 tl wday1
11933 iso-year iso-weekday iso-week iso-year iso-date)
11935 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11936 (setq ans "+0"))
11938 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11939 (setq ans (replace-match "" t t ans)
11940 deltan (car delta)
11941 deltaw (nth 1 delta)
11942 deltadef (nth 2 delta)))
11944 ;; Check if there is an iso week date in there
11945 ;; If yes, sore the info and postpone interpreting it until the rest
11946 ;; of the parsing is done
11947 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11948 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11949 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11950 iso-week (string-to-number (match-string 2 ans)))
11951 (setq ans (replace-match "" t t ans)))
11953 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11954 (when (string-match
11955 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11956 (setq year (if (match-end 2)
11957 (string-to-number (match-string 2 ans))
11958 (string-to-number (format-time-string "%Y")))
11959 month (string-to-number (match-string 3 ans))
11960 day (string-to-number (match-string 4 ans)))
11961 (if (< year 100) (setq year (+ 2000 year)))
11962 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11963 t nil ans)))
11964 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11965 ;; If there is a time with am/pm, and *no* time without it, we convert
11966 ;; so that matching will be successful.
11967 (loop for i from 1 to 2 do ; twice, for end time as well
11968 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11969 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11970 (setq hour (string-to-number (match-string 1 ans))
11971 minute (if (match-end 3)
11972 (string-to-number (match-string 3 ans))
11974 pm (equal ?p
11975 (string-to-char (downcase (match-string 4 ans)))))
11976 (if (and (= hour 12) (not pm))
11977 (setq hour 0)
11978 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11979 (setq ans (replace-match (format "%02d:%02d" hour minute)
11980 t t ans))))
11982 ;; Check if a time range is given as a duration
11983 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11984 (setq hour (string-to-number (match-string 1 ans))
11985 h2 (+ hour (string-to-number (match-string 3 ans)))
11986 minute (string-to-number (match-string 2 ans))
11987 m2 (+ minute (if (match-end 5) (string-to-number
11988 (match-string 5 ans))0)))
11989 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11990 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11991 t t ans)))
11993 ;; Check if there is a time range
11994 (when (boundp 'org-end-time-was-given)
11995 (setq org-time-was-given nil)
11996 (when (and (string-match org-plain-time-of-day-regexp ans)
11997 (match-end 8))
11998 (setq org-end-time-was-given (match-string 8 ans))
11999 (setq ans (concat (substring ans 0 (match-beginning 7))
12000 (substring ans (match-end 7))))))
12002 (setq tl (parse-time-string ans)
12003 day (or (nth 3 tl) (nth 3 defdecode))
12004 month (or (nth 4 tl)
12005 (if (and org-read-date-prefer-future
12006 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12007 (1+ (nth 4 defdecode))
12008 (nth 4 defdecode)))
12009 year (or (nth 5 tl)
12010 (if (and org-read-date-prefer-future
12011 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12012 (1+ (nth 5 defdecode))
12013 (nth 5 defdecode)))
12014 hour (or (nth 2 tl) (nth 2 defdecode))
12015 minute (or (nth 1 tl) (nth 1 defdecode))
12016 second (or (nth 0 tl) 0)
12017 wday (nth 6 tl))
12019 ;; Special date definitions below
12020 (cond
12021 (iso-week
12022 ;; There was an iso week
12023 (setq year (or iso-year year)
12024 day (or iso-weekday wday 1)
12025 wday nil ; to make sure that the trigger below does not match
12026 iso-date (calendar-gregorian-from-absolute
12027 (calendar-absolute-from-iso
12028 (list iso-week day year))))
12029 ; FIXME: Should we also push ISO weeks into the future?
12030 ; (when (and org-read-date-prefer-future
12031 ; (not iso-year)
12032 ; (< (calendar-absolute-from-gregorian iso-date)
12033 ; (time-to-days (current-time))))
12034 ; (setq year (1+ year)
12035 ; iso-date (calendar-gregorian-from-absolute
12036 ; (calendar-absolute-from-iso
12037 ; (list iso-week day year)))))
12038 (setq month (car iso-date)
12039 year (nth 2 iso-date)
12040 day (nth 1 iso-date)))
12041 (deltan
12042 (unless deltadef
12043 (let ((now (decode-time (current-time))))
12044 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12045 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12046 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12047 ((equal deltaw "m") (setq month (+ month deltan)))
12048 ((equal deltaw "y") (setq year (+ year deltan)))))
12049 ((and wday (not (nth 3 tl)))
12050 ;; Weekday was given, but no day, so pick that day in the week
12051 ;; on or after the derived date.
12052 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12053 (unless (equal wday wday1)
12054 (setq day (+ day (% (- wday wday1 -7) 7))))))
12055 (if (and (boundp 'org-time-was-given)
12056 (nth 2 tl))
12057 (setq org-time-was-given t))
12058 (if (< year 100) (setq year (+ 2000 year)))
12059 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12060 (list second minute hour day month year)))
12062 (defvar parse-time-weekdays)
12064 (defun org-read-date-get-relative (s today default)
12065 "Check string S for special relative date string.
12066 TODAY and DEFAULT are internal times, for today and for a default.
12067 Return shift list (N what def-flag)
12068 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12069 N is the number of WHATs to shift.
12070 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12071 the DEFAULT date rather than TODAY."
12072 (when (and
12073 (string-match
12074 (concat
12075 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12076 "\\([0-9]+\\)?"
12077 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12078 "\\([ \t]\\|$\\)") s)
12079 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12080 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12081 (string-to-char (substring (match-string 1 s) -1))
12082 ?+))
12083 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12084 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12085 (what (if (match-end 3) (match-string 3 s) "d"))
12086 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12087 (date (if rel default today))
12088 (wday (nth 6 (decode-time date)))
12089 delta)
12090 (if wday1
12091 (progn
12092 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12093 (if (= dir ?-) (setq delta (- delta 7)))
12094 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12095 (list delta "d" rel))
12096 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12098 (defun org-eval-in-calendar (form &optional keepdate)
12099 "Eval FORM in the calendar window and return to current window.
12100 Also, store the cursor date in variable org-ans2."
12101 (let ((sw (selected-window)))
12102 (select-window (get-buffer-window "*Calendar*"))
12103 (eval form)
12104 (when (and (not keepdate) (calendar-cursor-to-date))
12105 (let* ((date (calendar-cursor-to-date))
12106 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12107 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12108 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12109 (select-window sw)))
12111 (defun org-calendar-select ()
12112 "Return to `org-read-date' with the date currently selected.
12113 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12114 (interactive)
12115 (when (calendar-cursor-to-date)
12116 (let* ((date (calendar-cursor-to-date))
12117 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12118 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12119 (if (active-minibuffer-window) (exit-minibuffer))))
12121 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12122 "Insert a date stamp for the date given by the internal TIME.
12123 WITH-HM means, use the stamp format that includes the time of the day.
12124 INACTIVE means use square brackets instead of angular ones, so that the
12125 stamp will not contribute to the agenda.
12126 PRE and POST are optional strings to be inserted before and after the
12127 stamp.
12128 The command returns the inserted time stamp."
12129 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12130 stamp)
12131 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12132 (insert-before-markers (or pre ""))
12133 (insert-before-markers (setq stamp (format-time-string fmt time)))
12134 (when (listp extra)
12135 (setq extra (car extra))
12136 (if (and (stringp extra)
12137 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12138 (setq extra (format "-%02d:%02d"
12139 (string-to-number (match-string 1 extra))
12140 (string-to-number (match-string 2 extra))))
12141 (setq extra nil)))
12142 (when extra
12143 (backward-char 1)
12144 (insert-before-markers extra)
12145 (forward-char 1))
12146 (insert-before-markers (or post ""))
12147 (setq org-last-inserted-timestamp stamp)))
12149 (defun org-toggle-time-stamp-overlays ()
12150 "Toggle the use of custom time stamp formats."
12151 (interactive)
12152 (setq org-display-custom-times (not org-display-custom-times))
12153 (unless org-display-custom-times
12154 (let ((p (point-min)) (bmp (buffer-modified-p)))
12155 (while (setq p (next-single-property-change p 'display))
12156 (if (and (get-text-property p 'display)
12157 (eq (get-text-property p 'face) 'org-date))
12158 (remove-text-properties
12159 p (setq p (next-single-property-change p 'display))
12160 '(display t))))
12161 (set-buffer-modified-p bmp)))
12162 (if (featurep 'xemacs)
12163 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12164 (org-restart-font-lock)
12165 (setq org-table-may-need-update t)
12166 (if org-display-custom-times
12167 (message "Time stamps are overlayed with custom format")
12168 (message "Time stamp overlays removed")))
12170 (defun org-display-custom-time (beg end)
12171 "Overlay modified time stamp format over timestamp between BEG and END."
12172 (let* ((ts (buffer-substring beg end))
12173 t1 w1 with-hm tf time str w2 (off 0))
12174 (save-match-data
12175 (setq t1 (org-parse-time-string ts t))
12176 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12177 (setq off (- (match-end 0) (match-beginning 0)))))
12178 (setq end (- end off))
12179 (setq w1 (- end beg)
12180 with-hm (and (nth 1 t1) (nth 2 t1))
12181 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12182 time (org-fix-decoded-time t1)
12183 str (org-add-props
12184 (format-time-string
12185 (substring tf 1 -1) (apply 'encode-time time))
12186 nil 'mouse-face 'highlight)
12187 w2 (length str))
12188 (if (not (= w2 w1))
12189 (add-text-properties (1+ beg) (+ 2 beg)
12190 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12191 (if (featurep 'xemacs)
12192 (progn
12193 (put-text-property beg end 'invisible t)
12194 (put-text-property beg end 'end-glyph (make-glyph str)))
12195 (put-text-property beg end 'display str))))
12197 (defun org-translate-time (string)
12198 "Translate all timestamps in STRING to custom format.
12199 But do this only if the variable `org-display-custom-times' is set."
12200 (when org-display-custom-times
12201 (save-match-data
12202 (let* ((start 0)
12203 (re org-ts-regexp-both)
12204 t1 with-hm inactive tf time str beg end)
12205 (while (setq start (string-match re string start))
12206 (setq beg (match-beginning 0)
12207 end (match-end 0)
12208 t1 (save-match-data
12209 (org-parse-time-string (substring string beg end) t))
12210 with-hm (and (nth 1 t1) (nth 2 t1))
12211 inactive (equal (substring string beg (1+ beg)) "[")
12212 tf (funcall (if with-hm 'cdr 'car)
12213 org-time-stamp-custom-formats)
12214 time (org-fix-decoded-time t1)
12215 str (format-time-string
12216 (concat
12217 (if inactive "[" "<") (substring tf 1 -1)
12218 (if inactive "]" ">"))
12219 (apply 'encode-time time))
12220 string (replace-match str t t string)
12221 start (+ start (length str)))))))
12222 string)
12224 (defun org-fix-decoded-time (time)
12225 "Set 0 instead of nil for the first 6 elements of time.
12226 Don't touch the rest."
12227 (let ((n 0))
12228 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12230 (defun org-days-to-time (timestamp-string)
12231 "Difference between TIMESTAMP-STRING and now in days."
12232 (- (time-to-days (org-time-string-to-time timestamp-string))
12233 (time-to-days (current-time))))
12235 (defun org-deadline-close (timestamp-string &optional ndays)
12236 "Is the time in TIMESTAMP-STRING close to the current date?"
12237 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12238 (and (< (org-days-to-time timestamp-string) ndays)
12239 (not (org-entry-is-done-p))))
12241 (defun org-get-wdays (ts)
12242 "Get the deadline lead time appropriate for timestring TS."
12243 (cond
12244 ((<= org-deadline-warning-days 0)
12245 ;; 0 or negative, enforce this value no matter what
12246 (- org-deadline-warning-days))
12247 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12248 ;; lead time is specified.
12249 (floor (* (string-to-number (match-string 1 ts))
12250 (cdr (assoc (match-string 2 ts)
12251 '(("d" . 1) ("w" . 7)
12252 ("m" . 30.4) ("y" . 365.25)))))))
12253 ;; go for the default.
12254 (t org-deadline-warning-days)))
12256 (defun org-calendar-select-mouse (ev)
12257 "Return to `org-read-date' with the date currently selected.
12258 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12259 (interactive "e")
12260 (mouse-set-point ev)
12261 (when (calendar-cursor-to-date)
12262 (let* ((date (calendar-cursor-to-date))
12263 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12264 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12265 (if (active-minibuffer-window) (exit-minibuffer))))
12267 (defun org-check-deadlines (ndays)
12268 "Check if there are any deadlines due or past due.
12269 A deadline is considered due if it happens within `org-deadline-warning-days'
12270 days from today's date. If the deadline appears in an entry marked DONE,
12271 it is not shown. The prefix arg NDAYS can be used to test that many
12272 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12273 (interactive "P")
12274 (let* ((org-warn-days
12275 (cond
12276 ((equal ndays '(4)) 100000)
12277 (ndays (prefix-numeric-value ndays))
12278 (t (abs org-deadline-warning-days))))
12279 (case-fold-search nil)
12280 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12281 (callback
12282 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12284 (message "%d deadlines past-due or due within %d days"
12285 (org-occur regexp nil callback)
12286 org-warn-days)))
12288 (defun org-check-before-date (date)
12289 "Check if there are deadlines or scheduled entries before DATE."
12290 (interactive (list (org-read-date)))
12291 (let ((case-fold-search nil)
12292 (regexp (concat "\\<\\(" org-deadline-string
12293 "\\|" org-scheduled-string
12294 "\\) *<\\([^>]+\\)>"))
12295 (callback
12296 (lambda () (time-less-p
12297 (org-time-string-to-time (match-string 2))
12298 (org-time-string-to-time date)))))
12299 (message "%d entries before %s"
12300 (org-occur regexp nil callback) date)))
12302 (defun org-check-after-date (date)
12303 "Check if there are deadlines or scheduled entries after DATE."
12304 (interactive (list (org-read-date)))
12305 (let ((case-fold-search nil)
12306 (regexp (concat "\\<\\(" org-deadline-string
12307 "\\|" org-scheduled-string
12308 "\\) *<\\([^>]+\\)>"))
12309 (callback
12310 (lambda () (not
12311 (time-less-p
12312 (org-time-string-to-time (match-string 2))
12313 (org-time-string-to-time date))))))
12314 (message "%d entries after %s"
12315 (org-occur regexp nil callback) date)))
12317 (defun org-evaluate-time-range (&optional to-buffer)
12318 "Evaluate a time range by computing the difference between start and end.
12319 Normally the result is just printed in the echo area, but with prefix arg
12320 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12321 If the time range is actually in a table, the result is inserted into the
12322 next column.
12323 For time difference computation, a year is assumed to be exactly 365
12324 days in order to avoid rounding problems."
12325 (interactive "P")
12327 (org-clock-update-time-maybe)
12328 (save-excursion
12329 (unless (org-at-date-range-p t)
12330 (goto-char (point-at-bol))
12331 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12332 (if (not (org-at-date-range-p t))
12333 (error "Not at a time-stamp range, and none found in current line")))
12334 (let* ((ts1 (match-string 1))
12335 (ts2 (match-string 2))
12336 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12337 (match-end (match-end 0))
12338 (time1 (org-time-string-to-time ts1))
12339 (time2 (org-time-string-to-time ts2))
12340 (t1 (time-to-seconds time1))
12341 (t2 (time-to-seconds time2))
12342 (diff (abs (- t2 t1)))
12343 (negative (< (- t2 t1) 0))
12344 ;; (ys (floor (* 365 24 60 60)))
12345 (ds (* 24 60 60))
12346 (hs (* 60 60))
12347 (fy "%dy %dd %02d:%02d")
12348 (fy1 "%dy %dd")
12349 (fd "%dd %02d:%02d")
12350 (fd1 "%dd")
12351 (fh "%02d:%02d")
12352 y d h m align)
12353 (if havetime
12354 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12356 d (floor (/ diff ds)) diff (mod diff ds)
12357 h (floor (/ diff hs)) diff (mod diff hs)
12358 m (floor (/ diff 60)))
12359 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12361 d (floor (+ (/ diff ds) 0.5))
12362 h 0 m 0))
12363 (if (not to-buffer)
12364 (message "%s" (org-make-tdiff-string y d h m))
12365 (if (org-at-table-p)
12366 (progn
12367 (goto-char match-end)
12368 (setq align t)
12369 (and (looking-at " *|") (goto-char (match-end 0))))
12370 (goto-char match-end))
12371 (if (looking-at
12372 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12373 (replace-match ""))
12374 (if negative (insert " -"))
12375 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12376 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12377 (insert " " (format fh h m))))
12378 (if align (org-table-align))
12379 (message "Time difference inserted")))))
12381 (defun org-make-tdiff-string (y d h m)
12382 (let ((fmt "")
12383 (l nil))
12384 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12385 l (push y l)))
12386 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12387 l (push d l)))
12388 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12389 l (push h l)))
12390 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12391 l (push m l)))
12392 (apply 'format fmt (nreverse l))))
12394 (defun org-time-string-to-time (s)
12395 (apply 'encode-time (org-parse-time-string s)))
12397 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12398 "Convert a time stamp to an absolute day number.
12399 If there is a specifyer for a cyclic time stamp, get the closest date to
12400 DAYNR.
12401 PREFER and SHOW-ALL are passed through to `org-closest-date'."
12402 (cond
12403 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12404 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12405 daynr
12406 (+ daynr 1000)))
12407 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12408 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12409 (time-to-days (current-time))) (match-string 0 s)
12410 prefer show-all))
12411 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12413 (defun org-days-to-iso-week (days)
12414 "Return the iso week number."
12415 (require 'cal-iso)
12416 (car (calendar-iso-from-absolute days)))
12418 (defun org-small-year-to-year (year)
12419 "Convert 2-digit years into 4-digit years.
12420 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12421 The year 2000 cannot be abbreviated. Any year larger than 99
12422 is returned unchanged."
12423 (if (< year 38)
12424 (setq year (+ 2000 year))
12425 (if (< year 100)
12426 (setq year (+ 1900 year))))
12427 year)
12429 (defun org-time-from-absolute (d)
12430 "Return the time corresponding to date D.
12431 D may be an absolute day number, or a calendar-type list (month day year)."
12432 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12433 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12435 (defun org-calendar-holiday ()
12436 "List of holidays, for Diary display in Org-mode."
12437 (require 'holidays)
12438 (let ((hl (funcall
12439 (if (fboundp 'calendar-check-holidays)
12440 'calendar-check-holidays 'check-calendar-holidays) date)))
12441 (if hl (mapconcat 'identity hl "; "))))
12443 (defun org-diary-sexp-entry (sexp entry date)
12444 "Process a SEXP diary ENTRY for DATE."
12445 (require 'diary-lib)
12446 (let ((result (if calendar-debug-sexp
12447 (let ((stack-trace-on-error t))
12448 (eval (car (read-from-string sexp))))
12449 (condition-case nil
12450 (eval (car (read-from-string sexp)))
12451 (error
12452 (beep)
12453 (message "Bad sexp at line %d in %s: %s"
12454 (org-current-line)
12455 (buffer-file-name) sexp)
12456 (sleep-for 2))))))
12457 (cond ((stringp result) result)
12458 ((and (consp result)
12459 (stringp (cdr result))) (cdr result))
12460 (result entry)
12461 (t nil))))
12463 (defun org-diary-to-ical-string (frombuf)
12464 "Get iCalendar entries from diary entries in buffer FROMBUF.
12465 This uses the icalendar.el library."
12466 (let* ((tmpdir (if (featurep 'xemacs)
12467 (temp-directory)
12468 temporary-file-directory))
12469 (tmpfile (make-temp-name
12470 (expand-file-name "orgics" tmpdir)))
12471 buf rtn b e)
12472 (save-excursion
12473 (set-buffer frombuf)
12474 (icalendar-export-region (point-min) (point-max) tmpfile)
12475 (setq buf (find-buffer-visiting tmpfile))
12476 (set-buffer buf)
12477 (goto-char (point-min))
12478 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12479 (setq b (match-beginning 0)))
12480 (goto-char (point-max))
12481 (if (re-search-backward "^END:VEVENT" nil t)
12482 (setq e (match-end 0)))
12483 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12484 (kill-buffer buf)
12485 (delete-file tmpfile)
12486 rtn))
12488 (defun org-closest-date (start current change prefer show-all)
12489 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12490 When PREFER is `past' return a date that is either CURRENT or past.
12491 When PREFER is `future', return a date that is either CURRENT or future.
12492 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12493 ;; Make the proper lists from the dates
12494 (catch 'exit
12495 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12496 dn dw sday cday n1 n2 n0
12497 d m y y1 y2 date1 date2 nmonths nm ny m2)
12499 (setq start (org-date-to-gregorian start)
12500 current (org-date-to-gregorian
12501 (if show-all
12502 current
12503 (time-to-days (current-time))))
12504 sday (calendar-absolute-from-gregorian start)
12505 cday (calendar-absolute-from-gregorian current))
12507 (if (<= cday sday) (throw 'exit sday))
12509 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12510 (setq dn (string-to-number (match-string 1 change))
12511 dw (cdr (assoc (match-string 2 change) a1)))
12512 (error "Invalid change specifyer: %s" change))
12513 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12514 (cond
12515 ((eq dw 'day)
12516 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12517 n2 (+ n1 dn)))
12518 ((eq dw 'year)
12519 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12520 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12521 (setq date1 (list m d y1)
12522 n1 (calendar-absolute-from-gregorian date1)
12523 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12524 n2 (calendar-absolute-from-gregorian date2)))
12525 ((eq dw 'month)
12526 ;; approx number of month between the two dates
12527 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12528 ;; How often does dn fit in there?
12529 (setq d (nth 1 start) m (car start) y (nth 2 start)
12530 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12531 m (+ m nm)
12532 ny (floor (/ m 12))
12533 y (+ y ny)
12534 m (- m (* ny 12)))
12535 (while (> m 12) (setq m (- m 12) y (1+ y)))
12536 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12537 (setq m2 (+ m dn) y2 y)
12538 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12539 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12540 (while (<= n2 cday)
12541 (setq n1 n2 m m2 y y2)
12542 (setq m2 (+ m dn) y2 y)
12543 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12544 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12545 ;; Make sure n1 is the earlier date
12546 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12547 (if show-all
12548 (cond
12549 ((eq prefer 'past) n1)
12550 ((eq prefer 'future) (if (= cday n1) n1 n2))
12551 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12552 (cond
12553 ((eq prefer 'past) n1)
12554 ((eq prefer 'future) (if (= cday n1) n1 n2))
12555 (t (if (= cday n1) n1 n2)))))))
12557 (defun org-date-to-gregorian (date)
12558 "Turn any specification of DATE into a gregorian date for the calendar."
12559 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12560 ((and (listp date) (= (length date) 3)) date)
12561 ((stringp date)
12562 (setq date (org-parse-time-string date))
12563 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12564 ((listp date)
12565 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12567 (defun org-parse-time-string (s &optional nodefault)
12568 "Parse the standard Org-mode time string.
12569 This should be a lot faster than the normal `parse-time-string'.
12570 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12571 hour and minute fields will be nil if not given."
12572 (if (string-match org-ts-regexp0 s)
12573 (list 0
12574 (if (or (match-beginning 8) (not nodefault))
12575 (string-to-number (or (match-string 8 s) "0")))
12576 (if (or (match-beginning 7) (not nodefault))
12577 (string-to-number (or (match-string 7 s) "0")))
12578 (string-to-number (match-string 4 s))
12579 (string-to-number (match-string 3 s))
12580 (string-to-number (match-string 2 s))
12581 nil nil nil)
12582 (make-list 9 0)))
12584 (defun org-timestamp-up (&optional arg)
12585 "Increase the date item at the cursor by one.
12586 If the cursor is on the year, change the year. If it is on the month or
12587 the day, change that.
12588 With prefix ARG, change by that many units."
12589 (interactive "p")
12590 (org-timestamp-change (prefix-numeric-value arg)))
12592 (defun org-timestamp-down (&optional arg)
12593 "Decrease the date item at the cursor by one.
12594 If the cursor is on the year, change the year. If it is on the month or
12595 the day, change that.
12596 With prefix ARG, change by that many units."
12597 (interactive "p")
12598 (org-timestamp-change (- (prefix-numeric-value arg))))
12600 (defun org-timestamp-up-day (&optional arg)
12601 "Increase the date in the time stamp by one day.
12602 With prefix ARG, change that many days."
12603 (interactive "p")
12604 (if (and (not (org-at-timestamp-p t))
12605 (org-on-heading-p))
12606 (org-todo 'up)
12607 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12609 (defun org-timestamp-down-day (&optional arg)
12610 "Decrease the date in the time stamp by one day.
12611 With prefix ARG, change that many days."
12612 (interactive "p")
12613 (if (and (not (org-at-timestamp-p t))
12614 (org-on-heading-p))
12615 (org-todo 'down)
12616 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12618 (defun org-at-timestamp-p (&optional inactive-ok)
12619 "Determine if the cursor is in or at a timestamp."
12620 (interactive)
12621 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12622 (pos (point))
12623 (ans (or (looking-at tsr)
12624 (save-excursion
12625 (skip-chars-backward "^[<\n\r\t")
12626 (if (> (point) (point-min)) (backward-char 1))
12627 (and (looking-at tsr)
12628 (> (- (match-end 0) pos) -1))))))
12629 (and ans
12630 (boundp 'org-ts-what)
12631 (setq org-ts-what
12632 (cond
12633 ((= pos (match-beginning 0)) 'bracket)
12634 ((= pos (1- (match-end 0))) 'bracket)
12635 ((org-pos-in-match-range pos 2) 'year)
12636 ((org-pos-in-match-range pos 3) 'month)
12637 ((org-pos-in-match-range pos 7) 'hour)
12638 ((org-pos-in-match-range pos 8) 'minute)
12639 ((or (org-pos-in-match-range pos 4)
12640 (org-pos-in-match-range pos 5)) 'day)
12641 ((and (> pos (or (match-end 8) (match-end 5)))
12642 (< pos (match-end 0)))
12643 (- pos (or (match-end 8) (match-end 5))))
12644 (t 'day))))
12645 ans))
12647 (defun org-toggle-timestamp-type ()
12648 "Toggle the type (<active> or [inactive]) of a time stamp."
12649 (interactive)
12650 (when (org-at-timestamp-p t)
12651 (let ((beg (match-beginning 0)) (end (match-end 0))
12652 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12653 (save-excursion
12654 (goto-char beg)
12655 (while (re-search-forward "[][<>]" end t)
12656 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12657 t t)))
12658 (message "Timestamp is now %sactive"
12659 (if (equal (char-after beg) ?<) "" "in")))))
12661 (defun org-timestamp-change (n &optional what)
12662 "Change the date in the time stamp at point.
12663 The date will be changed by N times WHAT. WHAT can be `day', `month',
12664 `year', `minute', `second'. If WHAT is not given, the cursor position
12665 in the timestamp determines what will be changed."
12666 (let ((pos (point))
12667 with-hm inactive
12668 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12669 org-ts-what
12670 extra rem
12671 ts time time0)
12672 (if (not (org-at-timestamp-p t))
12673 (error "Not at a timestamp"))
12674 (if (and (not what) (eq org-ts-what 'bracket))
12675 (org-toggle-timestamp-type)
12676 (if (and (not what) (not (eq org-ts-what 'day))
12677 org-display-custom-times
12678 (get-text-property (point) 'display)
12679 (not (get-text-property (1- (point)) 'display)))
12680 (setq org-ts-what 'day))
12681 (setq org-ts-what (or what org-ts-what)
12682 inactive (= (char-after (match-beginning 0)) ?\[)
12683 ts (match-string 0))
12684 (replace-match "")
12685 (if (string-match
12686 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12688 (setq extra (match-string 1 ts)))
12689 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12690 (setq with-hm t))
12691 (setq time0 (org-parse-time-string ts))
12692 (when (and (eq org-ts-what 'minute)
12693 (eq current-prefix-arg nil))
12694 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12695 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12696 (setcar (cdr time0) (+ (nth 1 time0)
12697 (if (> n 0) (- rem) (- dm rem))))))
12698 (setq time
12699 (encode-time (or (car time0) 0)
12700 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12701 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12702 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12703 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12704 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12705 (nthcdr 6 time0)))
12706 (when (and (member org-ts-what '(hour minute))
12707 extra
12708 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
12709 (setq extra (org-modify-ts-extra
12710 extra
12711 (if (eq org-ts-what 'hour) 2 5)
12712 n dm)))
12713 (when (integerp org-ts-what)
12714 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12715 (if (eq what 'calendar)
12716 (let ((cal-date (org-get-date-from-calendar)))
12717 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12718 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12719 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12720 (setcar time0 (or (car time0) 0))
12721 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12722 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12723 (setq time (apply 'encode-time time0))))
12724 (setq org-last-changed-timestamp
12725 (org-insert-time-stamp time with-hm inactive nil nil extra))
12726 (org-clock-update-time-maybe)
12727 (goto-char pos)
12728 ;; Try to recenter the calendar window, if any
12729 (if (and org-calendar-follow-timestamp-change
12730 (get-buffer-window "*Calendar*" t)
12731 (memq org-ts-what '(day month year)))
12732 (org-recenter-calendar (time-to-days time))))))
12734 (defun org-modify-ts-extra (s pos n dm)
12735 "Change the different parts of the lead-time and repeat fields in timestamp."
12736 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12737 ng h m new rem)
12738 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12739 (cond
12740 ((or (org-pos-in-match-range pos 2)
12741 (org-pos-in-match-range pos 3))
12742 (setq m (string-to-number (match-string 3 s))
12743 h (string-to-number (match-string 2 s)))
12744 (if (org-pos-in-match-range pos 2)
12745 (setq h (+ h n))
12746 (setq n (* dm (org-no-warnings (signum n))))
12747 (when (not (= 0 (setq rem (% m dm))))
12748 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12749 (setq m (+ m n)))
12750 (if (< m 0) (setq m (+ m 60) h (1- h)))
12751 (if (> m 59) (setq m (- m 60) h (1+ h)))
12752 (setq h (min 24 (max 0 h)))
12753 (setq ng 1 new (format "-%02d:%02d" h m)))
12754 ((org-pos-in-match-range pos 6)
12755 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12756 ((org-pos-in-match-range pos 5)
12757 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12759 ((org-pos-in-match-range pos 9)
12760 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12761 ((org-pos-in-match-range pos 8)
12762 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12764 (when ng
12765 (setq s (concat
12766 (substring s 0 (match-beginning ng))
12768 (substring s (match-end ng))))))
12771 (defun org-recenter-calendar (date)
12772 "If the calendar is visible, recenter it to DATE."
12773 (let* ((win (selected-window))
12774 (cwin (get-buffer-window "*Calendar*" t))
12775 (calendar-move-hook nil))
12776 (when cwin
12777 (select-window cwin)
12778 (calendar-goto-date (if (listp date) date
12779 (calendar-gregorian-from-absolute date)))
12780 (select-window win))))
12782 (defun org-goto-calendar (&optional arg)
12783 "Go to the Emacs calendar at the current date.
12784 If there is a time stamp in the current line, go to that date.
12785 A prefix ARG can be used to force the current date."
12786 (interactive "P")
12787 (let ((tsr org-ts-regexp) diff
12788 (calendar-move-hook nil)
12789 (calendar-view-holidays-initially-flag nil)
12790 (view-calendar-holidays-initially nil)
12791 (calendar-view-diary-initially-flag nil)
12792 (view-diary-entries-initially nil))
12793 (if (or (org-at-timestamp-p)
12794 (save-excursion
12795 (beginning-of-line 1)
12796 (looking-at (concat ".*" tsr))))
12797 (let ((d1 (time-to-days (current-time)))
12798 (d2 (time-to-days
12799 (org-time-string-to-time (match-string 1)))))
12800 (setq diff (- d2 d1))))
12801 (calendar)
12802 (calendar-goto-today)
12803 (if (and diff (not arg)) (calendar-forward-day diff))))
12805 (defun org-get-date-from-calendar ()
12806 "Return a list (month day year) of date at point in calendar."
12807 (with-current-buffer "*Calendar*"
12808 (save-match-data
12809 (calendar-cursor-to-date))))
12811 (defun org-date-from-calendar ()
12812 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12813 If there is already a time stamp at the cursor position, update it."
12814 (interactive)
12815 (if (org-at-timestamp-p t)
12816 (org-timestamp-change 0 'calendar)
12817 (let ((cal-date (org-get-date-from-calendar)))
12818 (org-insert-time-stamp
12819 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12821 (defun org-minutes-to-hh:mm-string (m)
12822 "Compute H:MM from a number of minutes."
12823 (let ((h (/ m 60)))
12824 (setq m (- m (* 60 h)))
12825 (format org-time-clocksum-format h m)))
12827 (defun org-hh:mm-string-to-minutes (s)
12828 "Convert a string H:MM to a number of minutes."
12829 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12830 (+ (* (string-to-number (match-string 1 s)) 60)
12831 (string-to-number (match-string 2 s)))
12834 ;;;; Files
12836 (defun org-save-all-org-buffers ()
12837 "Save all Org-mode buffers without user confirmation."
12838 (interactive)
12839 (message "Saving all Org-mode buffers...")
12840 (save-some-buffers t 'org-mode-p)
12841 (when (featurep 'org-id) (org-id-locations-save))
12842 (message "Saving all Org-mode buffers... done"))
12844 (defun org-revert-all-org-buffers ()
12845 "Revert all Org-mode buffers.
12846 Prompt for confirmation when there are unsaved changes.
12847 Be sure you know what you are doing before letting this function
12848 overwrite your changes.
12850 This function is useful in a setup where one tracks org files
12851 with a version control system, to revert on one machine after pulling
12852 changes from another. I believe the procedure must be like this:
12854 1. M-x org-save-all-org-buffers
12855 2. Pull changes from the other machine, resolve conflicts
12856 3. M-x org-revert-all-org-buffers"
12857 (interactive)
12858 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
12859 (error "Abort"))
12860 (save-excursion
12861 (save-window-excursion
12862 (mapc
12863 (lambda (b)
12864 (when (and (with-current-buffer b (org-mode-p))
12865 (with-current-buffer b buffer-file-name))
12866 (switch-to-buffer b)
12867 (revert-buffer t 'no-confirm)))
12868 (buffer-list))
12869 (when (and (featurep 'org-id) org-id-track-globally)
12870 (org-id-locations-load)))))
12872 ;;;; Agenda files
12874 ;;;###autoload
12875 (defun org-iswitchb (&optional arg)
12876 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12877 With a prefix argument, restrict available to files.
12878 With two prefix arguments, restrict available buffers to agenda files.
12880 Due to some yet unresolved reason, the global function
12881 `iswitchb-mode' needs to be active for this function to work."
12882 (interactive "P")
12883 (require 'iswitchb)
12884 (let ((enabled iswitchb-mode) blist)
12885 (or enabled (iswitchb-mode 1))
12886 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12887 ((equal arg '(16)) (org-buffer-list 'agenda))
12888 (t (org-buffer-list))))
12889 (unwind-protect
12890 (let ((iswitchb-make-buflist-hook
12891 (lambda ()
12892 (setq iswitchb-temp-buflist
12893 (mapcar 'buffer-name blist)))))
12894 (switch-to-buffer
12895 (iswitchb-read-buffer
12896 "Switch-to: " nil t))
12897 (or enabled (iswitchb-mode -1))))))
12899 ;;;###autoload
12900 (defun org-ido-switchb (&optional arg)
12901 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12902 With a prefix argument, restrict available to files.
12903 With two prefix arguments, restrict available buffers to agenda files."
12904 (interactive "P")
12905 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12906 ((equal arg '(16)) (org-buffer-list 'agenda))
12907 (t (org-buffer-list)))))
12908 (switch-to-buffer
12909 (org-ido-completing-read "Org buffer: "
12910 (mapcar 'list (mapcar 'buffer-name blist))
12911 nil t))))
12913 (defun org-buffer-list (&optional predicate exclude-tmp)
12914 "Return a list of Org buffers.
12915 PREDICATE can be `export', `files' or `agenda'.
12917 export restrict the list to Export buffers.
12918 files restrict the list to buffers visiting Org files.
12919 agenda restrict the list to buffers visiting agenda files.
12921 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12922 (let* ((bfn nil)
12923 (agenda-files (and (eq predicate 'agenda)
12924 (mapcar 'file-truename (org-agenda-files t))))
12925 (filter
12926 (cond
12927 ((eq predicate 'files)
12928 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12929 ((eq predicate 'export)
12930 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12931 ((eq predicate 'agenda)
12932 (lambda (b)
12933 (with-current-buffer b
12934 (and (eq major-mode 'org-mode)
12935 (setq bfn (buffer-file-name b))
12936 (member (file-truename bfn) agenda-files)))))
12937 (t (lambda (b) (with-current-buffer b
12938 (or (eq major-mode 'org-mode)
12939 (string-match "\*Org .*Export"
12940 (buffer-name b)))))))))
12941 (delq nil
12942 (mapcar
12943 (lambda(b)
12944 (if (and (funcall filter b)
12945 (or (not exclude-tmp)
12946 (not (string-match "tmp" (buffer-name b)))))
12948 nil))
12949 (buffer-list)))))
12951 (defun org-agenda-files (&optional unrestricted archives)
12952 "Get the list of agenda files.
12953 Optional UNRESTRICTED means return the full list even if a restriction
12954 is currently in place.
12955 When ARCHIVES is t, include all archive files hat are really being
12956 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12957 `org-agenda-archives-mode' is t."
12958 (let ((files
12959 (cond
12960 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12961 ((stringp org-agenda-files) (org-read-agenda-file-list))
12962 ((listp org-agenda-files) org-agenda-files)
12963 (t (error "Invalid value of `org-agenda-files'")))))
12964 (setq files (apply 'append
12965 (mapcar (lambda (f)
12966 (if (file-directory-p f)
12967 (directory-files
12968 f t org-agenda-file-regexp)
12969 (list f)))
12970 files)))
12971 (when org-agenda-skip-unavailable-files
12972 (setq files (delq nil
12973 (mapcar (function
12974 (lambda (file)
12975 (and (file-readable-p file) file)))
12976 files))))
12977 (when (or (eq archives t)
12978 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12979 (setq files (org-add-archive-files files)))
12980 files))
12982 (defun org-edit-agenda-file-list ()
12983 "Edit the list of agenda files.
12984 Depending on setup, this either uses customize to edit the variable
12985 `org-agenda-files', or it visits the file that is holding the list. In the
12986 latter case, the buffer is set up in a way that saving it automatically kills
12987 the buffer and restores the previous window configuration."
12988 (interactive)
12989 (if (stringp org-agenda-files)
12990 (let ((cw (current-window-configuration)))
12991 (find-file org-agenda-files)
12992 (org-set-local 'org-window-configuration cw)
12993 (org-add-hook 'after-save-hook
12994 (lambda ()
12995 (set-window-configuration
12996 (prog1 org-window-configuration
12997 (kill-buffer (current-buffer))))
12998 (org-install-agenda-files-menu)
12999 (message "New agenda file list installed"))
13000 nil 'local)
13001 (message "%s" (substitute-command-keys
13002 "Edit list and finish with \\[save-buffer]")))
13003 (customize-variable 'org-agenda-files)))
13005 (defun org-store-new-agenda-file-list (list)
13006 "Set new value for the agenda file list and save it correctly."
13007 (if (stringp org-agenda-files)
13008 (let ((f org-agenda-files) b)
13009 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13010 (with-temp-file f
13011 (insert (mapconcat 'identity list "\n") "\n")))
13012 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13013 (setq org-agenda-files list)
13014 (customize-save-variable 'org-agenda-files org-agenda-files))))
13016 (defun org-read-agenda-file-list ()
13017 "Read the list of agenda files from a file."
13018 (when (file-directory-p org-agenda-files)
13019 (error "`org-agenda-files' cannot be a single directory"))
13020 (when (stringp org-agenda-files)
13021 (with-temp-buffer
13022 (insert-file-contents org-agenda-files)
13023 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13026 ;;;###autoload
13027 (defun org-cycle-agenda-files ()
13028 "Cycle through the files in `org-agenda-files'.
13029 If the current buffer visits an agenda file, find the next one in the list.
13030 If the current buffer does not, find the first agenda file."
13031 (interactive)
13032 (let* ((fs (org-agenda-files t))
13033 (files (append fs (list (car fs))))
13034 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13035 file)
13036 (unless files (error "No agenda files"))
13037 (catch 'exit
13038 (while (setq file (pop files))
13039 (if (equal (file-truename file) tcf)
13040 (when (car files)
13041 (find-file (car files))
13042 (throw 'exit t))))
13043 (find-file (car fs)))
13044 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13046 (defun org-agenda-file-to-front (&optional to-end)
13047 "Move/add the current file to the top of the agenda file list.
13048 If the file is not present in the list, it is added to the front. If it is
13049 present, it is moved there. With optional argument TO-END, add/move to the
13050 end of the list."
13051 (interactive "P")
13052 (let ((org-agenda-skip-unavailable-files nil)
13053 (file-alist (mapcar (lambda (x)
13054 (cons (file-truename x) x))
13055 (org-agenda-files t)))
13056 (ctf (file-truename buffer-file-name))
13057 x had)
13058 (setq x (assoc ctf file-alist) had x)
13060 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13061 (if to-end
13062 (setq file-alist (append (delq x file-alist) (list x)))
13063 (setq file-alist (cons x (delq x file-alist))))
13064 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13065 (org-install-agenda-files-menu)
13066 (message "File %s to %s of agenda file list"
13067 (if had "moved" "added") (if to-end "end" "front"))))
13069 (defun org-remove-file (&optional file)
13070 "Remove current file from the list of files in variable `org-agenda-files'.
13071 These are the files which are being checked for agenda entries.
13072 Optional argument FILE means, use this file instead of the current."
13073 (interactive)
13074 (let* ((org-agenda-skip-unavailable-files nil)
13075 (file (or file buffer-file-name))
13076 (true-file (file-truename file))
13077 (afile (abbreviate-file-name file))
13078 (files (delq nil (mapcar
13079 (lambda (x)
13080 (if (equal true-file
13081 (file-truename x))
13082 nil x))
13083 (org-agenda-files t)))))
13084 (if (not (= (length files) (length (org-agenda-files t))))
13085 (progn
13086 (org-store-new-agenda-file-list files)
13087 (org-install-agenda-files-menu)
13088 (message "Removed file: %s" afile))
13089 (message "File was not in list: %s (not removed)" afile))))
13091 (defun org-file-menu-entry (file)
13092 (vector file (list 'find-file file) t))
13094 (defun org-check-agenda-file (file)
13095 "Make sure FILE exists. If not, ask user what to do."
13096 (when (not (file-exists-p file))
13097 (message "non-existent file %s. [R]emove from list or [A]bort?"
13098 (abbreviate-file-name file))
13099 (let ((r (downcase (read-char-exclusive))))
13100 (cond
13101 ((equal r ?r)
13102 (org-remove-file file)
13103 (throw 'nextfile t))
13104 (t (error "Abort"))))))
13106 (defun org-get-agenda-file-buffer (file)
13107 "Get a buffer visiting FILE. If the buffer needs to be created, add
13108 it to the list of buffers which might be released later."
13109 (let ((buf (org-find-base-buffer-visiting file)))
13110 (if buf
13111 buf ; just return it
13112 ;; Make a new buffer and remember it
13113 (setq buf (find-file-noselect file))
13114 (if buf (push buf org-agenda-new-buffers))
13115 buf)))
13117 (defun org-release-buffers (blist)
13118 "Release all buffers in list, asking the user for confirmation when needed.
13119 When a buffer is unmodified, it is just killed. When modified, it is saved
13120 \(if the user agrees) and then killed."
13121 (let (buf file)
13122 (while (setq buf (pop blist))
13123 (setq file (buffer-file-name buf))
13124 (when (and (buffer-modified-p buf)
13125 file
13126 (y-or-n-p (format "Save file %s? " file)))
13127 (with-current-buffer buf (save-buffer)))
13128 (kill-buffer buf))))
13130 (defun org-prepare-agenda-buffers (files)
13131 "Create buffers for all agenda files, protect archived trees and comments."
13132 (interactive)
13133 (let ((pa '(:org-archived t))
13134 (pc '(:org-comment t))
13135 (pall '(:org-archived t :org-comment t))
13136 (inhibit-read-only t)
13137 (rea (concat ":" org-archive-tag ":"))
13138 bmp file re)
13139 (save-excursion
13140 (save-restriction
13141 (while (setq file (pop files))
13142 (if (bufferp file)
13143 (set-buffer file)
13144 (org-check-agenda-file file)
13145 (set-buffer (org-get-agenda-file-buffer file)))
13146 (widen)
13147 (setq bmp (buffer-modified-p))
13148 (org-refresh-category-properties)
13149 (setq org-todo-keywords-for-agenda
13150 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13151 (setq org-done-keywords-for-agenda
13152 (append org-done-keywords-for-agenda org-done-keywords))
13153 (setq org-todo-keyword-alist-for-agenda
13154 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13155 (setq org-tag-alist-for-agenda
13156 (append org-tag-alist-for-agenda org-tag-alist))
13158 (save-excursion
13159 (remove-text-properties (point-min) (point-max) pall)
13160 (when org-agenda-skip-archived-trees
13161 (goto-char (point-min))
13162 (while (re-search-forward rea nil t)
13163 (if (org-on-heading-p t)
13164 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13165 (goto-char (point-min))
13166 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13167 (while (re-search-forward re nil t)
13168 (add-text-properties
13169 (match-beginning 0) (org-end-of-subtree t) pc)))
13170 (set-buffer-modified-p bmp))))
13171 (setq org-todo-keyword-alist-for-agenda
13172 (org-uniquify org-todo-keyword-alist-for-agenda)
13173 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13175 ;;;; Embedded LaTeX
13177 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13178 "Keymap for the minor `org-cdlatex-mode'.")
13180 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13181 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13182 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13183 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13184 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13186 (defvar org-cdlatex-texmathp-advice-is-done nil
13187 "Flag remembering if we have applied the advice to texmathp already.")
13189 (define-minor-mode org-cdlatex-mode
13190 "Toggle the minor `org-cdlatex-mode'.
13191 This mode supports entering LaTeX environment and math in LaTeX fragments
13192 in Org-mode.
13193 \\{org-cdlatex-mode-map}"
13194 nil " OCDL" nil
13195 (when org-cdlatex-mode (require 'cdlatex))
13196 (unless org-cdlatex-texmathp-advice-is-done
13197 (setq org-cdlatex-texmathp-advice-is-done t)
13198 (defadvice texmathp (around org-math-always-on activate)
13199 "Always return t in org-mode buffers.
13200 This is because we want to insert math symbols without dollars even outside
13201 the LaTeX math segments. If Orgmode thinks that point is actually inside
13202 an embedded LaTeX fragment, let texmathp do its job.
13203 \\[org-cdlatex-mode-map]"
13204 (interactive)
13205 (let (p)
13206 (cond
13207 ((not (org-mode-p)) ad-do-it)
13208 ((eq this-command 'cdlatex-math-symbol)
13209 (setq ad-return-value t
13210 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13212 (let ((p (org-inside-LaTeX-fragment-p)))
13213 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13214 (setq ad-return-value t
13215 texmathp-why '("Org-mode embedded math" . 0))
13216 (if p ad-do-it)))))))))
13218 (defun turn-on-org-cdlatex ()
13219 "Unconditionally turn on `org-cdlatex-mode'."
13220 (org-cdlatex-mode 1))
13222 (defun org-inside-LaTeX-fragment-p ()
13223 "Test if point is inside a LaTeX fragment.
13224 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13225 sequence appearing also before point.
13226 Even though the matchers for math are configurable, this function assumes
13227 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13228 delimiters are skipped when they have been removed by customization.
13229 The return value is nil, or a cons cell with the delimiter and
13230 and the position of this delimiter.
13232 This function does a reasonably good job, but can locally be fooled by
13233 for example currency specifications. For example it will assume being in
13234 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13235 fragments that are properly closed, but during editing, we have to live
13236 with the uncertainty caused by missing closing delimiters. This function
13237 looks only before point, not after."
13238 (catch 'exit
13239 (let ((pos (point))
13240 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13241 (lim (progn
13242 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13243 (point)))
13244 dd-on str (start 0) m re)
13245 (goto-char pos)
13246 (when dodollar
13247 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13248 re (nth 1 (assoc "$" org-latex-regexps)))
13249 (while (string-match re str start)
13250 (cond
13251 ((= (match-end 0) (length str))
13252 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13253 ((= (match-end 0) (- (length str) 5))
13254 (throw 'exit nil))
13255 (t (setq start (match-end 0))))))
13256 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13257 (goto-char pos)
13258 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13259 (and (match-beginning 2) (throw 'exit nil))
13260 ;; count $$
13261 (while (re-search-backward "\\$\\$" lim t)
13262 (setq dd-on (not dd-on)))
13263 (goto-char pos)
13264 (if dd-on (cons "$$" m))))))
13267 (defun org-try-cdlatex-tab ()
13268 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13269 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13270 - inside a LaTeX fragment, or
13271 - after the first word in a line, where an abbreviation expansion could
13272 insert a LaTeX environment."
13273 (when org-cdlatex-mode
13274 (cond
13275 ((save-excursion
13276 (skip-chars-backward "a-zA-Z0-9*")
13277 (skip-chars-backward " \t")
13278 (bolp))
13279 (cdlatex-tab) t)
13280 ((org-inside-LaTeX-fragment-p)
13281 (cdlatex-tab) t)
13282 (t nil))))
13284 (defun org-cdlatex-underscore-caret (&optional arg)
13285 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13286 Revert to the normal definition outside of these fragments."
13287 (interactive "P")
13288 (if (org-inside-LaTeX-fragment-p)
13289 (call-interactively 'cdlatex-sub-superscript)
13290 (let (org-cdlatex-mode)
13291 (call-interactively (key-binding (vector last-input-event))))))
13293 (defun org-cdlatex-math-modify (&optional arg)
13294 "Execute `cdlatex-math-modify' in LaTeX fragments.
13295 Revert to the normal definition outside of these fragments."
13296 (interactive "P")
13297 (if (org-inside-LaTeX-fragment-p)
13298 (call-interactively 'cdlatex-math-modify)
13299 (let (org-cdlatex-mode)
13300 (call-interactively (key-binding (vector last-input-event))))))
13302 (defvar org-latex-fragment-image-overlays nil
13303 "List of overlays carrying the images of latex fragments.")
13304 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13306 (defun org-remove-latex-fragment-image-overlays ()
13307 "Remove all overlays with LaTeX fragment images in current buffer."
13308 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13309 (setq org-latex-fragment-image-overlays nil))
13311 (defun org-preview-latex-fragment (&optional subtree)
13312 "Preview the LaTeX fragment at point, or all locally or globally.
13313 If the cursor is in a LaTeX fragment, create the image and overlay
13314 it over the source code. If there is no fragment at point, display
13315 all fragments in the current text, from one headline to the next. With
13316 prefix SUBTREE, display all fragments in the current subtree. With a
13317 double prefix `C-u C-u', or when the cursor is before the first headline,
13318 display all fragments in the buffer.
13319 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13320 (interactive "P")
13321 (org-remove-latex-fragment-image-overlays)
13322 (save-excursion
13323 (save-restriction
13324 (let (beg end at msg)
13325 (cond
13326 ((or (equal subtree '(16))
13327 (not (save-excursion
13328 (re-search-backward (concat "^" outline-regexp) nil t))))
13329 (setq beg (point-min) end (point-max)
13330 msg "Creating images for buffer...%s"))
13331 ((equal subtree '(4))
13332 (org-back-to-heading)
13333 (setq beg (point) end (org-end-of-subtree t)
13334 msg "Creating images for subtree...%s"))
13336 (if (setq at (org-inside-LaTeX-fragment-p))
13337 (goto-char (max (point-min) (- (cdr at) 2)))
13338 (org-back-to-heading))
13339 (setq beg (point) end (progn (outline-next-heading) (point))
13340 msg (if at "Creating image...%s"
13341 "Creating images for entry...%s"))))
13342 (message msg "")
13343 (narrow-to-region beg end)
13344 (goto-char beg)
13345 (org-format-latex
13346 (concat "ltxpng/" (file-name-sans-extension
13347 (file-name-nondirectory
13348 buffer-file-name)))
13349 default-directory 'overlays msg at 'forbuffer)
13350 (message msg "done. Use `C-c C-c' to remove images.")))))
13352 (defvar org-latex-regexps
13353 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13354 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13355 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13356 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13357 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13358 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13359 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13360 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13361 "Regular expressions for matching embedded LaTeX.")
13363 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13364 "Replace LaTeX fragments with links to an image, and produce images."
13365 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13366 (let* ((prefixnodir (file-name-nondirectory prefix))
13367 (absprefix (expand-file-name prefix dir))
13368 (todir (file-name-directory absprefix))
13369 (opt org-format-latex-options)
13370 (matchers (plist-get opt :matchers))
13371 (re-list org-latex-regexps)
13372 (cnt 0) txt link beg end re e checkdir
13373 m n block linkfile movefile ov)
13374 ;; Check if there are old images files with this prefix, and remove them
13375 (when (file-directory-p todir)
13376 (mapc 'delete-file
13377 (directory-files
13378 todir 'full
13379 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13380 ;; Check the different regular expressions
13381 (while (setq e (pop re-list))
13382 (setq m (car e) re (nth 1 e) n (nth 2 e)
13383 block (if (nth 3 e) "\n\n" ""))
13384 (when (member m matchers)
13385 (goto-char (point-min))
13386 (while (re-search-forward re nil t)
13387 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13388 (not (get-text-property (match-beginning n)
13389 'org-protected)))
13390 (setq txt (match-string n)
13391 beg (match-beginning n) end (match-end n)
13392 cnt (1+ cnt)
13393 linkfile (format "%s_%04d.png" prefix cnt)
13394 movefile (format "%s_%04d.png" absprefix cnt)
13395 link (concat block "[[file:" linkfile "]]" block))
13396 (if msg (message msg cnt))
13397 (goto-char beg)
13398 (unless checkdir ; make sure the directory exists
13399 (setq checkdir t)
13400 (or (file-directory-p todir) (make-directory todir)))
13401 (org-create-formula-image
13402 txt movefile opt forbuffer)
13403 (if overlays
13404 (progn
13405 (setq ov (org-make-overlay beg end))
13406 (if (featurep 'xemacs)
13407 (progn
13408 (org-overlay-put ov 'invisible t)
13409 (org-overlay-put
13410 ov 'end-glyph
13411 (make-glyph (vector 'png :file movefile))))
13412 (org-overlay-put
13413 ov 'display
13414 (list 'image :type 'png :file movefile :ascent 'center)))
13415 (push ov org-latex-fragment-image-overlays)
13416 (goto-char end))
13417 (delete-region beg end)
13418 (insert link))))))))
13420 ;; This function borrows from Ganesh Swami's latex2png.el
13421 (defun org-create-formula-image (string tofile options buffer)
13422 (let* ((tmpdir (if (featurep 'xemacs)
13423 (temp-directory)
13424 temporary-file-directory))
13425 (texfilebase (make-temp-name
13426 (expand-file-name "orgtex" tmpdir)))
13427 (texfile (concat texfilebase ".tex"))
13428 (dvifile (concat texfilebase ".dvi"))
13429 (pngfile (concat texfilebase ".png"))
13430 (fnh (if (featurep 'xemacs)
13431 (font-height (get-face-font 'default))
13432 (face-attribute 'default :height nil)))
13433 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13434 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13435 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13436 "Black"))
13437 (bg (or (plist-get options (if buffer :background :html-background))
13438 "Transparent")))
13439 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13440 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13441 (with-temp-file texfile
13442 (insert org-format-latex-header
13443 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13444 (let ((dir default-directory))
13445 (condition-case nil
13446 (progn
13447 (cd tmpdir)
13448 (call-process "latex" nil nil nil texfile))
13449 (error nil))
13450 (cd dir))
13451 (if (not (file-exists-p dvifile))
13452 (progn (message "Failed to create dvi file from %s" texfile) nil)
13453 (condition-case nil
13454 (call-process "dvipng" nil nil nil
13455 "-E" "-fg" fg "-bg" bg
13456 "-D" dpi
13457 ;;"-x" scale "-y" scale
13458 "-T" "tight"
13459 "-o" pngfile
13460 dvifile)
13461 (error nil))
13462 (if (not (file-exists-p pngfile))
13463 (progn (message "Failed to create png file from %s" texfile) nil)
13464 ;; Use the requested file name and clean up
13465 (copy-file pngfile tofile 'replace)
13466 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13467 (delete-file (concat texfilebase e)))
13468 pngfile))))
13470 (defun org-dvipng-color (attr)
13471 "Return an rgb color specification for dvipng."
13472 (apply 'format "rgb %s %s %s"
13473 (mapcar 'org-normalize-color
13474 (color-values (face-attribute 'default attr nil)))))
13476 (defun org-normalize-color (value)
13477 "Return string to be used as color value for an RGB component."
13478 (format "%g" (/ value 65535.0)))
13480 ;;;; Key bindings
13482 ;; Make `C-c C-x' a prefix key
13483 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13485 ;; TAB key with modifiers
13486 (org-defkey org-mode-map "\C-i" 'org-cycle)
13487 (org-defkey org-mode-map [(tab)] 'org-cycle)
13488 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13489 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13490 (org-defkey org-mode-map "\M-\t" 'org-complete)
13491 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13492 ;; The following line is necessary under Suse GNU/Linux
13493 (unless (featurep 'xemacs)
13494 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13495 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13496 (define-key org-mode-map [backtab] 'org-shifttab)
13498 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13499 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13500 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13502 ;; Cursor keys with modifiers
13503 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13504 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13505 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13506 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13508 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13509 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13510 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13511 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13513 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13514 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13515 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13516 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13518 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13519 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13521 ;;; Extra keys for tty access.
13522 ;; We only set them when really needed because otherwise the
13523 ;; menus don't show the simple keys
13525 (when (or org-use-extra-keys
13526 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13527 (not window-system))
13528 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13529 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13530 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13531 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13532 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13533 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13534 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13535 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13536 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13537 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13538 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13539 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13540 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13541 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13542 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13543 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13544 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13545 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13546 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13547 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13548 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13549 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13551 ;; All the other keys
13553 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13554 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13555 (if (boundp 'narrow-map)
13556 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13557 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13558 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13559 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13560 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13561 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13562 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13563 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13564 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13565 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13566 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13567 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13568 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13569 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13570 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13571 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13572 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13573 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13574 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13575 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13576 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13577 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13578 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13579 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13580 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13581 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13582 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13583 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13584 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13585 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13586 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13587 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13588 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13589 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13590 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13591 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13592 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13593 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13594 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13595 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13596 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13597 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13598 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13599 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13600 (org-defkey org-mode-map "\C-c^" 'org-sort)
13601 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13602 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13603 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13604 (org-defkey org-mode-map "\C-m" 'org-return)
13605 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13606 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13607 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13608 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13609 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13610 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13611 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13612 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13613 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13614 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13615 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13616 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13617 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13618 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13619 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13620 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13621 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13623 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13624 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13625 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13626 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13628 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13629 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13630 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13631 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13632 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13633 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13634 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13635 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13636 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13637 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13638 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13639 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13640 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13642 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13643 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13644 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13645 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13647 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13649 (define-key org-mode-map "\C-c\C-xr" 'org-reload)
13651 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
13652 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
13654 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
13657 (when (featurep 'xemacs)
13658 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13661 (defvar org-self-insert-command-undo-counter 0)
13663 (defvar org-table-auto-blank-field) ; defined in org-table.el
13664 (defun org-self-insert-command (N)
13665 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13666 If the cursor is in a table looking at whitespace, the whitespace is
13667 overwritten, and the table is not marked as requiring realignment."
13668 (interactive "p")
13669 (if (and
13670 (org-table-p)
13671 (progn
13672 ;; check if we blank the field, and if that triggers align
13673 (and (featurep 'org-table) org-table-auto-blank-field
13674 (member last-command
13675 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13676 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13677 ;; got extra space, this field does not determine column width
13678 (let (org-table-may-need-update) (org-table-blank-field))
13679 ;; no extra space, this field may determine column width
13680 (org-table-blank-field)))
13682 (eq N 1)
13683 (looking-at "[^|\n]* |"))
13684 (let (org-table-may-need-update)
13685 (goto-char (1- (match-end 0)))
13686 (delete-backward-char 1)
13687 (goto-char (match-beginning 0))
13688 (self-insert-command N))
13689 (setq org-table-may-need-update t)
13690 (self-insert-command N)
13691 (org-fix-tags-on-the-fly)
13692 (if org-self-insert-cluster-for-undo
13693 (if (not (eq last-command 'org-self-insert-command))
13694 (setq org-self-insert-command-undo-counter 1)
13695 (if (>= org-self-insert-command-undo-counter 20)
13696 (setq org-self-insert-command-undo-counter 1)
13697 (and (> org-self-insert-command-undo-counter 0)
13698 buffer-undo-list
13699 (not (cadr buffer-undo-list)) ; remove nil entry
13700 (setcdr buffer-undo-list (cddr buffer-undo-list)))
13701 (setq org-self-insert-command-undo-counter
13702 (1+ org-self-insert-command-undo-counter)))))))
13704 (defun org-fix-tags-on-the-fly ()
13705 (when (and (equal (char-after (point-at-bol)) ?*)
13706 (org-on-heading-p))
13707 (org-align-tags-here org-tags-column)))
13709 (defun org-delete-backward-char (N)
13710 "Like `delete-backward-char', insert whitespace at field end in tables.
13711 When deleting backwards, in tables this function will insert whitespace in
13712 front of the next \"|\" separator, to keep the table aligned. The table will
13713 still be marked for re-alignment if the field did fill the entire column,
13714 because, in this case the deletion might narrow the column."
13715 (interactive "p")
13716 (if (and (org-table-p)
13717 (eq N 1)
13718 (string-match "|" (buffer-substring (point-at-bol) (point)))
13719 (looking-at ".*?|"))
13720 (let ((pos (point))
13721 (noalign (looking-at "[^|\n\r]* |"))
13722 (c org-table-may-need-update))
13723 (backward-delete-char N)
13724 (skip-chars-forward "^|")
13725 (insert " ")
13726 (goto-char (1- pos))
13727 ;; noalign: if there were two spaces at the end, this field
13728 ;; does not determine the width of the column.
13729 (if noalign (setq org-table-may-need-update c)))
13730 (backward-delete-char N)
13731 (org-fix-tags-on-the-fly)))
13733 (defun org-delete-char (N)
13734 "Like `delete-char', but insert whitespace at field end in tables.
13735 When deleting characters, in tables this function will insert whitespace in
13736 front of the next \"|\" separator, to keep the table aligned. The table will
13737 still be marked for re-alignment if the field did fill the entire column,
13738 because, in this case the deletion might narrow the column."
13739 (interactive "p")
13740 (if (and (org-table-p)
13741 (not (bolp))
13742 (not (= (char-after) ?|))
13743 (eq N 1))
13744 (if (looking-at ".*?|")
13745 (let ((pos (point))
13746 (noalign (looking-at "[^|\n\r]* |"))
13747 (c org-table-may-need-update))
13748 (replace-match (concat
13749 (substring (match-string 0) 1 -1)
13750 " |"))
13751 (goto-char pos)
13752 ;; noalign: if there were two spaces at the end, this field
13753 ;; does not determine the width of the column.
13754 (if noalign (setq org-table-may-need-update c)))
13755 (delete-char N))
13756 (delete-char N)
13757 (org-fix-tags-on-the-fly)))
13759 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13760 (put 'org-self-insert-command 'delete-selection t)
13761 (put 'orgtbl-self-insert-command 'delete-selection t)
13762 (put 'org-delete-char 'delete-selection 'supersede)
13763 (put 'org-delete-backward-char 'delete-selection 'supersede)
13764 (put 'org-yank 'delete-selection 'yank)
13766 ;; Make `flyspell-mode' delay after some commands
13767 (put 'org-self-insert-command 'flyspell-delayed t)
13768 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13769 (put 'org-delete-char 'flyspell-delayed t)
13770 (put 'org-delete-backward-char 'flyspell-delayed t)
13772 ;; Make pabbrev-mode expand after org-mode commands
13773 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13774 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13776 ;; How to do this: Measure non-white length of current string
13777 ;; If equal to column width, we should realign.
13779 (defun org-remap (map &rest commands)
13780 "In MAP, remap the functions given in COMMANDS.
13781 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13782 (let (new old)
13783 (while commands
13784 (setq old (pop commands) new (pop commands))
13785 (if (fboundp 'command-remapping)
13786 (org-defkey map (vector 'remap old) new)
13787 (substitute-key-definition old new map global-map)))))
13789 (when (eq org-enable-table-editor 'optimized)
13790 ;; If the user wants maximum table support, we need to hijack
13791 ;; some standard editing functions
13792 (org-remap org-mode-map
13793 'self-insert-command 'org-self-insert-command
13794 'delete-char 'org-delete-char
13795 'delete-backward-char 'org-delete-backward-char)
13796 (org-defkey org-mode-map "|" 'org-force-self-insert))
13798 (defvar org-ctrl-c-ctrl-c-hook nil
13799 "Hook for functions attaching themselves to `C-c C-c'.
13800 This can be used to add additional functionality to the C-c C-c key which
13801 executes context-dependent commands.
13802 Each function will be called with no arguments. The function must check
13803 if the context is appropriate for it to act. If yes, it should do its
13804 thing and then return a non-nil value. If the context is wrong,
13805 just do nothing.")
13807 (defvar org-metaleft-hook nil
13808 "Hook for functions attaching themselves to `M-left'.
13809 See `org-ctrl-c-ctrl-c-hook' for more information.")
13810 (defvar org-metaright-hook nil
13811 "Hook for functions attaching themselves to `M-right'.
13812 See `org-ctrl-c-ctrl-c-hook' for more information.")
13813 (defvar org-metaup-hook nil
13814 "Hook for functions attaching themselves to `M-up'.
13815 See `org-ctrl-c-ctrl-c-hook' for more information.")
13816 (defvar org-metadown-hook nil
13817 "Hook for functions attaching themselves to `M-down'.
13818 See `org-ctrl-c-ctrl-c-hook' for more information.")
13819 (defvar org-shiftmetaleft-hook nil
13820 "Hook for functions attaching themselves to `M-S-left'.
13821 See `org-ctrl-c-ctrl-c-hook' for more information.")
13822 (defvar org-shiftmetaright-hook nil
13823 "Hook for functions attaching themselves to `M-S-right'.
13824 See `org-ctrl-c-ctrl-c-hook' for more information.")
13825 (defvar org-shiftmetaup-hook nil
13826 "Hook for functions attaching themselves to `M-S-up'.
13827 See `org-ctrl-c-ctrl-c-hook' for more information.")
13828 (defvar org-shiftmetadown-hook nil
13829 "Hook for functions attaching themselves to `M-S-down'.
13830 See `org-ctrl-c-ctrl-c-hook' for more information.")
13831 (defvar org-metareturn-hook nil
13832 "Hook for functions attaching themselves to `M-RET'.
13833 See `org-ctrl-c-ctrl-c-hook' for more information.")
13835 (defun org-modifier-cursor-error ()
13836 "Throw an error, a modified cursor command was applied in wrong context."
13837 (error "This command is active in special context like tables, headlines or items"))
13839 (defun org-shiftselect-error ()
13840 "Throw an error because Shift-Cursor command was applied in wrong context."
13841 (if (and (boundp 'shift-select-mode) shift-select-mode)
13842 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13843 (error "This command works only in special context like headlines or timestamps.")))
13845 (defun org-call-for-shift-select (cmd)
13846 (let ((this-command-keys-shift-translated t))
13847 (call-interactively cmd)))
13849 (defun org-shifttab (&optional arg)
13850 "Global visibility cycling or move to previous table field.
13851 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13852 on context.
13853 See the individual commands for more information."
13854 (interactive "P")
13855 (cond
13856 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13857 ((integerp arg)
13858 (message "Content view to level: %d" arg)
13859 (org-content (prefix-numeric-value arg))
13860 (setq org-cycle-global-status 'overview))
13861 (t (call-interactively 'org-global-cycle))))
13863 (defun org-shiftmetaleft ()
13864 "Promote subtree or delete table column.
13865 Calls `org-promote-subtree', `org-outdent-item',
13866 or `org-table-delete-column', depending on context.
13867 See the individual commands for more information."
13868 (interactive)
13869 (cond
13870 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
13871 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13872 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13873 ((org-at-item-p) (call-interactively 'org-outdent-item))
13874 (t (org-modifier-cursor-error))))
13876 (defun org-shiftmetaright ()
13877 "Demote subtree or insert table column.
13878 Calls `org-demote-subtree', `org-indent-item',
13879 or `org-table-insert-column', depending on context.
13880 See the individual commands for more information."
13881 (interactive)
13882 (cond
13883 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
13884 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13885 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13886 ((org-at-item-p) (call-interactively 'org-indent-item))
13887 (t (org-modifier-cursor-error))))
13889 (defun org-shiftmetaup (&optional arg)
13890 "Move subtree up or kill table row.
13891 Calls `org-move-subtree-up' or `org-table-kill-row' or
13892 `org-move-item-up' depending on context. See the individual commands
13893 for more information."
13894 (interactive "P")
13895 (cond
13896 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
13897 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13898 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13899 ((org-at-item-p) (call-interactively 'org-move-item-up))
13900 (t (org-modifier-cursor-error))))
13902 (defun org-shiftmetadown (&optional arg)
13903 "Move subtree down or insert table row.
13904 Calls `org-move-subtree-down' or `org-table-insert-row' or
13905 `org-move-item-down', depending on context. See the individual
13906 commands for more information."
13907 (interactive "P")
13908 (cond
13909 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
13910 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13911 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13912 ((org-at-item-p) (call-interactively 'org-move-item-down))
13913 (t (org-modifier-cursor-error))))
13915 (defun org-metaleft (&optional arg)
13916 "Promote heading or move table column to left.
13917 Calls `org-do-promote' or `org-table-move-column', depending on context.
13918 With no specific context, calls the Emacs default `backward-word'.
13919 See the individual commands for more information."
13920 (interactive "P")
13921 (cond
13922 ((run-hook-with-args-until-success 'org-metaleft-hook))
13923 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13924 ((or (org-on-heading-p)
13925 (and (org-region-active-p)
13926 (save-excursion
13927 (goto-char (region-beginning))
13928 (org-on-heading-p))))
13929 (call-interactively 'org-do-promote))
13930 ((or (org-at-item-p)
13931 (and (org-region-active-p)
13932 (save-excursion
13933 (goto-char (region-beginning))
13934 (org-at-item-p))))
13935 (call-interactively 'org-outdent-item))
13936 (t (call-interactively 'backward-word))))
13938 (defun org-metaright (&optional arg)
13939 "Demote subtree or move table column to right.
13940 Calls `org-do-demote' or `org-table-move-column', depending on context.
13941 With no specific context, calls the Emacs default `forward-word'.
13942 See the individual commands for more information."
13943 (interactive "P")
13944 (cond
13945 ((run-hook-with-args-until-success 'org-metaright-hook))
13946 ((org-at-table-p) (call-interactively 'org-table-move-column))
13947 ((or (org-on-heading-p)
13948 (and (org-region-active-p)
13949 (save-excursion
13950 (goto-char (region-beginning))
13951 (org-on-heading-p))))
13952 (call-interactively 'org-do-demote))
13953 ((or (org-at-item-p)
13954 (and (org-region-active-p)
13955 (save-excursion
13956 (goto-char (region-beginning))
13957 (org-at-item-p))))
13958 (call-interactively 'org-indent-item))
13959 (t (call-interactively 'forward-word))))
13961 (defun org-metaup (&optional arg)
13962 "Move subtree up or move table row up.
13963 Calls `org-move-subtree-up' or `org-table-move-row' or
13964 `org-move-item-up', depending on context. See the individual commands
13965 for more information."
13966 (interactive "P")
13967 (cond
13968 ((run-hook-with-args-until-success 'org-metaup-hook))
13969 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13970 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13971 ((org-at-item-p) (call-interactively 'org-move-item-up))
13972 (t (transpose-lines 1) (beginning-of-line -1))))
13974 (defun org-metadown (&optional arg)
13975 "Move subtree down or move table row down.
13976 Calls `org-move-subtree-down' or `org-table-move-row' or
13977 `org-move-item-down', depending on context. See the individual
13978 commands for more information."
13979 (interactive "P")
13980 (cond
13981 ((run-hook-with-args-until-success 'org-metadown-hook))
13982 ((org-at-table-p) (call-interactively 'org-table-move-row))
13983 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13984 ((org-at-item-p) (call-interactively 'org-move-item-down))
13985 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13987 (defun org-shiftup (&optional arg)
13988 "Increase item in timestamp or increase priority of current headline.
13989 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13990 depending on context. See the individual commands for more information."
13991 (interactive "P")
13992 (cond
13993 ((and org-support-shift-select (org-region-active-p))
13994 (org-call-for-shift-select 'previous-line))
13995 ((org-at-timestamp-p t)
13996 (call-interactively (if org-edit-timestamp-down-means-later
13997 'org-timestamp-down 'org-timestamp-up)))
13998 ((and (not (eq org-support-shift-select 'always))
13999 (org-on-heading-p))
14000 (call-interactively 'org-priority-up))
14001 ((and (not org-support-shift-select) (org-at-item-p))
14002 (call-interactively 'org-previous-item))
14003 ((org-clocktable-try-shift 'up arg))
14004 (org-support-shift-select
14005 (org-call-for-shift-select 'previous-line))
14006 (t (org-shiftselect-error))))
14008 (defun org-shiftdown (&optional arg)
14009 "Decrease item in timestamp or decrease priority of current headline.
14010 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14011 depending on context. See the individual commands for more information."
14012 (interactive "P")
14013 (cond
14014 ((and org-support-shift-select (org-region-active-p))
14015 (org-call-for-shift-select 'next-line))
14016 ((org-at-timestamp-p t)
14017 (call-interactively (if org-edit-timestamp-down-means-later
14018 'org-timestamp-up 'org-timestamp-down)))
14019 ((and (not (eq org-support-shift-select 'always))
14020 (org-on-heading-p))
14021 (call-interactively 'org-priority-down))
14022 ((and (not org-support-shift-select) (org-at-item-p))
14023 (call-interactively 'org-next-item))
14024 ((org-clocktable-try-shift 'down arg))
14025 (org-support-shift-select
14026 (org-call-for-shift-select 'next-line))
14027 (t (org-shiftselect-error))))
14029 (defun org-shiftright (&optional arg)
14030 "Cycle the thing at point or in the current line, depending on context.
14031 Depending on context, this does one of the following:
14033 - switch a timestamp at point one day into the future
14034 - on a headline, switch to the next TODO keyword.
14035 - on an item, switch entire list to the next bullet type
14036 - on a property line, switch to the next allowed value
14037 - on a clocktable definition line, move time block into the future"
14038 (interactive "P")
14039 (cond
14040 ((and org-support-shift-select (org-region-active-p))
14041 (org-call-for-shift-select 'forward-char))
14042 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14043 ((and (not (eq org-support-shift-select 'always))
14044 (org-on-heading-p))
14045 (org-call-with-arg 'org-todo 'right))
14046 ((or (and org-support-shift-select
14047 (not (eq org-support-shift-select 'always))
14048 (org-at-item-bullet-p))
14049 (and (not org-support-shift-select) (org-at-item-p)))
14050 (org-call-with-arg 'org-cycle-list-bullet nil))
14051 ((and (not (eq org-support-shift-select 'always))
14052 (org-at-property-p))
14053 (call-interactively 'org-property-next-allowed-value))
14054 ((org-clocktable-try-shift 'right arg))
14055 (org-support-shift-select
14056 (org-call-for-shift-select 'forward-char))
14057 (t (org-shiftselect-error))))
14059 (defun org-shiftleft (&optional arg)
14060 "Cycle the thing at point or in the current line, depending on context.
14061 Depending on context, this does one of the following:
14063 - switch a timestamp at point one day into the past
14064 - on a headline, switch to the previous TODO keyword.
14065 - on an item, switch entire list to the previous bullet type
14066 - on a property line, switch to the previous allowed value
14067 - on a clocktable definition line, move time block into the past"
14068 (interactive "P")
14069 (cond
14070 ((and org-support-shift-select (org-region-active-p))
14071 (org-call-for-shift-select 'backward-char))
14072 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14073 ((and (not (eq org-support-shift-select 'always))
14074 (org-on-heading-p))
14075 (org-call-with-arg 'org-todo 'left))
14076 ((or (and org-support-shift-select
14077 (not (eq org-support-shift-select 'always))
14078 (org-at-item-bullet-p))
14079 (and (not org-support-shift-select) (org-at-item-p)))
14080 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14081 ((and (not (eq org-support-shift-select 'always))
14082 (org-at-property-p))
14083 (call-interactively 'org-property-previous-allowed-value))
14084 ((org-clocktable-try-shift 'left arg))
14085 (org-support-shift-select
14086 (org-call-for-shift-select 'backward-char))
14087 (t (org-shiftselect-error))))
14089 (defun org-shiftcontrolright ()
14090 "Switch to next TODO set."
14091 (interactive)
14092 (cond
14093 ((and org-support-shift-select (org-region-active-p))
14094 (org-call-for-shift-select 'forward-word))
14095 ((and (not (eq org-support-shift-select 'always))
14096 (org-on-heading-p))
14097 (org-call-with-arg 'org-todo 'nextset))
14098 (org-support-shift-select
14099 (org-call-for-shift-select 'forward-word))
14100 (t (org-shiftselect-error))))
14102 (defun org-shiftcontrolleft ()
14103 "Switch to previous TODO set."
14104 (interactive)
14105 (cond
14106 ((and org-support-shift-select (org-region-active-p))
14107 (org-call-for-shift-select 'backward-word))
14108 ((and (not (eq org-support-shift-select 'always))
14109 (org-on-heading-p))
14110 (org-call-with-arg 'org-todo 'previousset))
14111 (org-support-shift-select
14112 (org-call-for-shift-select 'backward-word))
14113 (t (org-shiftselect-error))))
14115 (defun org-ctrl-c-ret ()
14116 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14117 (interactive)
14118 (cond
14119 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14120 (t (call-interactively 'org-insert-heading))))
14122 (defun org-copy-special ()
14123 "Copy region in table or copy current subtree.
14124 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14125 See the individual commands for more information."
14126 (interactive)
14127 (call-interactively
14128 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14130 (defun org-cut-special ()
14131 "Cut region in table or cut current subtree.
14132 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14133 See the individual commands for more information."
14134 (interactive)
14135 (call-interactively
14136 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14138 (defun org-paste-special (arg)
14139 "Paste rectangular region into table, or past subtree relative to level.
14140 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14141 See the individual commands for more information."
14142 (interactive "P")
14143 (if (org-at-table-p)
14144 (org-table-paste-rectangle)
14145 (org-paste-subtree arg)))
14147 (defun org-edit-special ()
14148 "Call a special editor for the stuff at point.
14149 When at a table, call the formula editor with `org-table-edit-formulas'.
14150 When at the first line of an src example, call `org-edit-src-code'.
14151 When in an #+include line, visit the include file. Otherwise call
14152 `ffap' to visit the file at point."
14153 (interactive)
14154 (cond
14155 ((org-at-table-p)
14156 (call-interactively 'org-table-edit-formulas))
14157 ((save-excursion
14158 (beginning-of-line 1)
14159 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14160 (find-file (org-trim (match-string 1))))
14161 ((org-edit-src-code))
14162 ((org-edit-fixed-width-region))
14163 (t (call-interactively 'ffap))))
14166 (defun org-ctrl-c-ctrl-c (&optional arg)
14167 "Set tags in headline, or update according to changed information at point.
14169 This command does many different things, depending on context:
14171 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14172 this is what we do.
14174 - If the cursor is in a headline, prompt for tags and insert them
14175 into the current line, aligned to `org-tags-column'. When called
14176 with prefix arg, realign all tags in the current buffer.
14178 - If the cursor is in one of the special #+KEYWORD lines, this
14179 triggers scanning the buffer for these lines and updating the
14180 information.
14182 - If the cursor is inside a table, realign the table. This command
14183 works even if the automatic table editor has been turned off.
14185 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14186 the entire table.
14188 - If the cursor is at a footnote reference or definition, jump to
14189 the corresponding definition or references, respectively.
14191 - If the cursor is a the beginning of a dynamic block, update it.
14193 - If the cursor is inside a table created by the table.el package,
14194 activate that table.
14196 - If the current buffer is a remember buffer, close note and file
14197 it. A prefix argument of 1 files to the default location
14198 without further interaction. A prefix argument of 2 files to
14199 the currently clocking task.
14201 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14202 links in this buffer.
14204 - If the cursor is on a numbered item in a plain list, renumber the
14205 ordered list.
14207 - If the cursor is on a checkbox, toggle it."
14208 (interactive "P")
14209 (let ((org-enable-table-editor t))
14210 (cond
14211 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14212 org-occur-highlights
14213 org-latex-fragment-image-overlays)
14214 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14215 (org-remove-occur-highlights)
14216 (org-remove-latex-fragment-image-overlays)
14217 (message "Temporary highlights/overlays removed from current buffer"))
14218 ((and (local-variable-p 'org-finish-function (current-buffer))
14219 (fboundp org-finish-function))
14220 (funcall org-finish-function))
14221 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14222 ((org-at-property-p)
14223 (call-interactively 'org-property-action))
14224 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14225 ((org-on-heading-p) (call-interactively 'org-set-tags))
14226 ((org-at-table.el-p)
14227 (require 'table)
14228 (beginning-of-line 1)
14229 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14230 (call-interactively 'table-recognize-table))
14231 ((org-at-table-p)
14232 (org-table-maybe-eval-formula)
14233 (if arg
14234 (call-interactively 'org-table-recalculate)
14235 (org-table-maybe-recalculate-line))
14236 (call-interactively 'org-table-align))
14237 ((or (org-footnote-at-reference-p)
14238 (org-footnote-at-definition-p))
14239 (call-interactively 'org-footnote-action))
14240 ((org-at-item-checkbox-p)
14241 (call-interactively 'org-toggle-checkbox))
14242 ((org-at-item-p)
14243 (if arg
14244 (call-interactively 'org-toggle-checkbox)
14245 (call-interactively 'org-maybe-renumber-ordered-list)))
14246 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14247 ;; Dynamic block
14248 (beginning-of-line 1)
14249 (save-excursion (org-update-dblock)))
14250 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14251 (cond
14252 ((equal (match-string 1) "TBLFM")
14253 ;; Recalculate the table before this line
14254 (save-excursion
14255 (beginning-of-line 1)
14256 (skip-chars-backward " \r\n\t")
14257 (if (org-at-table-p)
14258 (org-call-with-arg 'org-table-recalculate t))))
14260 ; (org-set-regexps-and-options)
14261 ; (org-restart-font-lock)
14262 (let ((org-inhibit-startup t)) (org-mode-restart))
14263 (message "Local setup has been refreshed"))))
14264 (t (error "C-c C-c can do nothing useful at this location.")))))
14266 (defun org-mode-restart ()
14267 "Restart Org-mode, to scan again for special lines.
14268 Also updates the keyword regular expressions."
14269 (interactive)
14270 (org-mode)
14271 (message "Org-mode restarted"))
14273 (defun org-kill-note-or-show-branches ()
14274 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14275 (interactive)
14276 (if (not org-finish-function)
14277 (call-interactively 'show-branches)
14278 (let ((org-note-abort t))
14279 (funcall org-finish-function))))
14281 (defun org-return (&optional indent)
14282 "Goto next table row or insert a newline.
14283 Calls `org-table-next-row' or `newline', depending on context.
14284 See the individual commands for more information."
14285 (interactive)
14286 (cond
14287 ((bobp) (if indent (newline-and-indent) (newline)))
14288 ((org-at-table-p)
14289 (org-table-justify-field-maybe)
14290 (call-interactively 'org-table-next-row))
14291 ((and org-return-follows-link
14292 (eq (get-text-property (point) 'face) 'org-link))
14293 (call-interactively 'org-open-at-point))
14294 ((and (org-at-heading-p)
14295 (looking-at
14296 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14297 (org-show-entry)
14298 (end-of-line 1)
14299 (newline))
14300 (t (if indent (newline-and-indent) (newline)))))
14302 (defun org-return-indent ()
14303 "Goto next table row or insert a newline and indent.
14304 Calls `org-table-next-row' or `newline-and-indent', depending on
14305 context. See the individual commands for more information."
14306 (interactive)
14307 (org-return t))
14309 (defun org-ctrl-c-star ()
14310 "Compute table, or change heading status of lines.
14311 Calls `org-table-recalculate' or `org-toggle-heading',
14312 depending on context."
14313 (interactive)
14314 (cond
14315 ((org-at-table-p)
14316 (call-interactively 'org-table-recalculate))
14318 ;; Convert all lines in region to list items
14319 (call-interactively 'org-toggle-heading))))
14321 (defun org-ctrl-c-minus ()
14322 "Insert separator line in table or modify bullet status of line.
14323 Also turns a plain line or a region of lines into list items.
14324 Calls `org-table-insert-hline', `org-toggle-item', or
14325 `org-cycle-list-bullet', depending on context."
14326 (interactive)
14327 (cond
14328 ((org-at-table-p)
14329 (call-interactively 'org-table-insert-hline))
14330 ((org-region-active-p)
14331 (call-interactively 'org-toggle-item))
14332 ((org-in-item-p)
14333 (call-interactively 'org-cycle-list-bullet))
14335 (call-interactively 'org-toggle-item))))
14337 (defun org-toggle-item ()
14338 "Convert headings or normal lines to items, items to normal lines.
14339 If there is no active region, only the current line is considered.
14341 If the first line in the region is a headline, convert all headlines to items.
14343 If the first line in the region is an item, convert all items to normal lines.
14345 If the first line is normal text, add an item bullet to each line."
14346 (interactive)
14347 (let (l2 l beg end)
14348 (if (org-region-active-p)
14349 (setq beg (region-beginning) end (region-end))
14350 (setq beg (point-at-bol)
14351 end (min (1+ (point-at-eol)) (point-max))))
14352 (save-excursion
14353 (goto-char end)
14354 (setq l2 (org-current-line))
14355 (goto-char beg)
14356 (beginning-of-line 1)
14357 (setq l (1- (org-current-line)))
14358 (if (org-at-item-p)
14359 ;; We already have items, de-itemize
14360 (while (< (setq l (1+ l)) l2)
14361 (when (org-at-item-p)
14362 (goto-char (match-beginning 2))
14363 (delete-region (match-beginning 2) (match-end 2))
14364 (and (looking-at "[ \t]+") (replace-match "")))
14365 (beginning-of-line 2))
14366 (if (org-on-heading-p)
14367 ;; Headings, convert to items
14368 (while (< (setq l (1+ l)) l2)
14369 (if (looking-at org-outline-regexp)
14370 (replace-match "- " t t))
14371 (beginning-of-line 2))
14372 ;; normal lines, turn them into items
14373 (while (< (setq l (1+ l)) l2)
14374 (unless (org-at-item-p)
14375 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14376 (replace-match "\\1- \\2")))
14377 (beginning-of-line 2)))))))
14379 (defun org-toggle-heading (&optional nstars)
14380 "Convert headings to normal text, or items or text to headings.
14381 If there is no active region, only the current line is considered.
14383 If the first line is a heading, remove the stars from all headlines
14384 in the region.
14386 If the first line is a plain list item, turn all plain list items into
14387 headings.
14389 If the first line is a normal line, turn each and every line in the region
14390 into a heading.
14392 When converting a line into a heading, the number of stars is chosen
14393 such that the lines become children of the current entry. However, when
14394 a prefix argument is given, its value determines the number of stars to add."
14395 (interactive "P")
14396 (let (l2 l itemp beg end)
14397 (if (org-region-active-p)
14398 (setq beg (region-beginning) end (region-end))
14399 (setq beg (point-at-bol)
14400 end (min (1+ (point-at-eol)) (point-max))))
14401 (save-excursion
14402 (goto-char end)
14403 (setq l2 (org-current-line))
14404 (goto-char beg)
14405 (beginning-of-line 1)
14406 (setq l (1- (org-current-line)))
14407 (if (org-on-heading-p)
14408 ;; We already have headlines, de-star them
14409 (while (< (setq l (1+ l)) l2)
14410 (when (org-on-heading-p t)
14411 (and (looking-at outline-regexp) (replace-match "")))
14412 (beginning-of-line 2))
14413 (setq itemp (org-at-item-p))
14414 (let* ((stars
14415 (if nstars
14416 (make-string (prefix-numeric-value current-prefix-arg)
14418 (save-excursion
14419 (re-search-backward org-complex-heading-regexp nil t)
14420 (or (match-string 1) ""))))
14421 (add-stars (cond (nstars "")
14422 ((equal stars "") "*")
14423 (org-odd-levels-only "**")
14424 (t "*")))
14425 (rpl (concat stars add-stars " ")))
14426 (while (< (setq l (1+ l)) l2)
14427 (if itemp
14428 (and (org-at-item-p) (replace-match rpl t t))
14429 (unless (org-on-heading-p)
14430 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14431 (replace-match (concat rpl (match-string 2))))))
14432 (beginning-of-line 2)))))))
14434 (defun org-meta-return (&optional arg)
14435 "Insert a new heading or wrap a region in a table.
14436 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14437 See the individual commands for more information."
14438 (interactive "P")
14439 (cond
14440 ((run-hook-with-args-until-success 'org-metareturn-hook))
14441 ((org-at-table-p)
14442 (call-interactively 'org-table-wrap-region))
14443 (t (call-interactively 'org-insert-heading))))
14445 ;;; Menu entries
14447 ;; Define the Org-mode menus
14448 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14449 '("Tbl"
14450 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14451 ["Next Field" org-cycle (org-at-table-p)]
14452 ["Previous Field" org-shifttab (org-at-table-p)]
14453 ["Next Row" org-return (org-at-table-p)]
14454 "--"
14455 ["Blank Field" org-table-blank-field (org-at-table-p)]
14456 ["Edit Field" org-table-edit-field (org-at-table-p)]
14457 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14458 "--"
14459 ("Column"
14460 ["Move Column Left" org-metaleft (org-at-table-p)]
14461 ["Move Column Right" org-metaright (org-at-table-p)]
14462 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14463 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14464 ("Row"
14465 ["Move Row Up" org-metaup (org-at-table-p)]
14466 ["Move Row Down" org-metadown (org-at-table-p)]
14467 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14468 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14469 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14470 "--"
14471 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14472 ("Rectangle"
14473 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14474 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14475 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14476 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14477 "--"
14478 ("Calculate"
14479 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14480 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14481 ["Edit Formulas" org-edit-special (org-at-table-p)]
14482 "--"
14483 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14484 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14485 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14486 "--"
14487 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14488 "--"
14489 ["Sum Column/Rectangle" org-table-sum
14490 (or (org-at-table-p) (org-region-active-p))]
14491 ["Which Column?" org-table-current-column (org-at-table-p)])
14492 ["Debug Formulas"
14493 org-table-toggle-formula-debugger
14494 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14495 ["Show Col/Row Numbers"
14496 org-table-toggle-coordinate-overlays
14497 :style toggle
14498 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14499 "--"
14500 ["Create" org-table-create (and (not (org-at-table-p))
14501 org-enable-table-editor)]
14502 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14503 ["Import from File" org-table-import (not (org-at-table-p))]
14504 ["Export to File" org-table-export (org-at-table-p)]
14505 "--"
14506 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14508 (easy-menu-define org-org-menu org-mode-map "Org menu"
14509 '("Org"
14510 ("Show/Hide"
14511 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14512 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14513 ["Sparse Tree..." org-sparse-tree t]
14514 ["Reveal Context" org-reveal t]
14515 ["Show All" show-all t]
14516 "--"
14517 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14518 "--"
14519 ["New Heading" org-insert-heading t]
14520 ("Navigate Headings"
14521 ["Up" outline-up-heading t]
14522 ["Next" outline-next-visible-heading t]
14523 ["Previous" outline-previous-visible-heading t]
14524 ["Next Same Level" outline-forward-same-level t]
14525 ["Previous Same Level" outline-backward-same-level t]
14526 "--"
14527 ["Jump" org-goto t])
14528 ("Edit Structure"
14529 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14530 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14531 "--"
14532 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14533 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14534 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14535 "--"
14536 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14537 "--"
14538 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14539 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14540 ["Demote Heading" org-metaright (not (org-at-table-p))]
14541 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14542 "--"
14543 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14544 "--"
14545 ["Convert to odd levels" org-convert-to-odd-levels t]
14546 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14547 ("Editing"
14548 ["Emphasis..." org-emphasize t]
14549 ["Edit Source Example" org-edit-special t]
14550 "--"
14551 ["Footnote new/jump" org-footnote-action t]
14552 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14553 ("Archive"
14554 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14555 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14556 ; :active t :keys "C-u C-c C-x C-a"]
14557 ["Sparse trees open ARCHIVE trees"
14558 (setq org-sparse-tree-open-archived-trees
14559 (not org-sparse-tree-open-archived-trees))
14560 :style toggle :selected org-sparse-tree-open-archived-trees]
14561 ["Cycling opens ARCHIVE trees"
14562 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14563 :style toggle :selected org-cycle-open-archived-trees]
14564 "--"
14565 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14566 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14567 ; ["Check and Move Children" (org-archive-subtree '(4))
14568 ; :active t :keys "C-u C-c C-x C-s"]
14570 "--"
14571 ("Hyperlinks"
14572 ["Store Link (Global)" org-store-link t]
14573 ["Insert Link" org-insert-link t]
14574 ["Follow Link" org-open-at-point t]
14575 "--"
14576 ["Next link" org-next-link t]
14577 ["Previous link" org-previous-link t]
14578 "--"
14579 ["Descriptive Links"
14580 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14581 :style radio
14582 :selected (member '(org-link) buffer-invisibility-spec)]
14583 ["Literal Links"
14584 (progn
14585 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14586 :style radio
14587 :selected (not (member '(org-link) buffer-invisibility-spec))])
14588 "--"
14589 ("TODO Lists"
14590 ["TODO/DONE/-" org-todo t]
14591 ("Select keyword"
14592 ["Next keyword" org-shiftright (org-on-heading-p)]
14593 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14594 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14595 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14596 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14597 ["Show TODO Tree" org-show-todo-tree t]
14598 ["Global TODO list" org-todo-list t]
14599 "--"
14600 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14601 :selected org-enforce-todo-dependencies :style toggle :active t]
14602 "Settings for tree at point"
14603 ["Do Children sequentially" org-toggle-ordered-property :style radio
14604 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14605 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14606 ["Do Children parallel" org-toggle-ordered-property :style radio
14607 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14608 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14609 "--"
14610 ["Set Priority" org-priority t]
14611 ["Priority Up" org-shiftup t]
14612 ["Priority Down" org-shiftdown t]
14613 "--"
14614 ["Get news from all feeds" org-feed-update-all t]
14615 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
14616 ["Customize feeds" (customize-variable 'org-feed-alist) t])
14617 ("TAGS and Properties"
14618 ["Set Tags" org-set-tags-command t]
14619 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14620 "--"
14621 ["Set property" org-set-property t]
14622 ["Column view of properties" org-columns t]
14623 ["Insert Column View DBlock" org-insert-columns-dblock t])
14624 ("Dates and Scheduling"
14625 ["Timestamp" org-time-stamp t]
14626 ["Timestamp (inactive)" org-time-stamp-inactive t]
14627 ("Change Date"
14628 ["1 Day Later" org-shiftright t]
14629 ["1 Day Earlier" org-shiftleft t]
14630 ["1 ... Later" org-shiftup t]
14631 ["1 ... Earlier" org-shiftdown t])
14632 ["Compute Time Range" org-evaluate-time-range t]
14633 ["Schedule Item" org-schedule t]
14634 ["Deadline" org-deadline t]
14635 "--"
14636 ["Custom time format" org-toggle-time-stamp-overlays
14637 :style radio :selected org-display-custom-times]
14638 "--"
14639 ["Goto Calendar" org-goto-calendar t]
14640 ["Date from Calendar" org-date-from-calendar t]
14641 "--"
14642 ["Start/Restart Timer" org-timer-start t]
14643 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14644 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14645 ["Insert Timer String" org-timer t]
14646 ["Insert Timer Item" org-timer-item t])
14647 ("Logging work"
14648 ["Clock in" org-clock-in t]
14649 ["Clock out" org-clock-out t]
14650 ["Clock cancel" org-clock-cancel t]
14651 ["Goto running clock" org-clock-goto t]
14652 ["Display times" org-clock-display t]
14653 ["Create clock table" org-clock-report t]
14654 "--"
14655 ["Record DONE time"
14656 (progn (setq org-log-done (not org-log-done))
14657 (message "Switching to %s will %s record a timestamp"
14658 (car org-done-keywords)
14659 (if org-log-done "automatically" "not")))
14660 :style toggle :selected org-log-done])
14661 "--"
14662 ["Agenda Command..." org-agenda t]
14663 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14664 ("File List for Agenda")
14665 ("Special views current file"
14666 ["TODO Tree" org-show-todo-tree t]
14667 ["Check Deadlines" org-check-deadlines t]
14668 ["Timeline" org-timeline t]
14669 ["Tags/Property tree" org-match-sparse-tree t])
14670 "--"
14671 ["Export/Publish..." org-export t]
14672 ("LaTeX"
14673 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14674 :selected org-cdlatex-mode]
14675 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14676 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14677 ["Modify math symbol" org-cdlatex-math-modify
14678 (org-inside-LaTeX-fragment-p)]
14679 ["Insert citation" org-reftex-citation t]
14680 "--"
14681 ["Export LaTeX fragments as images"
14682 (if (featurep 'org-exp)
14683 (setq org-export-with-LaTeX-fragments
14684 (not org-export-with-LaTeX-fragments))
14685 (require 'org-exp))
14686 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14687 org-export-with-LaTeX-fragments)])
14688 "--"
14689 ("Documentation"
14690 ["Show Version" org-version t]
14691 ["Info Documentation" org-info t])
14692 ("Customize"
14693 ["Browse Org Group" org-customize t]
14694 "--"
14695 ["Expand This Menu" org-create-customize-menu
14696 (fboundp 'customize-menu-create)])
14697 "--"
14698 ("Refresh/Reload"
14699 ["Refresh setup current buffer" org-mode-restart t]
14700 ["Reload Org (after update)" org-reload t]
14701 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
14704 (defun org-info (&optional node)
14705 "Read documentation for Org-mode in the info system.
14706 With optional NODE, go directly to that node."
14707 (interactive)
14708 (info (format "(org)%s" (or node ""))))
14710 (defun org-install-agenda-files-menu ()
14711 (let ((bl (buffer-list)))
14712 (save-excursion
14713 (while bl
14714 (set-buffer (pop bl))
14715 (if (org-mode-p) (setq bl nil)))
14716 (when (org-mode-p)
14717 (easy-menu-change
14718 '("Org") "File List for Agenda"
14719 (append
14720 (list
14721 ["Edit File List" (org-edit-agenda-file-list) t]
14722 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14723 ["Remove Current File from List" org-remove-file t]
14724 ["Cycle through agenda files" org-cycle-agenda-files t]
14725 ["Occur in all agenda files" org-occur-in-agenda-files t]
14726 "--")
14727 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14729 ;;;; Documentation
14731 ;;;###autoload
14732 (defun org-require-autoloaded-modules ()
14733 (interactive)
14734 (mapc 'require
14735 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
14736 org-docbook org-exp org-export-latex org-icalendar
14737 org-id org-publish org-remember org-table
14738 org-timer org-xoxo)))
14740 ;;;###autoload
14741 (defun org-reload (&optional uncompiled)
14742 "Reload all org lisp files.
14743 With prefix arg UNCOMPILED, load the uncompiled versions."
14744 (interactive "P")
14745 (require 'find-func)
14746 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
14747 (dir-org (file-name-directory (org-find-library-name "org")))
14748 (dir-org-contrib (ignore-errors
14749 (file-name-directory
14750 (org-find-library-name "org-contribdir"))))
14751 (files
14752 (append (directory-files dir-org t file-re)
14753 (and dir-org-contrib
14754 (directory-files dir-org-contrib t file-re))))
14755 (remove-re (concat (if (featurep 'xemacs)
14756 "org-colview" "org-colview-xemacs")
14757 "\\'")))
14758 (setq files (mapcar 'file-name-sans-extension files))
14759 (setq files (mapcar
14760 (lambda (x) (if (string-match remove-re x) nil x))
14761 files))
14762 (setq files (delq nil files))
14763 (mapc
14764 (lambda (f)
14765 (when (featurep (intern (file-name-nondirectory f)))
14766 (if (and (not uncompiled)
14767 (file-exists-p (concat f ".elc")))
14768 (load (concat f ".elc") nil nil t)
14769 (load (concat f ".el") nil nil t))))
14770 files)))
14772 ;;;###autoload
14773 (defun org-customize ()
14774 "Call the customize function with org as argument."
14775 (interactive)
14776 (org-load-modules-maybe)
14777 (org-require-autoloaded-modules)
14778 (customize-browse 'org))
14780 (defun org-create-customize-menu ()
14781 "Create a full customization menu for Org-mode, insert it into the menu."
14782 (interactive)
14783 (org-load-modules-maybe)
14784 (org-require-autoloaded-modules)
14785 (if (fboundp 'customize-menu-create)
14786 (progn
14787 (easy-menu-change
14788 '("Org") "Customize"
14789 `(["Browse Org group" org-customize t]
14790 "--"
14791 ,(customize-menu-create 'org)
14792 ["Set" Custom-set t]
14793 ["Save" Custom-save t]
14794 ["Reset to Current" Custom-reset-current t]
14795 ["Reset to Saved" Custom-reset-saved t]
14796 ["Reset to Standard Settings" Custom-reset-standard t]))
14797 (message "\"Org\"-menu now contains full customization menu"))
14798 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14800 ;;;; Miscellaneous stuff
14802 ;;; Generally useful functions
14804 (defun org-find-text-property-in-string (prop s)
14805 "Return the first non-nil value of property PROP in string S."
14806 (or (get-text-property 0 prop s)
14807 (get-text-property (or (next-single-property-change 0 prop s) 0)
14808 prop s)))
14810 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14811 "Display the given MESSAGE as a warning."
14812 (if (fboundp 'display-warning)
14813 (display-warning 'org message
14814 (if (featurep 'xemacs)
14815 'warning
14816 :warning))
14817 (let ((buf (get-buffer-create "*Org warnings*")))
14818 (with-current-buffer buf
14819 (goto-char (point-max))
14820 (insert "Warning (Org): " message)
14821 (unless (bolp)
14822 (newline)))
14823 (display-buffer buf)
14824 (sit-for 0))))
14826 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14827 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14828 (if (and marker (marker-buffer marker)
14829 (buffer-live-p (marker-buffer marker)))
14830 (progn
14831 (switch-to-buffer (marker-buffer marker))
14832 (if (or (> marker (point-max)) (< marker (point-min)))
14833 (widen))
14834 (goto-char marker)
14835 (org-show-context 'org-goto))
14836 (if bookmark
14837 (bookmark-jump bookmark)
14838 (error "Cannot find location"))))
14840 (defun org-quote-csv-field (s)
14841 "Quote field for inclusion in CSV material."
14842 (if (string-match "[\",]" s)
14843 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14846 (defun org-plist-delete (plist property)
14847 "Delete PROPERTY from PLIST.
14848 This is in contrast to merely setting it to 0."
14849 (let (p)
14850 (while plist
14851 (if (not (eq property (car plist)))
14852 (setq p (plist-put p (car plist) (nth 1 plist))))
14853 (setq plist (cddr plist)))
14856 (defun org-force-self-insert (N)
14857 "Needed to enforce self-insert under remapping."
14858 (interactive "p")
14859 (self-insert-command N))
14861 (defun org-string-width (s)
14862 "Compute width of string, ignoring invisible characters.
14863 This ignores character with invisibility property `org-link', and also
14864 characters with property `org-cwidth', because these will become invisible
14865 upon the next fontification round."
14866 (let (b l)
14867 (when (or (eq t buffer-invisibility-spec)
14868 (assq 'org-link buffer-invisibility-spec))
14869 (while (setq b (text-property-any 0 (length s)
14870 'invisible 'org-link s))
14871 (setq s (concat (substring s 0 b)
14872 (substring s (or (next-single-property-change
14873 b 'invisible s) (length s)))))))
14874 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14875 (setq s (concat (substring s 0 b)
14876 (substring s (or (next-single-property-change
14877 b 'org-cwidth s) (length s))))))
14878 (setq l (string-width s) b -1)
14879 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14880 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14883 (defun org-get-indentation (&optional line)
14884 "Get the indentation of the current line, interpreting tabs.
14885 When LINE is given, assume it represents a line and compute its indentation."
14886 (if line
14887 (if (string-match "^ *" (org-remove-tabs line))
14888 (match-end 0))
14889 (save-excursion
14890 (beginning-of-line 1)
14891 (skip-chars-forward " \t")
14892 (current-column))))
14894 (defun org-remove-tabs (s &optional width)
14895 "Replace tabulators in S with spaces.
14896 Assumes that s is a single line, starting in column 0."
14897 (setq width (or width tab-width))
14898 (while (string-match "\t" s)
14899 (setq s (replace-match
14900 (make-string
14901 (- (* width (/ (+ (match-beginning 0) width) width))
14902 (match-beginning 0)) ?\ )
14903 t t s)))
14906 (defun org-fix-indentation (line ind)
14907 "Fix indentation in LINE.
14908 IND is a cons cell with target and minimum indentation.
14909 If the current indentation in LINE is smaller than the minimum,
14910 leave it alone. If it is larger than ind, set it to the target."
14911 (let* ((l (org-remove-tabs line))
14912 (i (org-get-indentation l))
14913 (i1 (car ind)) (i2 (cdr ind)))
14914 (if (>= i i2) (setq l (substring line i2)))
14915 (if (> i1 0)
14916 (concat (make-string i1 ?\ ) l)
14917 l)))
14919 (defun org-base-buffer (buffer)
14920 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14921 (if (not buffer)
14922 buffer
14923 (or (buffer-base-buffer buffer)
14924 buffer)))
14926 (defun org-trim (s)
14927 "Remove whitespace at beginning and end of string."
14928 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14929 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14932 (defun org-wrap (string &optional width lines)
14933 "Wrap string to either a number of lines, or a width in characters.
14934 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14935 that costs. If there is a word longer than WIDTH, the text is actually
14936 wrapped to the length of that word.
14937 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14938 many lines, whatever width that takes.
14939 The return value is a list of lines, without newlines at the end."
14940 (let* ((words (org-split-string string "[ \t\n]+"))
14941 (maxword (apply 'max (mapcar 'org-string-width words)))
14942 w ll)
14943 (cond (width
14944 (org-do-wrap words (max maxword width)))
14945 (lines
14946 (setq w maxword)
14947 (setq ll (org-do-wrap words maxword))
14948 (if (<= (length ll) lines)
14950 (setq ll words)
14951 (while (> (length ll) lines)
14952 (setq w (1+ w))
14953 (setq ll (org-do-wrap words w)))
14954 ll))
14955 (t (error "Cannot wrap this")))))
14957 (defun org-do-wrap (words width)
14958 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14959 (let (lines line)
14960 (while words
14961 (setq line (pop words))
14962 (while (and words (< (+ (length line) (length (car words))) width))
14963 (setq line (concat line " " (pop words))))
14964 (setq lines (push line lines)))
14965 (nreverse lines)))
14967 (defun org-split-string (string &optional separators)
14968 "Splits STRING into substrings at SEPARATORS.
14969 No empty strings are returned if there are matches at the beginning
14970 and end of string."
14971 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14972 (start 0)
14973 notfirst
14974 (list nil))
14975 (while (and (string-match rexp string
14976 (if (and notfirst
14977 (= start (match-beginning 0))
14978 (< start (length string)))
14979 (1+ start) start))
14980 (< (match-beginning 0) (length string)))
14981 (setq notfirst t)
14982 (or (eq (match-beginning 0) 0)
14983 (and (eq (match-beginning 0) (match-end 0))
14984 (eq (match-beginning 0) start))
14985 (setq list
14986 (cons (substring string start (match-beginning 0))
14987 list)))
14988 (setq start (match-end 0)))
14989 (or (eq start (length string))
14990 (setq list
14991 (cons (substring string start)
14992 list)))
14993 (nreverse list)))
14995 (defun org-uuidgen-p (s)
14996 "Is S an ID created by UUIDGEN?"
14997 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
14999 (defun org-context ()
15000 "Return a list of contexts of the current cursor position.
15001 If several contexts apply, all are returned.
15002 Each context entry is a list with a symbol naming the context, and
15003 two positions indicating start and end of the context. Possible
15004 contexts are:
15006 :headline anywhere in a headline
15007 :headline-stars on the leading stars in a headline
15008 :todo-keyword on a TODO keyword (including DONE) in a headline
15009 :tags on the TAGS in a headline
15010 :priority on the priority cookie in a headline
15011 :item on the first line of a plain list item
15012 :item-bullet on the bullet/number of a plain list item
15013 :checkbox on the checkbox in a plain list item
15014 :table in an org-mode table
15015 :table-special on a special filed in a table
15016 :table-table in a table.el table
15017 :link on a hyperlink
15018 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15019 :target on a <<target>>
15020 :radio-target on a <<<radio-target>>>
15021 :latex-fragment on a LaTeX fragment
15022 :latex-preview on a LaTeX fragment with overlayed preview image
15024 This function expects the position to be visible because it uses font-lock
15025 faces as a help to recognize the following contexts: :table-special, :link,
15026 and :keyword."
15027 (let* ((f (get-text-property (point) 'face))
15028 (faces (if (listp f) f (list f)))
15029 (p (point)) clist o)
15030 ;; First the large context
15031 (cond
15032 ((org-on-heading-p t)
15033 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15034 (when (progn
15035 (beginning-of-line 1)
15036 (looking-at org-todo-line-tags-regexp))
15037 (push (org-point-in-group p 1 :headline-stars) clist)
15038 (push (org-point-in-group p 2 :todo-keyword) clist)
15039 (push (org-point-in-group p 4 :tags) clist))
15040 (goto-char p)
15041 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15042 (if (looking-at "\\[#[A-Z0-9]\\]")
15043 (push (org-point-in-group p 0 :priority) clist)))
15045 ((org-at-item-p)
15046 (push (org-point-in-group p 2 :item-bullet) clist)
15047 (push (list :item (point-at-bol)
15048 (save-excursion (org-end-of-item) (point)))
15049 clist)
15050 (and (org-at-item-checkbox-p)
15051 (push (org-point-in-group p 0 :checkbox) clist)))
15053 ((org-at-table-p)
15054 (push (list :table (org-table-begin) (org-table-end)) clist)
15055 (if (memq 'org-formula faces)
15056 (push (list :table-special
15057 (previous-single-property-change p 'face)
15058 (next-single-property-change p 'face)) clist)))
15059 ((org-at-table-p 'any)
15060 (push (list :table-table) clist)))
15061 (goto-char p)
15063 ;; Now the small context
15064 (cond
15065 ((org-at-timestamp-p)
15066 (push (org-point-in-group p 0 :timestamp) clist))
15067 ((memq 'org-link faces)
15068 (push (list :link
15069 (previous-single-property-change p 'face)
15070 (next-single-property-change p 'face)) clist))
15071 ((memq 'org-special-keyword faces)
15072 (push (list :keyword
15073 (previous-single-property-change p 'face)
15074 (next-single-property-change p 'face)) clist))
15075 ((org-on-target-p)
15076 (push (org-point-in-group p 0 :target) clist)
15077 (goto-char (1- (match-beginning 0)))
15078 (if (looking-at org-radio-target-regexp)
15079 (push (org-point-in-group p 0 :radio-target) clist))
15080 (goto-char p))
15081 ((setq o (car (delq nil
15082 (mapcar
15083 (lambda (x)
15084 (if (memq x org-latex-fragment-image-overlays) x))
15085 (org-overlays-at (point))))))
15086 (push (list :latex-fragment
15087 (org-overlay-start o) (org-overlay-end o)) clist)
15088 (push (list :latex-preview
15089 (org-overlay-start o) (org-overlay-end o)) clist))
15090 ((org-inside-LaTeX-fragment-p)
15091 ;; FIXME: positions wrong.
15092 (push (list :latex-fragment (point) (point)) clist)))
15094 (setq clist (nreverse (delq nil clist)))
15095 clist))
15097 ;; FIXME: Compare with at-regexp-p Do we need both?
15098 (defun org-in-regexp (re &optional nlines visually)
15099 "Check if point is inside a match of regexp.
15100 Normally only the current line is checked, but you can include NLINES extra
15101 lines both before and after point into the search.
15102 If VISUALLY is set, require that the cursor is not after the match but
15103 really on, so that the block visually is on the match."
15104 (catch 'exit
15105 (let ((pos (point))
15106 (eol (point-at-eol (+ 1 (or nlines 0))))
15107 (inc (if visually 1 0)))
15108 (save-excursion
15109 (beginning-of-line (- 1 (or nlines 0)))
15110 (while (re-search-forward re eol t)
15111 (if (and (<= (match-beginning 0) pos)
15112 (>= (+ inc (match-end 0)) pos))
15113 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15115 (defun org-at-regexp-p (regexp)
15116 "Is point inside a match of REGEXP in the current line?"
15117 (catch 'exit
15118 (save-excursion
15119 (let ((pos (point)) (end (point-at-eol)))
15120 (beginning-of-line 1)
15121 (while (re-search-forward regexp end t)
15122 (if (and (<= (match-beginning 0) pos)
15123 (>= (match-end 0) pos))
15124 (throw 'exit t)))
15125 nil))))
15127 (defun org-occur-in-agenda-files (regexp &optional nlines)
15128 "Call `multi-occur' with buffers for all agenda files."
15129 (interactive "sOrg-files matching: \np")
15130 (let* ((files (org-agenda-files))
15131 (tnames (mapcar 'file-truename files))
15132 (extra org-agenda-text-search-extra-files)
15134 (when (eq (car extra) 'agenda-archives)
15135 (setq extra (cdr extra))
15136 (setq files (org-add-archive-files files)))
15137 (while (setq f (pop extra))
15138 (unless (member (file-truename f) tnames)
15139 (add-to-list 'files f 'append)
15140 (add-to-list 'tnames (file-truename f) 'append)))
15141 (multi-occur
15142 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15143 regexp)))
15145 (if (boundp 'occur-mode-find-occurrence-hook)
15146 ;; Emacs 23
15147 (add-hook 'occur-mode-find-occurrence-hook
15148 (lambda ()
15149 (when (org-mode-p)
15150 (org-reveal))))
15151 ;; Emacs 22
15152 (defadvice occur-mode-goto-occurrence
15153 (after org-occur-reveal activate)
15154 (and (org-mode-p) (org-reveal)))
15155 (defadvice occur-mode-goto-occurrence-other-window
15156 (after org-occur-reveal activate)
15157 (and (org-mode-p) (org-reveal)))
15158 (defadvice occur-mode-display-occurrence
15159 (after org-occur-reveal activate)
15160 (when (org-mode-p)
15161 (let ((pos (occur-mode-find-occurrence)))
15162 (with-current-buffer (marker-buffer pos)
15163 (save-excursion
15164 (goto-char pos)
15165 (org-reveal)))))))
15167 (defun org-uniquify (list)
15168 "Remove duplicate elements from LIST."
15169 (let (res)
15170 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15171 res))
15173 (defun org-delete-all (elts list)
15174 "Remove all elements in ELTS from LIST."
15175 (while elts
15176 (setq list (delete (pop elts) list)))
15177 list)
15179 (defun org-back-over-empty-lines ()
15180 "Move backwards over whitespace, to the beginning of the first empty line.
15181 Returns the number of empty lines passed."
15182 (let ((pos (point)))
15183 (skip-chars-backward " \t\n\r")
15184 (beginning-of-line 2)
15185 (goto-char (min (point) pos))
15186 (count-lines (point) pos)))
15188 (defun org-skip-whitespace ()
15189 (skip-chars-forward " \t\n\r"))
15191 (defun org-point-in-group (point group &optional context)
15192 "Check if POINT is in match-group GROUP.
15193 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15194 match. If the match group does ot exist or point is not inside it,
15195 return nil."
15196 (and (match-beginning group)
15197 (>= point (match-beginning group))
15198 (<= point (match-end group))
15199 (if context
15200 (list context (match-beginning group) (match-end group))
15201 t)))
15203 (defun org-switch-to-buffer-other-window (&rest args)
15204 "Switch to buffer in a second window on the current frame.
15205 In particular, do not allow pop-up frames."
15206 (let (pop-up-frames special-display-buffer-names special-display-regexps
15207 special-display-function)
15208 (apply 'switch-to-buffer-other-window args)))
15210 (defun org-combine-plists (&rest plists)
15211 "Create a single property list from all plists in PLISTS.
15212 The process starts by copying the first list, and then setting properties
15213 from the other lists. Settings in the last list are the most significant
15214 ones and overrule settings in the other lists."
15215 (let ((rtn (copy-sequence (pop plists)))
15216 p v ls)
15217 (while plists
15218 (setq ls (pop plists))
15219 (while ls
15220 (setq p (pop ls) v (pop ls))
15221 (setq rtn (plist-put rtn p v))))
15222 rtn))
15224 (defun org-move-line-down (arg)
15225 "Move the current line down. With prefix argument, move it past ARG lines."
15226 (interactive "p")
15227 (let ((col (current-column))
15228 beg end pos)
15229 (beginning-of-line 1) (setq beg (point))
15230 (beginning-of-line 2) (setq end (point))
15231 (beginning-of-line (+ 1 arg))
15232 (setq pos (move-marker (make-marker) (point)))
15233 (insert (delete-and-extract-region beg end))
15234 (goto-char pos)
15235 (org-move-to-column col)))
15237 (defun org-move-line-up (arg)
15238 "Move the current line up. With prefix argument, move it past ARG lines."
15239 (interactive "p")
15240 (let ((col (current-column))
15241 beg end pos)
15242 (beginning-of-line 1) (setq beg (point))
15243 (beginning-of-line 2) (setq end (point))
15244 (beginning-of-line (- arg))
15245 (setq pos (move-marker (make-marker) (point)))
15246 (insert (delete-and-extract-region beg end))
15247 (goto-char pos)
15248 (org-move-to-column col)))
15250 (defun org-replace-escapes (string table)
15251 "Replace %-escapes in STRING with values in TABLE.
15252 TABLE is an association list with keys like \"%a\" and string values.
15253 The sequences in STRING may contain normal field width and padding information,
15254 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15255 so values can contain further %-escapes if they are define later in TABLE."
15256 (let ((case-fold-search nil)
15257 e re rpl)
15258 (while (setq e (pop table))
15259 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15260 (while (string-match re string)
15261 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15262 (cdr e)))
15263 (setq string (replace-match rpl t t string))))
15264 string))
15267 (defun org-sublist (list start end)
15268 "Return a section of LIST, from START to END.
15269 Counting starts at 1."
15270 (let (rtn (c start))
15271 (setq list (nthcdr (1- start) list))
15272 (while (and list (<= c end))
15273 (push (pop list) rtn)
15274 (setq c (1+ c)))
15275 (nreverse rtn)))
15277 (defun org-find-base-buffer-visiting (file)
15278 "Like `find-buffer-visiting' but alway return the base buffer and
15279 not an indirect buffer."
15280 (let ((buf (find-buffer-visiting file)))
15281 (if buf
15282 (or (buffer-base-buffer buf) buf)
15283 nil)))
15285 (defun org-image-file-name-regexp (&optional extensions)
15286 "Return regexp matching the file names of images.
15287 If EXTENSIONS is given, only match these."
15288 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15289 (image-file-name-regexp)
15290 (let ((image-file-name-extensions
15291 (or extensions
15292 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15293 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15294 (concat "\\."
15295 (regexp-opt (nconc (mapcar 'upcase
15296 image-file-name-extensions)
15297 image-file-name-extensions)
15299 "\\'"))))
15301 (defun org-file-image-p (file &optional extensions)
15302 "Return non-nil if FILE is an image."
15303 (save-match-data
15304 (string-match (org-image-file-name-regexp extensions) file)))
15306 (defun org-get-cursor-date ()
15307 "Return the date at cursor in as a time.
15308 This works in the calendar and in the agenda, anywhere else it just
15309 returns the current time."
15310 (let (date day defd)
15311 (cond
15312 ((eq major-mode 'calendar-mode)
15313 (setq date (calendar-cursor-to-date)
15314 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15315 ((eq major-mode 'org-agenda-mode)
15316 (setq day (get-text-property (point) 'day))
15317 (if day
15318 (setq date (calendar-gregorian-from-absolute day)
15319 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15320 (nth 2 date))))))
15321 (or defd (current-time))))
15323 (defvar org-agenda-action-marker (make-marker)
15324 "Marker pointing to the entry for the next agenda action.")
15326 (defun org-mark-entry-for-agenda-action ()
15327 "Mark the current entry as target of an agenda action.
15328 Agenda actions are actions executed from the agenda with the key `k',
15329 which make use of the date at the cursor."
15330 (interactive)
15331 (move-marker org-agenda-action-marker
15332 (save-excursion (org-back-to-heading t) (point))
15333 (current-buffer))
15334 (message
15335 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15337 ;;; Paragraph filling stuff.
15338 ;; We want this to be just right, so use the full arsenal.
15340 (defun org-indent-line-function ()
15341 "Indent line like previous, but further if previous was headline or item."
15342 (interactive)
15343 (let* ((pos (point))
15344 (itemp (org-at-item-p))
15345 (org-drawer-regexp (or org-drawer-regexp "\000"))
15346 column bpos bcol tpos tcol bullet btype bullet-type)
15347 ;; Find the previous relevant line
15348 (beginning-of-line 1)
15349 (cond
15350 ((looking-at "#") (setq column 0))
15351 ((looking-at "\\*+ ") (setq column 0))
15352 ((and (looking-at "[ \t]*:END:")
15353 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15354 (save-excursion
15355 (goto-char (1- (match-beginning 1)))
15356 (setq column (current-column))))
15358 (beginning-of-line 0)
15359 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15360 (not (looking-at "[ \t]*:END:"))
15361 (not (looking-at org-drawer-regexp)))
15362 (beginning-of-line 0))
15363 (cond
15364 ((looking-at "\\*+[ \t]+")
15365 (if (not org-adapt-indentation)
15366 (setq column 0)
15367 (goto-char (match-end 0))
15368 (setq column (current-column))))
15369 ((looking-at org-drawer-regexp)
15370 (goto-char (1- (match-beginning 1)))
15371 (setq column (current-column)))
15372 ((looking-at "\\([ \t]*\\):END:")
15373 (goto-char (match-end 1))
15374 (setq column (current-column)))
15375 ((org-in-item-p)
15376 (org-beginning-of-item)
15377 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15378 (setq bpos (match-beginning 1) tpos (match-end 0)
15379 bcol (progn (goto-char bpos) (current-column))
15380 tcol (progn (goto-char tpos) (current-column))
15381 bullet (match-string 1)
15382 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15383 (if (> tcol (+ bcol org-description-max-indent))
15384 (setq tcol (+ bcol 5)))
15385 (if (not itemp)
15386 (setq column tcol)
15387 (goto-char pos)
15388 (beginning-of-line 1)
15389 (if (looking-at "\\S-")
15390 (progn
15391 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15392 (setq bullet (match-string 1)
15393 btype (if (string-match "[0-9]" bullet) "n" bullet))
15394 (setq column (if (equal btype bullet-type) bcol tcol)))
15395 (setq column (org-get-indentation)))))
15396 (t (setq column (org-get-indentation))))))
15397 (goto-char pos)
15398 (if (<= (current-column) (current-indentation))
15399 (org-indent-line-to column)
15400 (save-excursion (org-indent-line-to column)))
15401 (setq column (current-column))
15402 (beginning-of-line 1)
15403 (if (looking-at
15404 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15405 (replace-match (concat "\\1" (format org-property-format
15406 (match-string 2) (match-string 3)))
15407 t nil))
15408 (org-move-to-column column)))
15410 (defun org-set-autofill-regexps ()
15411 (interactive)
15412 ;; In the paragraph separator we include headlines, because filling
15413 ;; text in a line directly attached to a headline would otherwise
15414 ;; fill the headline as well.
15415 (org-set-local 'comment-start-skip "^#+[ \t]*")
15416 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15417 ;; The paragraph starter includes hand-formatted lists.
15418 (org-set-local 'paragraph-start
15419 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15420 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15421 ;; But only if the user has not turned off tables or fixed-width regions
15422 (org-set-local
15423 'auto-fill-inhibit-regexp
15424 (concat "\\*+ \\|#\\+"
15425 "\\|[ \t]*" org-keyword-time-regexp
15426 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15427 (concat
15428 "\\|[ \t]*["
15429 (if org-enable-table-editor "|" "")
15430 (if org-enable-fixed-width-editor ":" "")
15431 "]"))))
15432 ;; We use our own fill-paragraph function, to make sure that tables
15433 ;; and fixed-width regions are not wrapped. That function will pass
15434 ;; through to `fill-paragraph' when appropriate.
15435 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15436 ; Adaptive filling: To get full control, first make sure that
15437 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15438 (org-set-local 'adaptive-fill-regexp "\000")
15439 (org-set-local 'adaptive-fill-function
15440 'org-adaptive-fill-function)
15441 (org-set-local
15442 'align-mode-rules-list
15443 '((org-in-buffer-settings
15444 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15445 (modes . '(org-mode))))))
15447 (defun org-fill-paragraph (&optional justify)
15448 "Re-align a table, pass through to fill-paragraph if no table."
15449 (let ((table-p (org-at-table-p))
15450 (table.el-p (org-at-table.el-p)))
15451 (cond ((and (equal (char-after (point-at-bol)) ?*)
15452 (save-excursion (goto-char (point-at-bol))
15453 (looking-at outline-regexp)))
15454 t) ; skip headlines
15455 (table.el-p t) ; skip table.el tables
15456 (table-p (org-table-align) t) ; align org-mode tables
15457 (t nil)))) ; call paragraph-fill
15459 ;; For reference, this is the default value of adaptive-fill-regexp
15460 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15462 (defun org-adaptive-fill-function ()
15463 "Return a fill prefix for org-mode files.
15464 In particular, this makes sure hanging paragraphs for hand-formatted lists
15465 work correctly."
15466 (cond ((looking-at "#[ \t]+")
15467 (match-string 0))
15468 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15469 (save-excursion
15470 (if (> (match-end 1) (+ (match-beginning 1)
15471 org-description-max-indent))
15472 (goto-char (+ (match-beginning 1) 5))
15473 (goto-char (match-end 0)))
15474 (make-string (current-column) ?\ )))
15475 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15476 (save-excursion
15477 (goto-char (match-end 0))
15478 (make-string (current-column) ?\ )))
15479 (t nil)))
15481 ;;; Other stuff.
15483 (defun org-toggle-fixed-width-section (arg)
15484 "Toggle the fixed-width export.
15485 If there is no active region, the QUOTE keyword at the current headline is
15486 inserted or removed. When present, it causes the text between this headline
15487 and the next to be exported as fixed-width text, and unmodified.
15488 If there is an active region, this command adds or removes a colon as the
15489 first character of this line. If the first character of a line is a colon,
15490 this line is also exported in fixed-width font."
15491 (interactive "P")
15492 (let* ((cc 0)
15493 (regionp (org-region-active-p))
15494 (beg (if regionp (region-beginning) (point)))
15495 (end (if regionp (region-end)))
15496 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15497 (case-fold-search nil)
15498 (re "[ \t]*\\(: \\)")
15499 off)
15500 (if regionp
15501 (save-excursion
15502 (goto-char beg)
15503 (setq cc (current-column))
15504 (beginning-of-line 1)
15505 (setq off (looking-at re))
15506 (while (> nlines 0)
15507 (setq nlines (1- nlines))
15508 (beginning-of-line 1)
15509 (cond
15510 (arg
15511 (org-move-to-column cc t)
15512 (insert ": \n")
15513 (forward-line -1))
15514 ((and off (looking-at re))
15515 (replace-match "" t t nil 1))
15516 ((not off) (org-move-to-column cc t) (insert ": ")))
15517 (forward-line 1)))
15518 (save-excursion
15519 (org-back-to-heading)
15520 (if (looking-at (concat outline-regexp
15521 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15522 (replace-match "" t t nil 1)
15523 (if (looking-at outline-regexp)
15524 (progn
15525 (goto-char (match-end 0))
15526 (insert org-quote-string " "))))))))
15528 (defun org-reftex-citation ()
15529 "Use reftex-citation to insert a citation into the buffer.
15530 This looks for a line like
15532 #+BIBLIOGRAPHY: foo plain option:-d
15534 and derives from it that foo.bib is the bbliography file relevant
15535 for this document. It then installs the necessary environment for RefTeX
15536 to work in this buffer and calls `reftex-citation' to insert a citation
15537 into the buffer.
15539 Export of such citations to both LaTeX and HTML is handled by the contributed
15540 package org-exp-bibtex by Taru Karttunen."
15541 (interactive)
15542 (let ((reftex-docstruct-symbol 'rds)
15543 (reftex-cite-format "\\cite{%l}")
15544 rds bib)
15545 (save-excursion
15546 (save-restriction
15547 (widen)
15548 (let ((case-fold-search t)
15549 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
15550 (if (not (save-excursion
15551 (or (re-search-forward re nil t)
15552 (re-search-backward re nil t))))
15553 (error "No bibliography defined in file")
15554 (setq bib (concat (match-string 1) ".bib")
15555 rds (list (list 'bib bib)))))))
15556 (call-interactively 'reftex-citation)))
15558 ;;;; Functions extending outline functionality
15560 (defun org-beginning-of-line (&optional arg)
15561 "Go to the beginning of the current line. If that is invisible, continue
15562 to a visible line beginning. This makes the function of C-a more intuitive.
15563 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15564 first attempt, and only move to after the tags when the cursor is already
15565 beyond the end of the headline."
15566 (interactive "P")
15567 (let ((pos (point))
15568 (special (if (consp org-special-ctrl-a/e)
15569 (car org-special-ctrl-a/e)
15570 org-special-ctrl-a/e))
15571 refpos)
15572 (beginning-of-line 1)
15573 (if (and arg (fboundp 'move-beginning-of-line))
15574 (call-interactively 'move-beginning-of-line)
15575 (if (bobp)
15577 (backward-char 1)
15578 (if (org-invisible-p)
15579 (while (and (not (bobp)) (org-invisible-p))
15580 (backward-char 1)
15581 (beginning-of-line 1))
15582 (forward-char 1))))
15583 (when special
15584 (cond
15585 ((and (looking-at org-complex-heading-regexp)
15586 (= (char-after (match-end 1)) ?\ ))
15587 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15588 (point-at-eol)))
15589 (goto-char
15590 (if (eq special t)
15591 (cond ((> pos refpos) refpos)
15592 ((= pos (point)) refpos)
15593 (t (point)))
15594 (cond ((> pos (point)) (point))
15595 ((not (eq last-command this-command)) (point))
15596 (t refpos)))))
15597 ((org-at-item-p)
15598 (goto-char
15599 (if (eq special t)
15600 (cond ((> pos (match-end 4)) (match-end 4))
15601 ((= pos (point)) (match-end 4))
15602 (t (point)))
15603 (cond ((> pos (point)) (point))
15604 ((not (eq last-command this-command)) (point))
15605 (t (match-end 4))))))))
15606 (org-no-warnings
15607 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15609 (defun org-end-of-line (&optional arg)
15610 "Go to the end of the line.
15611 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15612 first attempt, and only move to after the tags when the cursor is already
15613 beyond the end of the headline."
15614 (interactive "P")
15615 (let ((special (if (consp org-special-ctrl-a/e)
15616 (cdr org-special-ctrl-a/e)
15617 org-special-ctrl-a/e)))
15618 (if (or (not special)
15619 (not (org-on-heading-p))
15620 arg)
15621 (call-interactively (if (fboundp 'move-end-of-line)
15622 'move-end-of-line
15623 'end-of-line))
15624 (let ((pos (point)))
15625 (beginning-of-line 1)
15626 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15627 (if (eq special t)
15628 (if (or (< pos (match-beginning 1))
15629 (= pos (match-end 0)))
15630 (goto-char (match-beginning 1))
15631 (goto-char (match-end 0)))
15632 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15633 (goto-char (match-end 0))
15634 (goto-char (match-beginning 1))))
15635 (call-interactively (if (fboundp 'move-end-of-line)
15636 'move-end-of-line
15637 'end-of-line)))))
15638 (org-no-warnings
15639 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15641 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15642 (define-key org-mode-map "\C-e" 'org-end-of-line)
15644 (defun org-backward-sentence (&optional arg)
15645 "Go to beginning of sentence, or beginning of table field.
15646 This will call `backward-sentence' or `org-table-beginning-of-field',
15647 depending on context."
15648 (interactive "P")
15649 (cond
15650 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
15651 (t (call-interactively 'backward-sentence))))
15653 (defun org-forward-sentence (&optional arg)
15654 "Go to end of sentence, or end of table field.
15655 This will call `forward-sentence' or `org-table-end-of-field',
15656 depending on context."
15657 (interactive "P")
15658 (cond
15659 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
15660 (t (call-interactively 'forward-sentence))))
15662 (define-key org-mode-map "\M-a" 'org-backward-sentence)
15663 (define-key org-mode-map "\M-e" 'org-forward-sentence)
15665 (defun org-kill-line (&optional arg)
15666 "Kill line, to tags or end of line."
15667 (interactive "P")
15668 (cond
15669 ((or (not org-special-ctrl-k)
15670 (bolp)
15671 (not (org-on-heading-p)))
15672 (call-interactively 'kill-line))
15673 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15674 (kill-region (point) (match-beginning 1))
15675 (org-set-tags nil t))
15676 (t (kill-region (point) (point-at-eol)))))
15678 (define-key org-mode-map "\C-k" 'org-kill-line)
15680 (defun org-yank (&optional arg)
15681 "Yank. If the kill is a subtree, treat it specially.
15682 This command will look at the current kill and check if is a single
15683 subtree, or a series of subtrees[1]. If it passes the test, and if the
15684 cursor is at the beginning of a line or after the stars of a currently
15685 empty headline, then the yank is handled specially. How exactly depends
15686 on the value of the following variables, both set by default.
15688 org-yank-folded-subtrees
15689 When set, the subtree(s) will be folded after insertion, but only
15690 if doing so would now swallow text after the yanked text.
15692 org-yank-adjusted-subtrees
15693 When set, the subtree will be promoted or demoted in order to
15694 fit into the local outline tree structure, which means that the level
15695 will be adjusted so that it becomes the smaller one of the two
15696 *visible* surrounding headings.
15698 Any prefix to this command will cause `yank' to be called directly with
15699 no special treatment. In particular, a simple `C-u' prefix will just
15700 plainly yank the text as it is.
15702 \[1] Basically, the test checks if the first non-white line is a heading
15703 and if there are no other headings with fewer stars."
15704 (interactive "P")
15705 (setq this-command 'yank)
15706 (if arg
15707 (call-interactively 'yank)
15708 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15709 (and (org-kill-is-subtree-p)
15710 (or (bolp)
15711 (and (looking-at "[ \t]*$")
15712 (string-match
15713 "\\`\\*+\\'"
15714 (buffer-substring (point-at-bol) (point)))))))
15715 swallowp)
15716 (cond
15717 ((and subtreep org-yank-folded-subtrees)
15718 (let ((beg (point))
15719 end)
15720 (if (and subtreep org-yank-adjusted-subtrees)
15721 (org-paste-subtree nil nil 'for-yank)
15722 (call-interactively 'yank))
15723 (setq end (point))
15724 (goto-char beg)
15725 (when (and (bolp) subtreep
15726 (not (setq swallowp
15727 (org-yank-folding-would-swallow-text beg end))))
15728 (or (looking-at outline-regexp)
15729 (re-search-forward (concat "^" outline-regexp) end t))
15730 (while (and (< (point) end) (looking-at outline-regexp))
15731 (hide-subtree)
15732 (org-cycle-show-empty-lines 'folded)
15733 (condition-case nil
15734 (outline-forward-same-level 1)
15735 (error (goto-char end)))))
15736 (when swallowp
15737 (message
15738 "Yanked text not folded because that would swallow text"))
15739 (goto-char end)
15740 (skip-chars-forward " \t\n\r")
15741 (beginning-of-line 1)
15742 (push-mark beg 'nomsg)))
15743 ((and subtreep org-yank-adjusted-subtrees)
15744 (let ((beg (point-at-bol)))
15745 (org-paste-subtree nil nil 'for-yank)
15746 (push-mark beg 'nomsg)))
15748 (call-interactively 'yank))))))
15750 (defun org-yank-folding-would-swallow-text (beg end)
15751 "Would hide-subtree at BEG swallow any text after END?"
15752 (let (level)
15753 (save-excursion
15754 (goto-char beg)
15755 (when (or (looking-at outline-regexp)
15756 (re-search-forward (concat "^" outline-regexp) end t))
15757 (setq level (org-outline-level)))
15758 (goto-char end)
15759 (skip-chars-forward " \t\r\n\v\f")
15760 (if (or (eobp)
15761 (and (bolp) (looking-at org-outline-regexp)
15762 (<= (org-outline-level) level)))
15763 nil ; Nothing would be swallowed
15764 t)))) ; something would swallow
15766 (define-key org-mode-map "\C-y" 'org-yank)
15768 (defun org-invisible-p ()
15769 "Check if point is at a character currently not visible."
15770 ;; Early versions of noutline don't have `outline-invisible-p'.
15771 (if (fboundp 'outline-invisible-p)
15772 (outline-invisible-p)
15773 (get-char-property (point) 'invisible)))
15775 (defun org-invisible-p2 ()
15776 "Check if point is at a character currently not visible."
15777 (save-excursion
15778 (if (and (eolp) (not (bobp))) (backward-char 1))
15779 ;; Early versions of noutline don't have `outline-invisible-p'.
15780 (if (fboundp 'outline-invisible-p)
15781 (outline-invisible-p)
15782 (get-char-property (point) 'invisible))))
15784 (defun org-back-to-heading (&optional invisible-ok)
15785 "Call `outline-back-to-heading', but provide a better error message."
15786 (condition-case nil
15787 (outline-back-to-heading invisible-ok)
15788 (error (error "Before first headline at position %d in buffer %s"
15789 (point) (current-buffer)))))
15791 (defun org-before-first-heading-p ()
15792 "Before first heading?"
15793 (save-excursion
15794 (null (re-search-backward "^\\*+ " nil t))))
15796 (defalias 'org-on-heading-p 'outline-on-heading-p)
15797 (defalias 'org-at-heading-p 'outline-on-heading-p)
15798 (defun org-at-heading-or-item-p ()
15799 (or (org-on-heading-p) (org-at-item-p)))
15801 (defun org-on-target-p ()
15802 (or (org-in-regexp org-radio-target-regexp)
15803 (org-in-regexp org-target-regexp)))
15805 (defun org-up-heading-all (arg)
15806 "Move to the heading line of which the present line is a subheading.
15807 This function considers both visible and invisible heading lines.
15808 With argument, move up ARG levels."
15809 (if (fboundp 'outline-up-heading-all)
15810 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15811 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15813 (defun org-up-heading-safe ()
15814 "Move to the heading line of which the present line is a subheading.
15815 This version will not throw an error. It will return the level of the
15816 headline found, or nil if no higher level is found.
15818 Also, this function will be a lot faster than `outline-up-heading',
15819 because it relies on stars being the outline starters. This can really
15820 make a significant difference in outlines with very many siblings."
15821 (let (start-level re)
15822 (org-back-to-heading t)
15823 (setq start-level (funcall outline-level))
15824 (if (equal start-level 1)
15826 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
15827 (if (re-search-backward re nil t)
15828 (funcall outline-level)))))
15830 (defun org-first-sibling-p ()
15831 "Is this heading the first child of its parents?"
15832 (interactive)
15833 (let ((re (concat "^" outline-regexp))
15834 level l)
15835 (unless (org-at-heading-p t)
15836 (error "Not at a heading"))
15837 (setq level (funcall outline-level))
15838 (save-excursion
15839 (if (not (re-search-backward re nil t))
15841 (setq l (funcall outline-level))
15842 (< l level)))))
15844 (defun org-goto-sibling (&optional previous)
15845 "Goto the next sibling, even if it is invisible.
15846 When PREVIOUS is set, go to the previous sibling instead. Returns t
15847 when a sibling was found. When none is found, return nil and don't
15848 move point."
15849 (let ((fun (if previous 're-search-backward 're-search-forward))
15850 (pos (point))
15851 (re (concat "^" outline-regexp))
15852 level l)
15853 (when (condition-case nil (org-back-to-heading t) (error nil))
15854 (setq level (funcall outline-level))
15855 (catch 'exit
15856 (or previous (forward-char 1))
15857 (while (funcall fun re nil t)
15858 (setq l (funcall outline-level))
15859 (when (< l level) (goto-char pos) (throw 'exit nil))
15860 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15861 (goto-char pos)
15862 nil))))
15864 (defun org-show-siblings ()
15865 "Show all siblings of the current headline."
15866 (save-excursion
15867 (while (org-goto-sibling) (org-flag-heading nil)))
15868 (save-excursion
15869 (while (org-goto-sibling 'previous)
15870 (org-flag-heading nil))))
15872 (defun org-show-hidden-entry ()
15873 "Show an entry where even the heading is hidden."
15874 (save-excursion
15875 (org-show-entry)))
15877 (defun org-flag-heading (flag &optional entry)
15878 "Flag the current heading. FLAG non-nil means make invisible.
15879 When ENTRY is non-nil, show the entire entry."
15880 (save-excursion
15881 (org-back-to-heading t)
15882 ;; Check if we should show the entire entry
15883 (if entry
15884 (progn
15885 (org-show-entry)
15886 (save-excursion
15887 (and (outline-next-heading)
15888 (org-flag-heading nil))))
15889 (outline-flag-region (max (point-min) (1- (point)))
15890 (save-excursion (outline-end-of-heading) (point))
15891 flag))))
15893 (defun org-forward-same-level (arg)
15894 "Move forward to the ARG'th subheading at same level as this one.
15895 Stop at the first and last subheadings of a superior heading.
15896 This is like outline-forward-same-level, but invisible headings are ok."
15897 (interactive "p")
15898 (org-back-to-heading t)
15899 (while (> arg 0)
15900 (let ((point-to-move-to (save-excursion
15901 (org-get-next-sibling))))
15902 (if point-to-move-to
15903 (progn
15904 (goto-char point-to-move-to)
15905 (setq arg (1- arg)))
15906 (progn
15907 (setq arg 0)
15908 (error "No following same-level heading"))))))
15910 (defun org-get-next-sibling ()
15911 "Move to next heading of the same level, and return point.
15912 If there is no such heading, return nil.
15913 This is like outline-next-sibling, but invisible headings are ok."
15914 (let ((level (funcall outline-level)))
15915 (outline-next-heading)
15916 (while (and (not (eobp)) (> (funcall outline-level) level))
15917 (outline-next-heading))
15918 (if (or (eobp) (< (funcall outline-level) level))
15920 (point))))
15922 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15923 ;; This is an exact copy of the original function, but it uses
15924 ;; `org-back-to-heading', to make it work also in invisible
15925 ;; trees. And is uses an invisible-OK argument.
15926 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15927 (org-back-to-heading invisible-OK)
15928 (let ((first t)
15929 (level (funcall outline-level)))
15930 (while (and (not (eobp))
15931 (or first (> (funcall outline-level) level)))
15932 (setq first nil)
15933 (outline-next-heading))
15934 (unless to-heading
15935 (if (memq (preceding-char) '(?\n ?\^M))
15936 (progn
15937 ;; Go to end of line before heading
15938 (forward-char -1)
15939 (if (memq (preceding-char) '(?\n ?\^M))
15940 ;; leave blank line before heading
15941 (forward-char -1))))))
15942 (point))
15944 (defun org-show-subtree ()
15945 "Show everything after this heading at deeper levels."
15946 (outline-flag-region
15947 (point)
15948 (save-excursion
15949 (outline-end-of-subtree) (outline-next-heading) (point))
15950 nil))
15952 (defun org-show-entry ()
15953 "Show the body directly following this heading.
15954 Show the heading too, if it is currently invisible."
15955 (interactive)
15956 (save-excursion
15957 (condition-case nil
15958 (progn
15959 (org-back-to-heading t)
15960 (outline-flag-region
15961 (max (point-min) (1- (point)))
15962 (save-excursion
15963 (if (re-search-forward
15964 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
15965 (match-beginning 1)
15966 (point-max)))
15967 nil))
15968 (error nil))))
15970 (defun org-make-options-regexp (kwds &optional extra)
15971 "Make a regular expression for keyword lines."
15972 (concat
15974 "#?[ \t]*\\+\\("
15975 (mapconcat 'regexp-quote kwds "\\|")
15976 (if extra (concat "\\|" extra))
15977 "\\):[ \t]*"
15978 "\\(.+\\)"))
15980 ;; Make isearch reveal the necessary context
15981 (defun org-isearch-end ()
15982 "Reveal context after isearch exits."
15983 (when isearch-success ; only if search was successful
15984 (if (featurep 'xemacs)
15985 ;; Under XEmacs, the hook is run in the correct place,
15986 ;; we directly show the context.
15987 (org-show-context 'isearch)
15988 ;; In Emacs the hook runs *before* restoring the overlays.
15989 ;; So we have to use a one-time post-command-hook to do this.
15990 ;; (Emacs 22 has a special variable, see function `org-mode')
15991 (unless (and (boundp 'isearch-mode-end-hook-quit)
15992 isearch-mode-end-hook-quit)
15993 ;; Only when the isearch was not quitted.
15994 (org-add-hook 'post-command-hook 'org-isearch-post-command
15995 'append 'local)))))
15997 (defun org-isearch-post-command ()
15998 "Remove self from hook, and show context."
15999 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16000 (org-show-context 'isearch))
16003 ;;;; Integration with and fixes for other packages
16005 ;;; Imenu support
16007 (defvar org-imenu-markers nil
16008 "All markers currently used by Imenu.")
16009 (make-variable-buffer-local 'org-imenu-markers)
16011 (defun org-imenu-new-marker (&optional pos)
16012 "Return a new marker for use by Imenu, and remember the marker."
16013 (let ((m (make-marker)))
16014 (move-marker m (or pos (point)))
16015 (push m org-imenu-markers)
16018 (defun org-imenu-get-tree ()
16019 "Produce the index for Imenu."
16020 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16021 (setq org-imenu-markers nil)
16022 (let* ((n org-imenu-depth)
16023 (re (concat "^" outline-regexp))
16024 (subs (make-vector (1+ n) nil))
16025 (last-level 0)
16026 m level head)
16027 (save-excursion
16028 (save-restriction
16029 (widen)
16030 (goto-char (point-max))
16031 (while (re-search-backward re nil t)
16032 (setq level (org-reduced-level (funcall outline-level)))
16033 (when (<= level n)
16034 (looking-at org-complex-heading-regexp)
16035 (setq head (org-link-display-format
16036 (org-match-string-no-properties 4))
16037 m (org-imenu-new-marker))
16038 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16039 (if (>= level last-level)
16040 (push (cons head m) (aref subs level))
16041 (push (cons head (aref subs (1+ level))) (aref subs level))
16042 (loop for i from (1+ level) to n do (aset subs i nil)))
16043 (setq last-level level)))))
16044 (aref subs 1)))
16046 (eval-after-load "imenu"
16047 '(progn
16048 (add-hook 'imenu-after-jump-hook
16049 (lambda ()
16050 (if (eq major-mode 'org-mode)
16051 (org-show-context 'org-goto))))))
16053 (defun org-link-display-format (link)
16054 "Replace a link with either the description, or the link target
16055 if no description is present"
16056 (save-match-data
16057 (if (string-match org-bracket-link-analytic-regexp link)
16058 (replace-match (or (match-string 5 link)
16059 (concat (match-string 1 link)
16060 (match-string 3 link)))
16061 nil nil link)
16062 link)))
16064 ;; Speedbar support
16066 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16067 "Overlay marking the agenda restriction line in speedbar.")
16068 (org-overlay-put org-speedbar-restriction-lock-overlay
16069 'face 'org-agenda-restriction-lock)
16070 (org-overlay-put org-speedbar-restriction-lock-overlay
16071 'help-echo "Agendas are currently limited to this item.")
16072 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16074 (defun org-speedbar-set-agenda-restriction ()
16075 "Restrict future agenda commands to the location at point in speedbar.
16076 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16077 (interactive)
16078 (require 'org-agenda)
16079 (let (p m tp np dir txt)
16080 (cond
16081 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16082 'org-imenu t))
16083 (setq m (get-text-property p 'org-imenu-marker))
16084 (save-excursion
16085 (save-restriction
16086 (set-buffer (marker-buffer m))
16087 (goto-char m)
16088 (org-agenda-set-restriction-lock 'subtree))))
16089 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16090 'speedbar-function 'speedbar-find-file))
16091 (setq tp (previous-single-property-change
16092 (1+ p) 'speedbar-function)
16093 np (next-single-property-change
16094 tp 'speedbar-function)
16095 dir (speedbar-line-directory)
16096 txt (buffer-substring-no-properties (or tp (point-min))
16097 (or np (point-max))))
16098 (save-excursion
16099 (save-restriction
16100 (set-buffer (find-file-noselect
16101 (let ((default-directory dir))
16102 (expand-file-name txt))))
16103 (unless (org-mode-p)
16104 (error "Cannot restrict to non-Org-mode file"))
16105 (org-agenda-set-restriction-lock 'file))))
16106 (t (error "Don't know how to restrict Org-mode's agenda")))
16107 (org-move-overlay org-speedbar-restriction-lock-overlay
16108 (point-at-bol) (point-at-eol))
16109 (setq current-prefix-arg nil)
16110 (org-agenda-maybe-redo)))
16112 (eval-after-load "speedbar"
16113 '(progn
16114 (speedbar-add-supported-extension ".org")
16115 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16116 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16117 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16118 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16119 (add-hook 'speedbar-visiting-tag-hook
16120 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16123 ;;; Fixes and Hacks for problems with other packages
16125 ;; Make flyspell not check words in links, to not mess up our keymap
16126 (defun org-mode-flyspell-verify ()
16127 "Don't let flyspell put overlays at active buttons."
16128 (not (get-text-property (point) 'keymap)))
16130 ;; Make `bookmark-jump' show the jump location if it was hidden.
16131 (eval-after-load "bookmark"
16132 '(if (boundp 'bookmark-after-jump-hook)
16133 ;; We can use the hook
16134 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16135 ;; Hook not available, use advice
16136 (defadvice bookmark-jump (after org-make-visible activate)
16137 "Make the position visible."
16138 (org-bookmark-jump-unhide))))
16140 ;; Make sure saveplace show the location if it was hidden
16141 (eval-after-load "saveplace"
16142 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16143 "Make the position visible."
16144 (org-bookmark-jump-unhide)))
16146 (defun org-bookmark-jump-unhide ()
16147 "Unhide the current position, to show the bookmark location."
16148 (and (org-mode-p)
16149 (or (org-invisible-p)
16150 (save-excursion (goto-char (max (point-min) (1- (point))))
16151 (org-invisible-p)))
16152 (org-show-context 'bookmark-jump)))
16154 ;; Make session.el ignore our circular variable
16155 (eval-after-load "session"
16156 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16158 ;;;; Experimental code
16160 (defun org-closed-in-range ()
16161 "Sparse tree of items closed in a certain time range.
16162 Still experimental, may disappear in the future."
16163 (interactive)
16164 ;; Get the time interval from the user.
16165 (let* ((time1 (time-to-seconds
16166 (org-read-date nil 'to-time nil "Starting date: ")))
16167 (time2 (time-to-seconds
16168 (org-read-date nil 'to-time nil "End date:")))
16169 ;; callback function
16170 (callback (lambda ()
16171 (let ((time
16172 (time-to-seconds
16173 (apply 'encode-time
16174 (org-parse-time-string
16175 (match-string 1))))))
16176 ;; check if time in interval
16177 (and (>= time time1) (<= time time2))))))
16178 ;; make tree, check each match with the callback
16179 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16181 ;;;; Finish up
16183 (provide 'org)
16185 (run-hooks 'org-load-hook)
16187 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16189 ;;; org.el ends here