LaTeX export: Format time stamps
[org-mode/org-kjn.git] / lisp / org.el
blobc3314278cf2edacdc3def361eccdb388239e484d
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/paste 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 (OBSOLETE, use org-protocol)" 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 (OBSOLETE, use org-protocol)" 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 (PARTIALLY OBSOLETE, see built-in dependency support))" 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 (PARTIALLY OBSOLETE, see secondary filtering)" 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. The custom formats are also honored by export
2026 commands, if custom time display is turned on at the time of export."
2027 :group 'org-time
2028 :type 'sexp)
2030 (defun org-time-stamp-format (&optional long inactive)
2031 "Get the right format for a time string."
2032 (let ((f (if long (cdr org-time-stamp-formats)
2033 (car org-time-stamp-formats))))
2034 (if inactive
2035 (concat "[" (substring f 1 -1) "]")
2036 f)))
2038 (defcustom org-time-clocksum-format "%d:%02d"
2039 "The format string used when creating CLOCKSUM lines, or when
2040 org-mode generates a time duration."
2041 :group 'org-time
2042 :type 'string)
2044 (defcustom org-deadline-warning-days 14
2045 "No. of days before expiration during which a deadline becomes active.
2046 This variable governs the display in sparse trees and in the agenda.
2047 When 0 or negative, it means use this number (the absolute value of it)
2048 even if a deadline has a different individual lead time specified.
2050 Custom commands can set this variable in the options section."
2051 :group 'org-time
2052 :group 'org-agenda-daily/weekly
2053 :type 'integer)
2055 (defcustom org-read-date-prefer-future t
2056 "Non-nil means, assume future for incomplete date input from user.
2057 This affects the following situations:
2058 1. The user gives a day, but no month.
2059 For example, if today is the 15th, and you enter \"3\", Org-mode will
2060 read this as the third of *next* month. However, if you enter \"17\",
2061 it will be considered as *this* month.
2062 2. The user gives a month but not a year.
2063 For example, if it is april and you enter \"feb 2\", this will be read
2064 as feb 2, *next* year. \"May 5\", however, will be this year.
2066 Currently this does not work for ISO week specifications.
2068 When this option is nil, the current month and year will always be used
2069 as defaults."
2070 :group 'org-time
2071 :type 'boolean)
2073 (defcustom org-read-date-display-live t
2074 "Non-nil means, display current interpretation of date prompt live.
2075 This display will be in an overlay, in the minibuffer."
2076 :group 'org-time
2077 :type 'boolean)
2079 (defcustom org-read-date-popup-calendar t
2080 "Non-nil means, pop up a calendar when prompting for a date.
2081 In the calendar, the date can be selected with mouse-1. However, the
2082 minibuffer will also be active, and you can simply enter the date as well.
2083 When nil, only the minibuffer will be available."
2084 :group 'org-time
2085 :type 'boolean)
2086 (if (fboundp 'defvaralias)
2087 (defvaralias 'org-popup-calendar-for-date-prompt
2088 'org-read-date-popup-calendar))
2090 (defcustom org-read-date-minibuffer-setup-hook nil
2091 "Hook to be used to set up keys for the date/time interface.
2092 Add key definitions to `minibuffer-local-map', which will be a temporary
2093 copy."
2094 :group 'org-time
2095 :type 'hook)
2097 (defcustom org-extend-today-until 0
2098 "The hour when your day really ends. Must be an integer.
2099 This has influence for the following applications:
2100 - When switching the agenda to \"today\". It it is still earlier than
2101 the time given here, the day recognized as TODAY is actually yesterday.
2102 - When a date is read from the user and it is still before the time given
2103 here, the current date and time will be assumed to be yesterday, 23:59.
2104 Also, timestamps inserted in remember templates follow this rule.
2106 IMPORTANT: This is a feature whose implementation is and likely will
2107 remain incomplete. Really, it is only here because past midnight seems to
2108 be the favorite working time of John Wiegley :-)"
2109 :group 'org-time
2110 :type 'integer)
2112 (defcustom org-edit-timestamp-down-means-later nil
2113 "Non-nil means, S-down will increase the time in a time stamp.
2114 When nil, S-up will increase."
2115 :group 'org-time
2116 :type 'boolean)
2118 (defcustom org-calendar-follow-timestamp-change t
2119 "Non-nil means, make the calendar window follow timestamp changes.
2120 When a timestamp is modified and the calendar window is visible, it will be
2121 moved to the new date."
2122 :group 'org-time
2123 :type 'boolean)
2125 (defgroup org-tags nil
2126 "Options concerning tags in Org-mode."
2127 :tag "Org Tags"
2128 :group 'org)
2130 (defcustom org-tag-alist nil
2131 "List of tags allowed in Org-mode files.
2132 When this list is nil, Org-mode will base TAG input on what is already in the
2133 buffer.
2134 The value of this variable is an alist, the car of each entry must be a
2135 keyword as a string, the cdr may be a character that is used to select
2136 that tag through the fast-tag-selection interface.
2137 See the manual for details."
2138 :group 'org-tags
2139 :type '(repeat
2140 (choice
2141 (cons (string :tag "Tag name")
2142 (character :tag "Access char"))
2143 (const :tag "Start radio group" (:startgroup))
2144 (const :tag "End radio group" (:endgroup))
2145 (const :tag "New line" (:newline)))))
2147 (defcustom org-tag-persistent-alist nil
2148 "List of tags that will always appear in all Org-mode files.
2149 This is in addition to any in buffer settings or customizations
2150 of `org-tag-alist'.
2151 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2152 The value of this variable is an alist, the car of each entry must be a
2153 keyword as a string, the cdr may be a character that is used to select
2154 that tag through the fast-tag-selection interface.
2155 See the manual for details.
2156 To disable these tags on a per-file basis, insert anywhere in the file:
2157 #+STARTUP: noptag"
2158 :group 'org-tags
2159 :type '(repeat
2160 (choice
2161 (cons (string :tag "Tag name")
2162 (character :tag "Access char"))
2163 (const :tag "Start radio group" (:startgroup))
2164 (const :tag "End radio group" (:endgroup))
2165 (const :tag "New line" (:newline)))))
2167 (defvar org-file-tags nil
2168 "List of tags that can be inherited by all entries in the file.
2169 The tags will be inherited if the variable `org-use-tag-inheritance'
2170 says they should be.
2171 This variable is populated from #+TAG lines.")
2173 (defcustom org-use-fast-tag-selection 'auto
2174 "Non-nil means, use fast tag selection scheme.
2175 This is a special interface to select and deselect tags with single keys.
2176 When nil, fast selection is never used.
2177 When the symbol `auto', fast selection is used if and only if selection
2178 characters for tags have been configured, either through the variable
2179 `org-tag-alist' or through a #+TAGS line in the buffer.
2180 When t, fast selection is always used and selection keys are assigned
2181 automatically if necessary."
2182 :group 'org-tags
2183 :type '(choice
2184 (const :tag "Always" t)
2185 (const :tag "Never" nil)
2186 (const :tag "When selection characters are configured" 'auto)))
2188 (defcustom org-fast-tag-selection-single-key nil
2189 "Non-nil means, fast tag selection exits after first change.
2190 When nil, you have to press RET to exit it.
2191 During fast tag selection, you can toggle this flag with `C-c'.
2192 This variable can also have the value `expert'. In this case, the window
2193 displaying the tags menu is not even shown, until you press C-c again."
2194 :group 'org-tags
2195 :type '(choice
2196 (const :tag "No" nil)
2197 (const :tag "Yes" t)
2198 (const :tag "Expert" expert)))
2200 (defvar org-fast-tag-selection-include-todo nil
2201 "Non-nil means, fast tags selection interface will also offer TODO states.
2202 This is an undocumented feature, you should not rely on it.")
2204 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2205 "The column to which tags should be indented in a headline.
2206 If this number is positive, it specifies the column. If it is negative,
2207 it means that the tags should be flushright to that column. For example,
2208 -80 works well for a normal 80 character screen."
2209 :group 'org-tags
2210 :type 'integer)
2212 (defcustom org-auto-align-tags t
2213 "Non-nil means, realign tags after pro/demotion of TODO state change.
2214 These operations change the length of a headline and therefore shift
2215 the tags around. With this options turned on, after each such operation
2216 the tags are again aligned to `org-tags-column'."
2217 :group 'org-tags
2218 :type 'boolean)
2220 (defcustom org-use-tag-inheritance t
2221 "Non-nil means, tags in levels apply also for sublevels.
2222 When nil, only the tags directly given in a specific line apply there.
2223 This may also be a list of tags that should be inherited, or a regexp that
2224 matches tags that should be inherited. Additional control is possible
2225 with the variable `org-tags-exclude-from-inheritance' which gives an
2226 explicit list of tags to be excluded from inheritance., even if the value of
2227 `org-use-tag-inheritance' would select it for inheritance.
2229 If this option is t, a match early-on in a tree can lead to a large
2230 number of matches in the subtree when constructing the agenda or creating
2231 a sparse tree. If you only want to see the first match in a tree during
2232 a search, check out the variable `org-tags-match-list-sublevels'."
2233 :group 'org-tags
2234 :type '(choice
2235 (const :tag "Not" nil)
2236 (const :tag "Always" t)
2237 (repeat :tag "Specific tags" (string :tag "Tag"))
2238 (regexp :tag "Tags matched by regexp")))
2240 (defcustom org-tags-exclude-from-inheritance nil
2241 "List of tags that should never be inherited.
2242 This is a way to exclude a few tags from inheritance. For way to do
2243 the opposite, to actively allow inheritance for selected tags,
2244 see the variable `org-use-tag-inheritance'."
2245 :group 'org-tags
2246 :type '(repeat (string :tag "Tag")))
2248 (defun org-tag-inherit-p (tag)
2249 "Check if TAG is one that should be inherited."
2250 (cond
2251 ((member tag org-tags-exclude-from-inheritance) nil)
2252 ((eq org-use-tag-inheritance t) t)
2253 ((not org-use-tag-inheritance) nil)
2254 ((stringp org-use-tag-inheritance)
2255 (string-match org-use-tag-inheritance tag))
2256 ((listp org-use-tag-inheritance)
2257 (member tag org-use-tag-inheritance))
2258 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2260 (defcustom org-tags-match-list-sublevels t
2261 "Non-nil means list also sublevels of headlines matching a search.
2262 This variable applies to tags/property searches, and also to stuck
2263 projects because this search is based on a tags match as well.
2265 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2266 the sublevels of a headline matching a tag search often also match
2267 the same search. Listing all of them can create very long lists.
2268 Setting this variable to nil causes subtrees of a match to be skipped.
2270 As a special case, if the tag search is restricted to TODO items, the
2271 value of this variable is ignored and sublevels are always checked, to
2272 make sure all corresponding TODO items find their way into the list.
2274 This variable is semi-obsolete and probably should always be true. It
2275 is better to limit inheritance to certain tags using the variables
2276 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2277 :group 'org-tags
2278 :type '(choice
2279 (const :tag "No, don't list them" nil)
2280 (const :tag "Yes, do list them" t)
2281 (const :tag "List them, indented with leading dots" indented)))
2283 (defvar org-tags-history nil
2284 "History of minibuffer reads for tags.")
2285 (defvar org-last-tags-completion-table nil
2286 "The last used completion table for tags.")
2287 (defvar org-after-tags-change-hook nil
2288 "Hook that is run after the tags in a line have changed.")
2290 (defgroup org-properties nil
2291 "Options concerning properties in Org-mode."
2292 :tag "Org Properties"
2293 :group 'org)
2295 (defcustom org-property-format "%-10s %s"
2296 "How property key/value pairs should be formatted by `indent-line'.
2297 When `indent-line' hits a property definition, it will format the line
2298 according to this format, mainly to make sure that the values are
2299 lined-up with respect to each other."
2300 :group 'org-properties
2301 :type 'string)
2303 (defcustom org-use-property-inheritance nil
2304 "Non-nil means, properties apply also for sublevels.
2306 This setting is chiefly used during property searches. Turning it on can
2307 cause significant overhead when doing a search, which is why it is not
2308 on by default.
2310 When nil, only the properties directly given in the current entry count.
2311 When t, every property is inherited. The value may also be a list of
2312 properties that should have inheritance, or a regular expression matching
2313 properties that should be inherited.
2315 However, note that some special properties use inheritance under special
2316 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2317 and the properties ending in \"_ALL\" when they are used as descriptor
2318 for valid values of a property.
2320 Note for programmers:
2321 When querying an entry with `org-entry-get', you can control if inheritance
2322 should be used. By default, `org-entry-get' looks only at the local
2323 properties. You can request inheritance by setting the inherit argument
2324 to t (to force inheritance) or to `selective' (to respect the setting
2325 in this variable)."
2326 :group 'org-properties
2327 :type '(choice
2328 (const :tag "Not" nil)
2329 (const :tag "Always" t)
2330 (repeat :tag "Specific properties" (string :tag "Property"))
2331 (regexp :tag "Properties matched by regexp")))
2333 (defun org-property-inherit-p (property)
2334 "Check if PROPERTY is one that should be inherited."
2335 (cond
2336 ((eq org-use-property-inheritance t) t)
2337 ((not org-use-property-inheritance) nil)
2338 ((stringp org-use-property-inheritance)
2339 (string-match org-use-property-inheritance property))
2340 ((listp org-use-property-inheritance)
2341 (member property org-use-property-inheritance))
2342 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2344 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2345 "The default column format, if no other format has been defined.
2346 This variable can be set on the per-file basis by inserting a line
2348 #+COLUMNS: %25ITEM ....."
2349 :group 'org-properties
2350 :type 'string)
2352 (defcustom org-columns-ellipses ".."
2353 "The ellipses to be used when a field in column view is truncated.
2354 When this is the empty string, as many characters as possible are shown,
2355 but then there will be no visual indication that the field has been truncated.
2356 When this is a string of length N, the last N characters of a truncated
2357 field are replaced by this string. If the column is narrower than the
2358 ellipses string, only part of the ellipses string will be shown."
2359 :group 'org-properties
2360 :type 'string)
2362 (defcustom org-columns-modify-value-for-display-function nil
2363 "Function that modifies values for display in column view.
2364 For example, it can be used to cut out a certain part from a time stamp.
2365 The function must take 2 arguments:
2367 column-title The title of the column (*not* the property name)
2368 value The value that should be modified.
2370 The function should return the value that should be displayed,
2371 or nil if the normal value should be used."
2372 :group 'org-properties
2373 :type 'function)
2375 (defcustom org-effort-property "Effort"
2376 "The property that is being used to keep track of effort estimates.
2377 Effort estimates given in this property need to have the format H:MM."
2378 :group 'org-properties
2379 :group 'org-progress
2380 :type '(string :tag "Property"))
2382 (defconst org-global-properties-fixed
2383 '(("VISIBILITY_ALL" . "folded children content all"))
2384 "List of property/value pairs that can be inherited by any entry.
2386 These are fixed values, for the preset properties. The user variable
2387 that can be used to add to this list is `org-global-properties'.
2389 The entries in this list are cons cells where the car is a property
2390 name and cdr is a string with the value. If the value represents
2391 multiple items like an \"_ALL\" property, separate the items by
2392 spaces.")
2394 (defcustom org-global-properties nil
2395 "List of property/value pairs that can be inherited by any entry.
2397 This list will be combined with the constant `org-global-properties-fixed'.
2399 The entries in this list are cons cells where the car is a property
2400 name and cdr is a string with the value.
2402 You can set buffer-local values for the same purpose in the variable
2403 `org-file-properties' this by adding lines like
2405 #+PROPERTY: NAME VALUE"
2406 :group 'org-properties
2407 :type '(repeat
2408 (cons (string :tag "Property")
2409 (string :tag "Value"))))
2411 (defvar org-file-properties nil
2412 "List of property/value pairs that can be inherited by any entry.
2413 Valid for the current buffer.
2414 This variable is populated from #+PROPERTY lines.")
2415 (make-variable-buffer-local 'org-file-properties)
2417 (defgroup org-agenda nil
2418 "Options concerning agenda views in Org-mode."
2419 :tag "Org Agenda"
2420 :group 'org)
2422 (defvar org-category nil
2423 "Variable used by org files to set a category for agenda display.
2424 Such files should use a file variable to set it, for example
2426 # -*- mode: org; org-category: \"ELisp\"
2428 or contain a special line
2430 #+CATEGORY: ELisp
2432 If the file does not specify a category, then file's base name
2433 is used instead.")
2434 (make-variable-buffer-local 'org-category)
2435 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2437 (defcustom org-agenda-files nil
2438 "The files to be used for agenda display.
2439 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2440 \\[org-remove-file]. You can also use customize to edit the list.
2442 If an entry is a directory, all files in that directory that are matched by
2443 `org-agenda-file-regexp' will be part of the file list.
2445 If the value of the variable is not a list but a single file name, then
2446 the list of agenda files is actually stored and maintained in that file, one
2447 agenda file per line."
2448 :group 'org-agenda
2449 :type '(choice
2450 (repeat :tag "List of files and directories" file)
2451 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2453 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2454 "Regular expression to match files for `org-agenda-files'.
2455 If any element in the list in that variable contains a directory instead
2456 of a normal file, all files in that directory that are matched by this
2457 regular expression will be included."
2458 :group 'org-agenda
2459 :type 'regexp)
2461 (defcustom org-agenda-text-search-extra-files nil
2462 "List of extra files to be searched by text search commands.
2463 These files will be search in addition to the agenda files by the
2464 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2465 Note that these files will only be searched for text search commands,
2466 not for the other agenda views like todo lists, tag searches or the weekly
2467 agenda. This variable is intended to list notes and possibly archive files
2468 that should also be searched by these two commands.
2469 In fact, if the first element in the list is the symbol `agenda-archives',
2470 than all archive files of all agenda files will be added to the search
2471 scope."
2472 :group 'org-agenda
2473 :type '(set :greedy t
2474 (const :tag "Agenda Archives" agenda-archives)
2475 (repeat :inline t (file))))
2477 (if (fboundp 'defvaralias)
2478 (defvaralias 'org-agenda-multi-occur-extra-files
2479 'org-agenda-text-search-extra-files))
2481 (defcustom org-agenda-skip-unavailable-files nil
2482 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2483 A nil value means to remove them, after a query, from the list."
2484 :group 'org-agenda
2485 :type 'boolean)
2487 (defcustom org-calendar-to-agenda-key [?c]
2488 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2489 The command `org-calendar-goto-agenda' will be bound to this key. The
2490 default is the character `c' because then `c' can be used to switch back and
2491 forth between agenda and calendar."
2492 :group 'org-agenda
2493 :type 'sexp)
2495 (defcustom org-calendar-agenda-action-key [?k]
2496 "The key to be installed in `calendar-mode-map' for agenda-action.
2497 The command `org-agenda-action' will be bound to this key. The
2498 default is the character `k' because we use the same key in the agenda."
2499 :group 'org-agenda
2500 :type 'sexp)
2502 (eval-after-load "calendar"
2503 '(progn
2504 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2505 'org-calendar-goto-agenda)
2506 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2507 'org-agenda-action)))
2509 (defgroup org-latex nil
2510 "Options for embedding LaTeX code into Org-mode."
2511 :tag "Org LaTeX"
2512 :group 'org)
2514 (defcustom org-format-latex-options
2515 '(:foreground default :background default :scale 1.0
2516 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2517 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2518 "Options for creating images from LaTeX fragments.
2519 This is a property list with the following properties:
2520 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2521 `default' means use the foreground of the default face.
2522 :background the background color, or \"Transparent\".
2523 `default' means use the background of the default face.
2524 :scale a scaling factor for the size of the images.
2525 :html-foreground, :html-background, :html-scale
2526 the same numbers for HTML export.
2527 :matchers a list indicating which matchers should be used to
2528 find LaTeX fragments. Valid members of this list are:
2529 \"begin\" find environments
2530 \"$1\" find single characters surrounded by $.$
2531 \"$\" find math expressions surrounded by $...$
2532 \"$$\" find math expressions surrounded by $$....$$
2533 \"\\(\" find math expressions surrounded by \\(...\\)
2534 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2535 :group 'org-latex
2536 :type 'plist)
2538 (defcustom org-format-latex-header "\\documentclass{article}
2539 \\usepackage{fullpage} % do not remove
2540 \\usepackage{amssymb}
2541 \\usepackage[usenames]{color}
2542 \\usepackage{amsmath}
2543 \\usepackage{latexsym}
2544 \\usepackage[mathscr]{eucal}
2545 \\pagestyle{empty} % do not remove"
2546 "The document header used for processing LaTeX fragments."
2547 :group 'org-latex
2548 :type 'string)
2551 (defgroup org-font-lock nil
2552 "Font-lock settings for highlighting in Org-mode."
2553 :tag "Org Font Lock"
2554 :group 'org)
2556 (defcustom org-level-color-stars-only nil
2557 "Non-nil means fontify only the stars in each headline.
2558 When nil, the entire headline is fontified.
2559 Changing it requires restart of `font-lock-mode' to become effective
2560 also in regions already fontified."
2561 :group 'org-font-lock
2562 :type 'boolean)
2564 (defcustom org-hide-leading-stars nil
2565 "Non-nil means, hide the first N-1 stars in a headline.
2566 This works by using the face `org-hide' for these stars. This
2567 face is white for a light background, and black for a dark
2568 background. You may have to customize the face `org-hide' to
2569 make this work.
2570 Changing it requires restart of `font-lock-mode' to become effective
2571 also in regions already fontified.
2572 You may also set this on a per-file basis by adding one of the following
2573 lines to the buffer:
2575 #+STARTUP: hidestars
2576 #+STARTUP: showstars"
2577 :group 'org-font-lock
2578 :type 'boolean)
2580 (defcustom org-fontify-done-headline nil
2581 "Non-nil means, change the face of a headline if it is marked DONE.
2582 Normally, only the TODO/DONE keyword indicates the state of a headline.
2583 When this is non-nil, the headline after the keyword is set to the
2584 `org-headline-done' as an additional indication."
2585 :group 'org-font-lock
2586 :type 'boolean)
2588 (defcustom org-fontify-emphasized-text t
2589 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2590 Changing this variable requires a restart of Emacs to take effect."
2591 :group 'org-font-lock
2592 :type 'boolean)
2594 (defcustom org-highlight-latex-fragments-and-specials nil
2595 "Non-nil means, fontify what is treated specially by the exporters."
2596 :group 'org-font-lock
2597 :type 'boolean)
2599 (defcustom org-hide-emphasis-markers nil
2600 "Non-nil mean font-lock should hide the emphasis marker characters."
2601 :group 'org-font-lock
2602 :type 'boolean)
2604 (defvar org-emph-re nil
2605 "Regular expression for matching emphasis.")
2606 (defvar org-verbatim-re nil
2607 "Regular expression for matching verbatim text.")
2608 (defvar org-emphasis-regexp-components) ; defined just below
2609 (defvar org-emphasis-alist) ; defined just below
2610 (defun org-set-emph-re (var val)
2611 "Set variable and compute the emphasis regular expression."
2612 (set var val)
2613 (when (and (boundp 'org-emphasis-alist)
2614 (boundp 'org-emphasis-regexp-components)
2615 org-emphasis-alist org-emphasis-regexp-components)
2616 (let* ((e org-emphasis-regexp-components)
2617 (pre (car e))
2618 (post (nth 1 e))
2619 (border (nth 2 e))
2620 (body (nth 3 e))
2621 (nl (nth 4 e))
2622 (body1 (concat body "*?"))
2623 (markers (mapconcat 'car org-emphasis-alist ""))
2624 (vmarkers (mapconcat
2625 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2626 org-emphasis-alist "")))
2627 ;; make sure special characters appear at the right position in the class
2628 (if (string-match "\\^" markers)
2629 (setq markers (concat (replace-match "" t t markers) "^")))
2630 (if (string-match "-" markers)
2631 (setq markers (concat (replace-match "" t t markers) "-")))
2632 (if (string-match "\\^" vmarkers)
2633 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2634 (if (string-match "-" vmarkers)
2635 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2636 (if (> nl 0)
2637 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2638 (int-to-string nl) "\\}")))
2639 ;; Make the regexp
2640 (setq org-emph-re
2641 (concat "\\([" pre "]\\|^\\)"
2642 "\\("
2643 "\\([" markers "]\\)"
2644 "\\("
2645 "[^" border "]\\|"
2646 "[^" border "]"
2647 body1
2648 "[^" border "]"
2649 "\\)"
2650 "\\3\\)"
2651 "\\([" post "]\\|$\\)"))
2652 (setq org-verbatim-re
2653 (concat "\\([" pre "]\\|^\\)"
2654 "\\("
2655 "\\([" vmarkers "]\\)"
2656 "\\("
2657 "[^" border "]\\|"
2658 "[^" border "]"
2659 body1
2660 "[^" border "]"
2661 "\\)"
2662 "\\3\\)"
2663 "\\([" post "]\\|$\\)")))))
2665 (defcustom org-emphasis-regexp-components
2666 '(" \t('\"{" "- \t.,:!?;'\")}" " \t\r\n,\"'" "." 1)
2667 "Components used to build the regular expression for emphasis.
2668 This is a list with 6 entries. Terminology: In an emphasis string
2669 like \" *strong word* \", we call the initial space PREMATCH, the final
2670 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2671 and \"trong wor\" is the body. The different components in this variable
2672 specify what is allowed/forbidden in each part:
2674 pre Chars allowed as prematch. Beginning of line will be allowed too.
2675 post Chars allowed as postmatch. End of line will be allowed too.
2676 border The chars *forbidden* as border characters.
2677 body-regexp A regexp like \".\" to match a body character. Don't use
2678 non-shy groups here, and don't allow newline here.
2679 newline The maximum number of newlines allowed in an emphasis exp.
2681 Use customize to modify this, or restart Emacs after changing it."
2682 :group 'org-font-lock
2683 :set 'org-set-emph-re
2684 :type '(list
2685 (sexp :tag "Allowed chars in pre ")
2686 (sexp :tag "Allowed chars in post ")
2687 (sexp :tag "Forbidden chars in border ")
2688 (sexp :tag "Regexp for body ")
2689 (integer :tag "number of newlines allowed")
2690 (option (boolean :tag "Please ignore this button"))))
2692 (defcustom org-emphasis-alist
2693 `(("*" bold "<b>" "</b>")
2694 ("/" italic "<i>" "</i>")
2695 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2696 ("=" org-code "<code>" "</code>" verbatim)
2697 ("~" org-verbatim "<code>" "</code>" verbatim)
2698 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2699 "<del>" "</del>")
2701 "Special syntax for emphasized text.
2702 Text starting and ending with a special character will be emphasized, for
2703 example *bold*, _underlined_ and /italic/. This variable sets the marker
2704 characters, the face to be used by font-lock for highlighting in Org-mode
2705 Emacs buffers, and the HTML tags to be used for this.
2706 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2707 Use customize to modify this, or restart Emacs after changing it."
2708 :group 'org-font-lock
2709 :set 'org-set-emph-re
2710 :type '(repeat
2711 (list
2712 (string :tag "Marker character")
2713 (choice
2714 (face :tag "Font-lock-face")
2715 (plist :tag "Face property list"))
2716 (string :tag "HTML start tag")
2717 (string :tag "HTML end tag")
2718 (option (const verbatim)))))
2720 ;;; Miscellaneous options
2722 (defgroup org-completion nil
2723 "Completion in Org-mode."
2724 :tag "Org Completion"
2725 :group 'org)
2727 (defcustom org-completion-use-ido nil
2728 "Non-nil means, use ido completion wherever possible.
2729 Note that `ido-mode' must be active for this variable to be relevant.
2730 If you decide to turn this variable on, you might well want to turn off
2731 `org-outline-path-complete-in-steps'."
2732 :group 'org-completion
2733 :type 'boolean)
2735 (defcustom org-completion-fallback-command 'hippie-expand
2736 "The expansion command called by \\[org-complete] in normal context.
2737 Normal means, no org-mode-specific context."
2738 :group 'org-completion
2739 :type 'function)
2741 ;;; Functions and variables from ther packages
2742 ;; Declared here to avoid compiler warnings
2744 ;; XEmacs only
2745 (defvar outline-mode-menu-heading)
2746 (defvar outline-mode-menu-show)
2747 (defvar outline-mode-menu-hide)
2748 (defvar zmacs-regions) ; XEmacs regions
2750 ;; Emacs only
2751 (defvar mark-active)
2753 ;; Various packages
2754 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2755 (declare-function calendar-forward-day "cal-move" (arg))
2756 (declare-function calendar-goto-date "cal-move" (date))
2757 (declare-function calendar-goto-today "cal-move" ())
2758 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2759 (defvar calc-embedded-close-formula)
2760 (defvar calc-embedded-open-formula)
2761 (declare-function cdlatex-tab "ext:cdlatex" ())
2762 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2763 (defvar font-lock-unfontify-region-function)
2764 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2765 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2766 (defvar iswitchb-temp-buflist)
2767 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2768 (defvar org-agenda-tags-todo-honor-ignore-options)
2769 (declare-function org-agenda-skip "org-agenda" ())
2770 (declare-function org-format-agenda-item "org-agenda"
2771 (extra txt &optional category tags dotime noprefix remove-re))
2772 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2773 (declare-function org-agenda-change-all-lines "org-agenda"
2774 (newhead hdmarker &optional fixface just-this))
2775 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2776 (declare-function org-agenda-maybe-redo "org-agenda" ())
2777 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2778 (beg end))
2779 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2780 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2781 "org-agenda" (&optional end))
2783 (declare-function parse-time-string "parse-time" (string))
2784 (declare-function remember "remember" (&optional initial))
2785 (declare-function remember-buffer-desc "remember" ())
2786 (declare-function remember-finalize "remember" ())
2787 (defvar remember-save-after-remembering)
2788 (defvar remember-data-file)
2789 (defvar remember-register)
2790 (defvar remember-buffer)
2791 (defvar remember-handler-functions)
2792 (defvar remember-annotation-functions)
2793 (defvar texmathp-why)
2794 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2795 (declare-function table--at-cell-p "table" (position &optional object at-column))
2797 (defvar w3m-current-url)
2798 (defvar w3m-current-title)
2800 (defvar org-latex-regexps)
2802 ;;; Autoload and prepare some org modules
2804 ;; Some table stuff that needs to be defined here, because it is used
2805 ;; by the functions setting up org-mode or checking for table context.
2807 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2808 "Detects an org-type or table-type table.")
2809 (defconst org-table-line-regexp "^[ \t]*|"
2810 "Detects an org-type table line.")
2811 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2812 "Detects an org-type table line.")
2813 (defconst org-table-hline-regexp "^[ \t]*|-"
2814 "Detects an org-type table hline.")
2815 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2816 "Detects a table-type table hline.")
2817 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2818 "Searching from within a table (any type) this finds the first line
2819 outside the table.")
2821 ;; Autoload the functions in org-table.el that are needed by functions here.
2823 (eval-and-compile
2824 (org-autoload "org-table"
2825 '(org-table-align org-table-begin org-table-blank-field
2826 org-table-convert org-table-convert-region org-table-copy-down
2827 org-table-copy-region org-table-create
2828 org-table-create-or-convert-from-region
2829 org-table-create-with-table.el org-table-current-dline
2830 org-table-cut-region org-table-delete-column org-table-edit-field
2831 org-table-edit-formulas org-table-end org-table-eval-formula
2832 org-table-export org-table-field-info
2833 org-table-get-stored-formulas org-table-goto-column
2834 org-table-hline-and-move org-table-import org-table-insert-column
2835 org-table-insert-hline org-table-insert-row org-table-iterate
2836 org-table-justify-field-maybe org-table-kill-row
2837 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2838 org-table-move-column org-table-move-column-left
2839 org-table-move-column-right org-table-move-row
2840 org-table-move-row-down org-table-move-row-up
2841 org-table-next-field org-table-next-row org-table-paste-rectangle
2842 org-table-previous-field org-table-recalculate
2843 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2844 org-table-toggle-coordinate-overlays
2845 org-table-toggle-formula-debugger org-table-wrap-region
2846 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2848 (defun org-at-table-p (&optional table-type)
2849 "Return t if the cursor is inside an org-type table.
2850 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2851 (if org-enable-table-editor
2852 (save-excursion
2853 (beginning-of-line 1)
2854 (looking-at (if table-type org-table-any-line-regexp
2855 org-table-line-regexp)))
2856 nil))
2857 (defsubst org-table-p () (org-at-table-p))
2859 (defun org-at-table.el-p ()
2860 "Return t if and only if we are at a table.el table."
2861 (and (org-at-table-p 'any)
2862 (save-excursion
2863 (goto-char (org-table-begin 'any))
2864 (looking-at org-table1-hline-regexp))))
2865 (defun org-table-recognize-table.el ()
2866 "If there is a table.el table nearby, recognize it and move into it."
2867 (if org-table-tab-recognizes-table.el
2868 (if (org-at-table.el-p)
2869 (progn
2870 (beginning-of-line 1)
2871 (if (looking-at org-table-dataline-regexp)
2873 (if (looking-at org-table1-hline-regexp)
2874 (progn
2875 (beginning-of-line 2)
2876 (if (looking-at org-table-any-border-regexp)
2877 (beginning-of-line -1)))))
2878 (if (re-search-forward "|" (org-table-end t) t)
2879 (progn
2880 (require 'table)
2881 (if (table--at-cell-p (point))
2883 (message "recognizing table.el table...")
2884 (table-recognize-table)
2885 (message "recognizing table.el table...done")))
2886 (error "This should not happen..."))
2888 nil)
2889 nil))
2891 (defun org-at-table-hline-p ()
2892 "Return t if the cursor is inside a hline in a table."
2893 (if org-enable-table-editor
2894 (save-excursion
2895 (beginning-of-line 1)
2896 (looking-at org-table-hline-regexp))
2897 nil))
2899 (defvar org-table-clean-did-remove-column nil)
2901 (defun org-table-map-tables (function)
2902 "Apply FUNCTION to the start of all tables in the buffer."
2903 (save-excursion
2904 (save-restriction
2905 (widen)
2906 (goto-char (point-min))
2907 (while (re-search-forward org-table-any-line-regexp nil t)
2908 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2909 (beginning-of-line 1)
2910 (if (looking-at org-table-line-regexp)
2911 (save-excursion (funcall function)))
2912 (re-search-forward org-table-any-border-regexp nil 1))))
2913 (message "Mapping tables: done"))
2915 ;; Declare and autoload functions from org-exp.el & Co
2917 (declare-function org-default-export-plist "org-exp")
2918 (declare-function org-infile-export-plist "org-exp")
2919 (declare-function org-get-current-options "org-exp")
2920 (eval-and-compile
2921 (org-autoload "org-exp"
2922 '(org-export org-export-visible
2923 org-insert-export-options-template
2924 org-table-clean-before-export))
2925 (org-autoload "org-ascii"
2926 '(org-export-as-ascii org-export-ascii-preprocess))
2927 (org-autoload "org-html"
2928 '(org-export-as-html-and-open
2929 org-export-as-html-batch org-export-as-html-to-buffer
2930 org-replace-region-by-html org-export-region-as-html
2931 org-export-as-html))
2932 (org-autoload "org-icalendar"
2933 '(org-export-icalendar-this-file
2934 org-export-icalendar-all-agenda-files
2935 org-export-icalendar-combine-agenda-files))
2936 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
2938 ;; Declare and autoload functions from org-agenda.el
2940 (eval-and-compile
2941 (org-autoload "org-agenda"
2942 '(org-agenda org-agenda-list org-search-view
2943 org-todo-list org-tags-view org-agenda-list-stuck-projects
2944 org-diary org-agenda-to-appt
2945 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2947 ;; Autoload org-remember
2949 (eval-and-compile
2950 (org-autoload "org-remember"
2951 '(org-remember-insinuate org-remember-annotation
2952 org-remember-apply-template org-remember org-remember-handler)))
2954 ;; Autoload org-clock.el
2957 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2958 (beg end))
2959 (declare-function org-clock-update-mode-line "org-clock" ())
2960 (defvar org-clock-start-time)
2961 (defvar org-clock-marker (make-marker)
2962 "Marker recording the last clock-in.")
2964 (eval-and-compile
2965 (org-autoload
2966 "org-clock"
2967 '(org-clock-in org-clock-out org-clock-cancel
2968 org-clock-goto org-clock-sum org-clock-display
2969 org-clock-remove-overlays org-clock-report
2970 org-clocktable-shift org-dblock-write:clocktable
2971 org-get-clocktable)))
2973 (defun org-clock-update-time-maybe ()
2974 "If this is a CLOCK line, update it and return t.
2975 Otherwise, return nil."
2976 (interactive)
2977 (save-excursion
2978 (beginning-of-line 1)
2979 (skip-chars-forward " \t")
2980 (when (looking-at org-clock-string)
2981 (let ((re (concat "[ \t]*" org-clock-string
2982 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2983 "\\([ \t]*=>.*\\)?\\)?"))
2984 ts te h m s neg)
2985 (cond
2986 ((not (looking-at re))
2987 nil)
2988 ((not (match-end 2))
2989 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2990 (> org-clock-marker (point))
2991 (<= org-clock-marker (point-at-eol)))
2992 ;; The clock is running here
2993 (setq org-clock-start-time
2994 (apply 'encode-time
2995 (org-parse-time-string (match-string 1))))
2996 (org-clock-update-mode-line)))
2998 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2999 (end-of-line 1)
3000 (setq ts (match-string 1)
3001 te (match-string 3))
3002 (setq s (- (time-to-seconds
3003 (apply 'encode-time (org-parse-time-string te)))
3004 (time-to-seconds
3005 (apply 'encode-time (org-parse-time-string ts))))
3006 neg (< s 0)
3007 s (abs s)
3008 h (floor (/ s 3600))
3009 s (- s (* 3600 h))
3010 m (floor (/ s 60))
3011 s (- s (* 60 s)))
3012 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3013 t))))))
3015 (defun org-check-running-clock ()
3016 "Check if the current buffer contains the running clock.
3017 If yes, offer to stop it and to save the buffer with the changes."
3018 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3019 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3020 (buffer-name))))
3021 (org-clock-out)
3022 (when (y-or-n-p "Save changed buffer?")
3023 (save-buffer))))
3025 (defun org-clocktable-try-shift (dir n)
3026 "Check if this line starts a clock table, if yes, shift the time block."
3027 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3028 (org-clocktable-shift dir n)))
3030 ;; Autoload org-timer.el
3032 (eval-and-compile
3033 (org-autoload
3034 "org-timer"
3035 '(org-timer-start org-timer org-timer-item
3036 org-timer-change-times-in-region)))
3038 ;; Autoload org-feed.el
3040 (eval-and-compile
3041 (org-autoload
3042 "org-feed"
3043 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3046 ;; Autoload archiving code
3047 ;; The stuff that is needed for cycling and tags has to be defined here.
3049 (defgroup org-archive nil
3050 "Options concerning archiving in Org-mode."
3051 :tag "Org Archive"
3052 :group 'org-structure)
3054 (defcustom org-archive-location "%s_archive::"
3055 "The location where subtrees should be archived.
3057 The value of this variable is a string, consisting of two parts,
3058 separated by a double-colon. The first part is a filename and
3059 the second part is a headline.
3061 When the filename is omitted, archiving happens in the same file.
3062 %s in the filename will be replaced by the current file
3063 name (without the directory part). Archiving to a different file
3064 is useful to keep archived entries from contributing to the
3065 Org-mode Agenda.
3067 The archived entries will be filed as subtrees of the specified
3068 headline. When the headline is omitted, the subtrees are simply
3069 filed away at the end of the file, as top-level entries. Also in
3070 the heading you can use %s to represent the file name, this can be
3071 useful when using the same archive for a number of different files.
3073 Here are a few examples:
3074 \"%s_archive::\"
3075 If the current file is Projects.org, archive in file
3076 Projects.org_archive, as top-level trees. This is the default.
3078 \"::* Archived Tasks\"
3079 Archive in the current file, under the top-level headline
3080 \"* Archived Tasks\".
3082 \"~/org/archive.org::\"
3083 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3085 \"~/org/archive.org::From %s\"
3086 Archive in file ~/org/archive.org (absolute path), und headlines
3087 \"From FILENAME\" where file name is the current file name.
3089 \"basement::** Finished Tasks\"
3090 Archive in file ./basement (relative path), as level 3 trees
3091 below the level 2 heading \"** Finished Tasks\".
3093 You may set this option on a per-file basis by adding to the buffer a
3094 line like
3096 #+ARCHIVE: basement::** Finished Tasks
3098 You may also define it locally for a subtree by setting an ARCHIVE property
3099 in the entry. If such a property is found in an entry, or anywhere up
3100 the hierarchy, it will be used."
3101 :group 'org-archive
3102 :type 'string)
3104 (defcustom org-archive-tag "ARCHIVE"
3105 "The tag that marks a subtree as archived.
3106 An archived subtree does not open during visibility cycling, and does
3107 not contribute to the agenda listings.
3108 After changing this, font-lock must be restarted in the relevant buffers to
3109 get the proper fontification."
3110 :group 'org-archive
3111 :group 'org-keywords
3112 :type 'string)
3114 (defcustom org-agenda-skip-archived-trees t
3115 "Non-nil means, the agenda will skip any items located in archived trees.
3116 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3117 variable is no longer recommended, you should leave it at the value t.
3118 Instead, use the key `v' to cycle the archives-mode in the agenda."
3119 :group 'org-archive
3120 :group 'org-agenda-skip
3121 :type 'boolean)
3123 (defcustom org-columns-skip-arrchived-trees t
3124 "Non-nil means, irgnore archived trees when creating column view."
3125 :group 'org-archive
3126 :group 'org-properties
3127 :type 'boolean)
3129 (defcustom org-cycle-open-archived-trees nil
3130 "Non-nil means, `org-cycle' will open archived trees.
3131 An archived tree is a tree marked with the tag ARCHIVE.
3132 When nil, archived trees will stay folded. You can still open them with
3133 normal outline commands like `show-all', but not with the cycling commands."
3134 :group 'org-archive
3135 :group 'org-cycle
3136 :type 'boolean)
3138 (defcustom org-sparse-tree-open-archived-trees nil
3139 "Non-nil means sparse tree construction shows matches in archived trees.
3140 When nil, matches in these trees are highlighted, but the trees are kept in
3141 collapsed state."
3142 :group 'org-archive
3143 :group 'org-sparse-trees
3144 :type 'boolean)
3146 (defun org-cycle-hide-archived-subtrees (state)
3147 "Re-hide all archived subtrees after a visibility state change."
3148 (when (and (not org-cycle-open-archived-trees)
3149 (not (memq state '(overview folded))))
3150 (save-excursion
3151 (let* ((globalp (memq state '(contents all)))
3152 (beg (if globalp (point-min) (point)))
3153 (end (if globalp (point-max) (org-end-of-subtree t))))
3154 (org-hide-archived-subtrees beg end)
3155 (goto-char beg)
3156 (if (looking-at (concat ".*:" org-archive-tag ":"))
3157 (message "%s" (substitute-command-keys
3158 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3160 (defun org-force-cycle-archived ()
3161 "Cycle subtree even if it is archived."
3162 (interactive)
3163 (setq this-command 'org-cycle)
3164 (let ((org-cycle-open-archived-trees t))
3165 (call-interactively 'org-cycle)))
3167 (defun org-hide-archived-subtrees (beg end)
3168 "Re-hide all archived subtrees after a visibility state change."
3169 (save-excursion
3170 (let* ((re (concat ":" org-archive-tag ":")))
3171 (goto-char beg)
3172 (while (re-search-forward re end t)
3173 (and (org-on-heading-p) (hide-subtree))
3174 (org-end-of-subtree t)))))
3176 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3178 (eval-and-compile
3179 (org-autoload "org-archive"
3180 '(org-add-archive-files org-archive-subtree
3181 org-archive-to-archive-sibling org-toggle-archive-tag)))
3183 ;; Autoload Column View Code
3185 (declare-function org-columns-number-to-string "org-colview")
3186 (declare-function org-columns-get-format-and-top-level "org-colview")
3187 (declare-function org-columns-compute "org-colview")
3189 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3190 '(org-columns-number-to-string org-columns-get-format-and-top-level
3191 org-columns-compute org-agenda-columns org-columns-remove-overlays
3192 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3194 ;; Autoload ID code
3196 (declare-function org-id-store-link "org-id")
3197 (declare-function org-id-locations-load "org-id")
3198 (declare-function org-id-locations-save "org-id")
3199 (defvar org-id-track-globally)
3200 (org-autoload "org-id"
3201 '(org-id-get-create org-id-new org-id-copy org-id-get
3202 org-id-get-with-outline-path-completion
3203 org-id-get-with-outline-drilling
3204 org-id-goto org-id-find org-id-store-link))
3206 ;; Autoload Plotting Code
3208 (org-autoload "org-plot"
3209 '(org-plot/gnuplot))
3211 ;;; Variables for pre-computed regular expressions, all buffer local
3213 (defvar org-drawer-regexp nil
3214 "Matches first line of a hidden block.")
3215 (make-variable-buffer-local 'org-drawer-regexp)
3216 (defvar org-todo-regexp nil
3217 "Matches any of the TODO state keywords.")
3218 (make-variable-buffer-local 'org-todo-regexp)
3219 (defvar org-not-done-regexp nil
3220 "Matches any of the TODO state keywords except the last one.")
3221 (make-variable-buffer-local 'org-not-done-regexp)
3222 (defvar org-not-done-heading-regexp nil
3223 "Matches a TODO headline that is not done.")
3224 (make-variable-buffer-local 'org-not-done-regexp)
3225 (defvar org-todo-line-regexp nil
3226 "Matches a headline and puts TODO state into group 2 if present.")
3227 (make-variable-buffer-local 'org-todo-line-regexp)
3228 (defvar org-complex-heading-regexp nil
3229 "Matches a headline and puts everything into groups:
3230 group 1: the stars
3231 group 2: The todo keyword, maybe
3232 group 3: Priority cookie
3233 group 4: True headline
3234 group 5: Tags")
3235 (make-variable-buffer-local 'org-complex-heading-regexp)
3236 (defvar org-todo-line-tags-regexp nil
3237 "Matches a headline and puts TODO state into group 2 if present.
3238 Also put tags into group 4 if tags are present.")
3239 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3240 (defvar org-nl-done-regexp nil
3241 "Matches newline followed by a headline with the DONE keyword.")
3242 (make-variable-buffer-local 'org-nl-done-regexp)
3243 (defvar org-looking-at-done-regexp nil
3244 "Matches the DONE keyword a point.")
3245 (make-variable-buffer-local 'org-looking-at-done-regexp)
3246 (defvar org-ds-keyword-length 12
3247 "Maximum length of the Deadline and SCHEDULED keywords.")
3248 (make-variable-buffer-local 'org-ds-keyword-length)
3249 (defvar org-deadline-regexp nil
3250 "Matches the DEADLINE keyword.")
3251 (make-variable-buffer-local 'org-deadline-regexp)
3252 (defvar org-deadline-time-regexp nil
3253 "Matches the DEADLINE keyword together with a time stamp.")
3254 (make-variable-buffer-local 'org-deadline-time-regexp)
3255 (defvar org-deadline-line-regexp nil
3256 "Matches the DEADLINE keyword and the rest of the line.")
3257 (make-variable-buffer-local 'org-deadline-line-regexp)
3258 (defvar org-scheduled-regexp nil
3259 "Matches the SCHEDULED keyword.")
3260 (make-variable-buffer-local 'org-scheduled-regexp)
3261 (defvar org-scheduled-time-regexp nil
3262 "Matches the SCHEDULED keyword together with a time stamp.")
3263 (make-variable-buffer-local 'org-scheduled-time-regexp)
3264 (defvar org-closed-time-regexp nil
3265 "Matches the CLOSED keyword together with a time stamp.")
3266 (make-variable-buffer-local 'org-closed-time-regexp)
3268 (defvar org-keyword-time-regexp nil
3269 "Matches any of the 4 keywords, together with the time stamp.")
3270 (make-variable-buffer-local 'org-keyword-time-regexp)
3271 (defvar org-keyword-time-not-clock-regexp nil
3272 "Matches any of the 3 keywords, together with the time stamp.")
3273 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3274 (defvar org-maybe-keyword-time-regexp nil
3275 "Matches a timestamp, possibly preceeded by a keyword.")
3276 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3277 (defvar org-planning-or-clock-line-re nil
3278 "Matches a line with planning or clock info.")
3279 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3281 (defconst org-plain-time-of-day-regexp
3282 (concat
3283 "\\(\\<[012]?[0-9]"
3284 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3285 "\\(--?"
3286 "\\(\\<[012]?[0-9]"
3287 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3288 "\\)?")
3289 "Regular expression to match a plain time or time range.
3290 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3291 groups carry important information:
3292 0 the full match
3293 1 the first time, range or not
3294 8 the second time, if it is a range.")
3296 (defconst org-plain-time-extension-regexp
3297 (concat
3298 "\\(\\<[012]?[0-9]"
3299 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3300 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3301 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3302 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3303 groups carry important information:
3304 0 the full match
3305 7 hours of duration
3306 9 minutes of duration")
3308 (defconst org-stamp-time-of-day-regexp
3309 (concat
3310 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3311 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3312 "\\(--?"
3313 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3314 "Regular expression to match a timestamp time or time range.
3315 After a match, the following groups carry important information:
3316 0 the full match
3317 1 date plus weekday, for backreferencing to make sure both times on same day
3318 2 the first time, range or not
3319 4 the second time, if it is a range.")
3321 (defconst org-startup-options
3322 '(("fold" org-startup-folded t)
3323 ("overview" org-startup-folded t)
3324 ("nofold" org-startup-folded nil)
3325 ("showall" org-startup-folded nil)
3326 ("content" org-startup-folded content)
3327 ("hidestars" org-hide-leading-stars t)
3328 ("showstars" org-hide-leading-stars nil)
3329 ("odd" org-odd-levels-only t)
3330 ("oddeven" org-odd-levels-only nil)
3331 ("align" org-startup-align-all-tables t)
3332 ("noalign" org-startup-align-all-tables nil)
3333 ("customtime" org-display-custom-times t)
3334 ("logdone" org-log-done time)
3335 ("lognotedone" org-log-done note)
3336 ("nologdone" org-log-done nil)
3337 ("lognoteclock-out" org-log-note-clock-out t)
3338 ("nolognoteclock-out" org-log-note-clock-out nil)
3339 ("logrepeat" org-log-repeat state)
3340 ("lognoterepeat" org-log-repeat note)
3341 ("nologrepeat" org-log-repeat nil)
3342 ("fninline" org-footnote-define-inline t)
3343 ("nofninline" org-footnote-define-inline nil)
3344 ("fnlocal" org-footnote-section nil)
3345 ("fnauto" org-footnote-auto-label t)
3346 ("fnprompt" org-footnote-auto-label nil)
3347 ("fnconfirm" org-footnote-auto-label confirm)
3348 ("fnplain" org-footnote-auto-label plain)
3349 ("constcgs" constants-unit-system cgs)
3350 ("constSI" constants-unit-system SI)
3351 ("noptag" org-tag-persistent-alist nil))
3352 "Variable associated with STARTUP options for org-mode.
3353 Each element is a list of three items: The startup options as written
3354 in the #+STARTUP line, the corresponding variable, and the value to
3355 set this variable to if the option is found. An optional forth element PUSH
3356 means to push this value onto the list in the variable.")
3358 (defun org-set-regexps-and-options ()
3359 "Precompute regular expressions for current buffer."
3360 (when (org-mode-p)
3361 (org-set-local 'org-todo-kwd-alist nil)
3362 (org-set-local 'org-todo-key-alist nil)
3363 (org-set-local 'org-todo-key-trigger nil)
3364 (org-set-local 'org-todo-keywords-1 nil)
3365 (org-set-local 'org-done-keywords nil)
3366 (org-set-local 'org-todo-heads nil)
3367 (org-set-local 'org-todo-sets nil)
3368 (org-set-local 'org-todo-log-states nil)
3369 (org-set-local 'org-file-properties nil)
3370 (org-set-local 'org-file-tags nil)
3371 (let ((re (org-make-options-regexp
3372 '("CATEGORY" "TODO" "COLUMNS"
3373 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3374 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3375 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3376 (splitre "[ \t]+")
3377 kwds kws0 kwsa key log value cat arch tags const links hw dws
3378 tail sep kws1 prio props ftags drawers
3379 ext-setup-or-nil setup-contents (start 0))
3380 (save-excursion
3381 (save-restriction
3382 (widen)
3383 (goto-char (point-min))
3384 (while (or (and ext-setup-or-nil
3385 (string-match re ext-setup-or-nil start)
3386 (setq start (match-end 0)))
3387 (and (setq ext-setup-or-nil nil start 0)
3388 (re-search-forward re nil t)))
3389 (setq key (upcase (match-string 1 ext-setup-or-nil))
3390 value (org-match-string-no-properties 2 ext-setup-or-nil))
3391 (cond
3392 ((equal key "CATEGORY")
3393 (if (string-match "[ \t]+$" value)
3394 (setq value (replace-match "" t t value)))
3395 (setq cat value))
3396 ((member key '("SEQ_TODO" "TODO"))
3397 (push (cons 'sequence (org-split-string value splitre)) kwds))
3398 ((equal key "TYP_TODO")
3399 (push (cons 'type (org-split-string value splitre)) kwds))
3400 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3401 ;; general TODO-like setup
3402 (push (cons (intern (downcase (match-string 1 key)))
3403 (org-split-string value splitre)) kwds))
3404 ((equal key "TAGS")
3405 (setq tags (append tags (if tags '("\\n") nil)
3406 (org-split-string value splitre))))
3407 ((equal key "COLUMNS")
3408 (org-set-local 'org-columns-default-format value))
3409 ((equal key "LINK")
3410 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3411 (push (cons (match-string 1 value)
3412 (org-trim (match-string 2 value)))
3413 links)))
3414 ((equal key "PRIORITIES")
3415 (setq prio (org-split-string value " +")))
3416 ((equal key "PROPERTY")
3417 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3418 (push (cons (match-string 1 value) (match-string 2 value))
3419 props)))
3420 ((equal key "FILETAGS")
3421 (when (string-match "\\S-" value)
3422 (setq ftags
3423 (append
3424 ftags
3425 (apply 'append
3426 (mapcar (lambda (x) (org-split-string x ":"))
3427 (org-split-string value)))))))
3428 ((equal key "DRAWERS")
3429 (setq drawers (org-split-string value splitre)))
3430 ((equal key "CONSTANTS")
3431 (setq const (append const (org-split-string value splitre))))
3432 ((equal key "STARTUP")
3433 (let ((opts (org-split-string value splitre))
3434 l var val)
3435 (while (setq l (pop opts))
3436 (when (setq l (assoc l org-startup-options))
3437 (setq var (nth 1 l) val (nth 2 l))
3438 (if (not (nth 3 l))
3439 (set (make-local-variable var) val)
3440 (if (not (listp (symbol-value var)))
3441 (set (make-local-variable var) nil))
3442 (set (make-local-variable var) (symbol-value var))
3443 (add-to-list var val))))))
3444 ((equal key "ARCHIVE")
3445 (string-match " *$" value)
3446 (setq arch (replace-match "" t t value))
3447 (remove-text-properties 0 (length arch)
3448 '(face t fontified t) arch))
3449 ((equal key "SETUPFILE")
3450 (setq setup-contents (org-file-contents
3451 (expand-file-name
3452 (org-remove-double-quotes value))
3453 'noerror))
3454 (if (not ext-setup-or-nil)
3455 (setq ext-setup-or-nil setup-contents start 0)
3456 (setq ext-setup-or-nil
3457 (concat (substring ext-setup-or-nil 0 start)
3458 "\n" setup-contents "\n"
3459 (substring ext-setup-or-nil start)))))
3460 ))))
3461 (when cat
3462 (org-set-local 'org-category (intern cat))
3463 (push (cons "CATEGORY" cat) props))
3464 (when prio
3465 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3466 (setq prio (mapcar 'string-to-char prio))
3467 (org-set-local 'org-highest-priority (nth 0 prio))
3468 (org-set-local 'org-lowest-priority (nth 1 prio))
3469 (org-set-local 'org-default-priority (nth 2 prio)))
3470 (and props (org-set-local 'org-file-properties (nreverse props)))
3471 (and ftags (org-set-local 'org-file-tags
3472 (mapcar 'org-add-prop-inherited ftags)))
3473 (and drawers (org-set-local 'org-drawers drawers))
3474 (and arch (org-set-local 'org-archive-location arch))
3475 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3476 ;; Process the TODO keywords
3477 (unless kwds
3478 ;; Use the global values as if they had been given locally.
3479 (setq kwds (default-value 'org-todo-keywords))
3480 (if (stringp (car kwds))
3481 (setq kwds (list (cons org-todo-interpretation
3482 (default-value 'org-todo-keywords)))))
3483 (setq kwds (reverse kwds)))
3484 (setq kwds (nreverse kwds))
3485 (let (inter kws kw)
3486 (while (setq kws (pop kwds))
3487 (let ((kws (or
3488 (run-hook-with-args-until-success
3489 'org-todo-setup-filter-hook kws)
3490 kws)))
3491 (setq inter (pop kws) sep (member "|" kws)
3492 kws0 (delete "|" (copy-sequence kws))
3493 kwsa nil
3494 kws1 (mapcar
3495 (lambda (x)
3496 ;; 1 2
3497 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3498 (progn
3499 (setq kw (match-string 1 x)
3500 key (and (match-end 2) (match-string 2 x))
3501 log (org-extract-log-state-settings x))
3502 (push (cons kw (and key (string-to-char key))) kwsa)
3503 (and log (push log org-todo-log-states))
3505 (error "Invalid TODO keyword %s" x)))
3506 kws0)
3507 kwsa (if kwsa (append '((:startgroup))
3508 (nreverse kwsa)
3509 '((:endgroup))))
3510 hw (car kws1)
3511 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3512 tail (list inter hw (car dws) (org-last dws))))
3513 (add-to-list 'org-todo-heads hw 'append)
3514 (push kws1 org-todo-sets)
3515 (setq org-done-keywords (append org-done-keywords dws nil))
3516 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3517 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3518 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3519 (setq org-todo-sets (nreverse org-todo-sets)
3520 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3521 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3522 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3523 ;; Process the constants
3524 (when const
3525 (let (e cst)
3526 (while (setq e (pop const))
3527 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3528 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3529 (setq org-table-formula-constants-local cst)))
3531 ;; Process the tags.
3532 (when tags
3533 (let (e tgs)
3534 (while (setq e (pop tags))
3535 (cond
3536 ((equal e "{") (push '(:startgroup) tgs))
3537 ((equal e "}") (push '(:endgroup) tgs))
3538 ((equal e "\\n") (push '(:newline) tgs))
3539 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3540 (push (cons (match-string 1 e)
3541 (string-to-char (match-string 2 e)))
3542 tgs))
3543 (t (push (list e) tgs))))
3544 (org-set-local 'org-tag-alist nil)
3545 (while (setq e (pop tgs))
3546 (or (and (stringp (car e))
3547 (assoc (car e) org-tag-alist))
3548 (push e org-tag-alist)))))
3550 ;; Compute the regular expressions and other local variables
3551 (if (not org-done-keywords)
3552 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3553 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3554 (length org-scheduled-string)
3555 (length org-clock-string)
3556 (length org-closed-string)))
3557 org-drawer-regexp
3558 (concat "^[ \t]*:\\("
3559 (mapconcat 'regexp-quote org-drawers "\\|")
3560 "\\):[ \t]*$")
3561 org-not-done-keywords
3562 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3563 org-todo-regexp
3564 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3565 "\\|") "\\)\\>")
3566 org-not-done-regexp
3567 (concat "\\<\\("
3568 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3569 "\\)\\>")
3570 org-not-done-heading-regexp
3571 (concat "^\\(\\*+\\)[ \t]+\\("
3572 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3573 "\\)\\>")
3574 org-todo-line-regexp
3575 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3576 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3577 "\\)\\>\\)?[ \t]*\\(.*\\)")
3578 org-complex-heading-regexp
3579 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3580 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3581 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3582 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3583 org-nl-done-regexp
3584 (concat "\n\\*+[ \t]+"
3585 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3586 "\\)" "\\>")
3587 org-todo-line-tags-regexp
3588 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3589 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3590 (org-re
3591 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3592 org-looking-at-done-regexp
3593 (concat "^" "\\(?:"
3594 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3595 "\\>")
3596 org-deadline-regexp (concat "\\<" org-deadline-string)
3597 org-deadline-time-regexp
3598 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3599 org-deadline-line-regexp
3600 (concat "\\<\\(" org-deadline-string "\\).*")
3601 org-scheduled-regexp
3602 (concat "\\<" org-scheduled-string)
3603 org-scheduled-time-regexp
3604 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3605 org-closed-time-regexp
3606 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3607 org-keyword-time-regexp
3608 (concat "\\<\\(" org-scheduled-string
3609 "\\|" org-deadline-string
3610 "\\|" org-closed-string
3611 "\\|" org-clock-string "\\)"
3612 " *[[<]\\([^]>]+\\)[]>]")
3613 org-keyword-time-not-clock-regexp
3614 (concat "\\<\\(" org-scheduled-string
3615 "\\|" org-deadline-string
3616 "\\|" org-closed-string
3617 "\\)"
3618 " *[[<]\\([^]>]+\\)[]>]")
3619 org-maybe-keyword-time-regexp
3620 (concat "\\(\\<\\(" org-scheduled-string
3621 "\\|" org-deadline-string
3622 "\\|" org-closed-string
3623 "\\|" org-clock-string "\\)\\)?"
3624 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3625 org-planning-or-clock-line-re
3626 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3627 "\\|" org-deadline-string
3628 "\\|" org-closed-string "\\|" org-clock-string
3629 "\\)\\>\\)")
3631 (org-compute-latex-and-specials-regexp)
3632 (org-set-font-lock-defaults))))
3634 (defun org-file-contents (file &optional noerror)
3635 "Return the contents of FILE, as a string."
3636 (if (or (not file)
3637 (not (file-readable-p file)))
3638 (if noerror
3639 (progn
3640 (message "Cannot read file %s" file)
3641 (ding) (sit-for 2)
3643 (error "Cannot read file %s" file))
3644 (with-temp-buffer
3645 (insert-file-contents file)
3646 (buffer-string))))
3648 (defun org-extract-log-state-settings (x)
3649 "Extract the log state setting from a TODO keyword string.
3650 This will extract info from a string like \"WAIT(w@/!)\"."
3651 (let (kw key log1 log2)
3652 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3653 (setq kw (match-string 1 x)
3654 key (and (match-end 2) (match-string 2 x))
3655 log1 (and (match-end 3) (match-string 3 x))
3656 log2 (and (match-end 4) (match-string 4 x)))
3657 (and (or log1 log2)
3658 (list kw
3659 (and log1 (if (equal log1 "!") 'time 'note))
3660 (and log2 (if (equal log2 "!") 'time 'note)))))))
3662 (defun org-remove-keyword-keys (list)
3663 "Remove a pair of parenthesis at the end of each string in LIST."
3664 (mapcar (lambda (x)
3665 (if (string-match "(.*)$" x)
3666 (substring x 0 (match-beginning 0))
3668 list))
3670 ;; FIXME: this could be done much better, using second characters etc.
3671 (defun org-assign-fast-keys (alist)
3672 "Assign fast keys to a keyword-key alist.
3673 Respect keys that are already there."
3674 (let (new e k c c1 c2 (char ?a))
3675 (while (setq e (pop alist))
3676 (cond
3677 ((equal e '(:startgroup)) (push e new))
3678 ((equal e '(:endgroup)) (push e new))
3679 ((equal e '(:newline)) (push e new))
3681 (setq k (car e) c2 nil)
3682 (if (cdr e)
3683 (setq c (cdr e))
3684 ;; automatically assign a character.
3685 (setq c1 (string-to-char
3686 (downcase (substring
3687 k (if (= (string-to-char k) ?@) 1 0)))))
3688 (if (or (rassoc c1 new) (rassoc c1 alist))
3689 (while (or (rassoc char new) (rassoc char alist))
3690 (setq char (1+ char)))
3691 (setq c2 c1))
3692 (setq c (or c2 char)))
3693 (push (cons k c) new))))
3694 (nreverse new)))
3696 ;;; Some variables used in various places
3698 (defvar org-window-configuration nil
3699 "Used in various places to store a window configuration.")
3700 (defvar org-finish-function nil
3701 "Function to be called when `C-c C-c' is used.
3702 This is for getting out of special buffers like remember.")
3705 ;; FIXME: Occasionally check by commenting these, to make sure
3706 ;; no other functions uses these, forgetting to let-bind them.
3707 (defvar entry)
3708 (defvar state)
3709 (defvar last-state)
3710 (defvar date)
3711 (defvar description)
3713 ;; Defined somewhere in this file, but used before definition.
3714 (defvar org-html-entities)
3715 (defvar org-struct-menu)
3716 (defvar org-org-menu)
3717 (defvar org-tbl-menu)
3718 (defvar org-agenda-keymap)
3720 ;;;; Define the Org-mode
3722 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3723 (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."))
3726 ;; We use a before-change function to check if a table might need
3727 ;; an update.
3728 (defvar org-table-may-need-update t
3729 "Indicates that a table might need an update.
3730 This variable is set by `org-before-change-function'.
3731 `org-table-align' sets it back to nil.")
3732 (defun org-before-change-function (beg end)
3733 "Every change indicates that a table might need an update."
3734 (setq org-table-may-need-update t))
3735 (defvar org-mode-map)
3736 (defvar org-mode-hook nil
3737 "Mode hook for Org-mode, run after the mode was turned on.")
3738 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3739 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3740 (defvar org-table-buffer-is-an nil)
3741 (defconst org-outline-regexp "\\*+ ")
3743 ;;;###autoload
3744 (define-derived-mode org-mode outline-mode "Org"
3745 "Outline-based notes management and organizer, alias
3746 \"Carsten's outline-mode for keeping track of everything.\"
3748 Org-mode develops organizational tasks around a NOTES file which
3749 contains information about projects as plain text. Org-mode is
3750 implemented on top of outline-mode, which is ideal to keep the content
3751 of large files well structured. It supports ToDo items, deadlines and
3752 time stamps, which magically appear in the diary listing of the Emacs
3753 calendar. Tables are easily created with a built-in table editor.
3754 Plain text URL-like links connect to websites, emails (VM), Usenet
3755 messages (Gnus), BBDB entries, and any files related to the project.
3756 For printing and sharing of notes, an Org-mode file (or a part of it)
3757 can be exported as a structured ASCII or HTML file.
3759 The following commands are available:
3761 \\{org-mode-map}"
3763 ;; Get rid of Outline menus, they are not needed
3764 ;; Need to do this here because define-derived-mode sets up
3765 ;; the keymap so late. Still, it is a waste to call this each time
3766 ;; we switch another buffer into org-mode.
3767 (if (featurep 'xemacs)
3768 (when (boundp 'outline-mode-menu-heading)
3769 ;; Assume this is Greg's port, it used easymenu
3770 (easy-menu-remove outline-mode-menu-heading)
3771 (easy-menu-remove outline-mode-menu-show)
3772 (easy-menu-remove outline-mode-menu-hide))
3773 (define-key org-mode-map [menu-bar headings] 'undefined)
3774 (define-key org-mode-map [menu-bar hide] 'undefined)
3775 (define-key org-mode-map [menu-bar show] 'undefined))
3777 (org-load-modules-maybe)
3778 (easy-menu-add org-org-menu)
3779 (easy-menu-add org-tbl-menu)
3780 (org-install-agenda-files-menu)
3781 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3782 (org-add-to-invisibility-spec '(org-cwidth))
3783 (when (featurep 'xemacs)
3784 (org-set-local 'line-move-ignore-invisible t))
3785 (org-set-local 'outline-regexp org-outline-regexp)
3786 (org-set-local 'outline-level 'org-outline-level)
3787 (when (and org-ellipsis
3788 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3789 (fboundp 'make-glyph-code))
3790 (unless org-display-table
3791 (setq org-display-table (make-display-table)))
3792 (set-display-table-slot
3793 org-display-table 4
3794 (vconcat (mapcar
3795 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3796 org-ellipsis)))
3797 (if (stringp org-ellipsis) org-ellipsis "..."))))
3798 (setq buffer-display-table org-display-table))
3799 (org-set-regexps-and-options)
3800 (when (and org-tag-faces (not org-tags-special-faces-re))
3801 ;; tag faces set outside customize.... force initialization.
3802 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3803 ;; Calc embedded
3804 (org-set-local 'calc-embedded-open-mode "# ")
3805 (modify-syntax-entry ?# "<")
3806 (modify-syntax-entry ?@ "w")
3807 (if org-startup-truncated (setq truncate-lines t))
3808 (org-set-local 'font-lock-unfontify-region-function
3809 'org-unfontify-region)
3810 ;; Activate before-change-function
3811 (org-set-local 'org-table-may-need-update t)
3812 (org-add-hook 'before-change-functions 'org-before-change-function nil
3813 'local)
3814 ;; Check for running clock before killing a buffer
3815 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3816 ;; Paragraphs and auto-filling
3817 (org-set-autofill-regexps)
3818 (setq indent-line-function 'org-indent-line-function)
3819 (org-update-radio-target-regexp)
3820 ;; Make sure dependence stuff works reliably, even for users who set it
3821 ;; too late :-(
3822 (if org-enforce-todo-dependencies
3823 (add-hook 'org-blocker-hook
3824 'org-block-todo-from-children-or-siblings-or-parent)
3825 (remove-hook 'org-blocker-hook
3826 'org-block-todo-from-children-or-siblings-or-parent))
3827 (if org-enforce-todo-checkbox-dependencies
3828 (add-hook 'org-blocker-hook
3829 'org-block-todo-from-checkboxes)
3830 (remove-hook 'org-blocker-hook
3831 'org-block-todo-from-checkboxes))
3833 ;; Comment characters
3834 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3835 (org-set-local 'comment-padding " ")
3837 ;; Align options lines
3838 (org-set-local
3839 'align-mode-rules-list
3840 '((org-in-buffer-settings
3841 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3842 (modes . '(org-mode)))))
3844 ;; Imenu
3845 (org-set-local 'imenu-create-index-function
3846 'org-imenu-get-tree)
3848 ;; Make isearch reveal context
3849 (if (or (featurep 'xemacs)
3850 (not (boundp 'outline-isearch-open-invisible-function)))
3851 ;; Emacs 21 and XEmacs make use of the hook
3852 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3853 ;; Emacs 22 deals with this through a special variable
3854 (org-set-local 'outline-isearch-open-invisible-function
3855 (lambda (&rest ignore) (org-show-context 'isearch))))
3857 ;; If empty file that did not turn on org-mode automatically, make it to.
3858 (if (and org-insert-mode-line-in-empty-file
3859 (interactive-p)
3860 (= (point-min) (point-max)))
3861 (insert "# -*- mode: org -*-\n\n"))
3863 (unless org-inhibit-startup
3864 (when org-startup-align-all-tables
3865 (let ((bmp (buffer-modified-p)))
3866 (org-table-map-tables 'org-table-align)
3867 (set-buffer-modified-p bmp)))
3868 (org-set-startup-visibility)))
3870 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3872 (defun org-current-time ()
3873 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3874 (if (> (car org-time-stamp-rounding-minutes) 1)
3875 (let ((r (car org-time-stamp-rounding-minutes))
3876 (time (decode-time)))
3877 (apply 'encode-time
3878 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3879 (nthcdr 2 time))))
3880 (current-time)))
3882 ;;;; Font-Lock stuff, including the activators
3884 (defvar org-mouse-map (make-sparse-keymap))
3885 (org-defkey org-mouse-map
3886 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3887 (org-defkey org-mouse-map
3888 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3889 (when org-mouse-1-follows-link
3890 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3891 (when org-tab-follows-link
3892 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3893 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3895 (require 'font-lock)
3897 (defconst org-non-link-chars "]\t\n\r<>")
3898 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3899 "shell" "elisp"))
3900 (defvar org-link-types-re nil
3901 "Matches a link that has a url-like prefix like \"http:\"")
3902 (defvar org-link-re-with-space nil
3903 "Matches a link with spaces, optional angular brackets around it.")
3904 (defvar org-link-re-with-space2 nil
3905 "Matches a link with spaces, optional angular brackets around it.")
3906 (defvar org-link-re-with-space3 nil
3907 "Matches a link with spaces, only for internal part in bracket links.")
3908 (defvar org-angle-link-re nil
3909 "Matches link with angular brackets, spaces are allowed.")
3910 (defvar org-plain-link-re nil
3911 "Matches plain link, without spaces.")
3912 (defvar org-bracket-link-regexp nil
3913 "Matches a link in double brackets.")
3914 (defvar org-bracket-link-analytic-regexp nil
3915 "Regular expression used to analyze links.
3916 Here is what the match groups contain after a match:
3917 1: http:
3918 2: http
3919 3: path
3920 4: [desc]
3921 5: desc")
3922 (defvar org-bracket-link-analytic-regexp++ nil
3923 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3924 (defvar org-any-link-re nil
3925 "Regular expression matching any link.")
3927 (defun org-make-link-regexps ()
3928 "Update the link regular expressions.
3929 This should be called after the variable `org-link-types' has changed."
3930 (setq org-link-types-re
3931 (concat
3932 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3933 org-link-re-with-space
3934 (concat
3935 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3936 "\\([^" org-non-link-chars " ]"
3937 "[^" org-non-link-chars "]*"
3938 "[^" org-non-link-chars " ]\\)>?")
3939 org-link-re-with-space2
3940 (concat
3941 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3942 "\\([^" org-non-link-chars " ]"
3943 "[^\t\n\r]*"
3944 "[^" org-non-link-chars " ]\\)>?")
3945 org-link-re-with-space3
3946 (concat
3947 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3948 "\\([^" org-non-link-chars " ]"
3949 "[^\t\n\r]*\\)")
3950 org-angle-link-re
3951 (concat
3952 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3953 "\\([^" org-non-link-chars " ]"
3954 "[^" org-non-link-chars "]*"
3955 "\\)>")
3956 org-plain-link-re
3957 (concat
3958 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3959 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3960 org-bracket-link-regexp
3961 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3962 org-bracket-link-analytic-regexp
3963 (concat
3964 "\\[\\["
3965 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3966 "\\([^]]+\\)"
3967 "\\]"
3968 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3969 "\\]")
3970 org-bracket-link-analytic-regexp++
3971 (concat
3972 "\\[\\["
3973 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3974 "\\([^]]+\\)"
3975 "\\]"
3976 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3977 "\\]")
3978 org-any-link-re
3979 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3980 org-angle-link-re "\\)\\|\\("
3981 org-plain-link-re "\\)")))
3983 (org-make-link-regexps)
3985 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3986 "Regular expression for fast time stamp matching.")
3987 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3988 "Regular expression for fast time stamp matching.")
3989 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3990 "Regular expression matching time strings for analysis.
3991 This one does not require the space after the date, so it can be used
3992 on a string that terminates immediately after the date.")
3993 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3994 "Regular expression matching time strings for analysis.")
3995 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3996 "Regular expression matching time stamps, with groups.")
3997 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3998 "Regular expression matching time stamps (also [..]), with groups.")
3999 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4000 "Regular expression matching a time stamp range.")
4001 (defconst org-tr-regexp-both
4002 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4003 "Regular expression matching a time stamp range.")
4004 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4005 org-ts-regexp "\\)?")
4006 "Regular expression matching a time stamp or time stamp range.")
4007 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4008 org-ts-regexp-both "\\)?")
4009 "Regular expression matching a time stamp or time stamp range.
4010 The time stamps may be either active or inactive.")
4012 (defvar org-emph-face nil)
4014 (defun org-do-emphasis-faces (limit)
4015 "Run through the buffer and add overlays to links."
4016 (let (rtn)
4017 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4018 (if (not (= (char-after (match-beginning 3))
4019 (char-after (match-beginning 4))))
4020 (progn
4021 (setq rtn t)
4022 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4023 'face
4024 (nth 1 (assoc (match-string 3)
4025 org-emphasis-alist)))
4026 (add-text-properties (match-beginning 2) (match-end 2)
4027 '(font-lock-multiline t))
4028 (when org-hide-emphasis-markers
4029 (add-text-properties (match-end 4) (match-beginning 5)
4030 '(invisible org-link))
4031 (add-text-properties (match-beginning 3) (match-end 3)
4032 '(invisible org-link)))))
4033 (backward-char 1))
4034 rtn))
4036 (defun org-emphasize (&optional char)
4037 "Insert or change an emphasis, i.e. a font like bold or italic.
4038 If there is an active region, change that region to a new emphasis.
4039 If there is no region, just insert the marker characters and position
4040 the cursor between them.
4041 CHAR should be either the marker character, or the first character of the
4042 HTML tag associated with that emphasis. If CHAR is a space, the means
4043 to remove the emphasis of the selected region.
4044 If char is not given (for example in an interactive call) it
4045 will be prompted for."
4046 (interactive)
4047 (let ((eal org-emphasis-alist) e det
4048 (erc org-emphasis-regexp-components)
4049 (prompt "")
4050 (string "") beg end move tag c s)
4051 (if (org-region-active-p)
4052 (setq beg (region-beginning) end (region-end)
4053 string (buffer-substring beg end))
4054 (setq move t))
4056 (while (setq e (pop eal))
4057 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4058 c (aref tag 0))
4059 (push (cons c (string-to-char (car e))) det)
4060 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4061 (substring tag 1)))))
4062 (setq det (nreverse det))
4063 (unless char
4064 (message "%s" (concat "Emphasis marker or tag:" prompt))
4065 (setq char (read-char-exclusive)))
4066 (setq char (or (cdr (assoc char det)) char))
4067 (if (equal char ?\ )
4068 (setq s "" move nil)
4069 (unless (assoc (char-to-string char) org-emphasis-alist)
4070 (error "No such emphasis marker: \"%c\"" char))
4071 (setq s (char-to-string char)))
4072 (while (and (> (length string) 1)
4073 (equal (substring string 0 1) (substring string -1))
4074 (assoc (substring string 0 1) org-emphasis-alist))
4075 (setq string (substring string 1 -1)))
4076 (setq string (concat s string s))
4077 (if beg (delete-region beg end))
4078 (unless (or (bolp)
4079 (string-match (concat "[" (nth 0 erc) "\n]")
4080 (char-to-string (char-before (point)))))
4081 (insert " "))
4082 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4083 (char-to-string (char-after (point))))
4084 (insert " ") (backward-char 1))
4085 (insert string)
4086 (and move (backward-char 1))))
4088 (defconst org-nonsticky-props
4089 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4092 (defun org-activate-plain-links (limit)
4093 "Run through the buffer and add overlays to links."
4094 (catch 'exit
4095 (let (f)
4096 (while (re-search-forward org-plain-link-re limit t)
4097 (setq f (get-text-property (match-beginning 0) 'face))
4098 (if (or (eq f 'org-tag)
4099 (and (listp f) (memq 'org-tag f)))
4101 (add-text-properties (match-beginning 0) (match-end 0)
4102 (list 'mouse-face 'highlight
4103 'rear-nonsticky org-nonsticky-props
4104 'keymap org-mouse-map
4106 (throw 'exit t))))))
4108 (defun org-activate-code (limit)
4109 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4110 (progn
4111 (remove-text-properties (match-beginning 0) (match-end 0)
4112 '(display t invisible t intangible t))
4113 t)))
4115 (defun org-activate-angle-links (limit)
4116 "Run through the buffer and add overlays to links."
4117 (if (re-search-forward org-angle-link-re limit t)
4118 (progn
4119 (add-text-properties (match-beginning 0) (match-end 0)
4120 (list 'mouse-face 'highlight
4121 'rear-nonsticky org-nonsticky-props
4122 'keymap org-mouse-map
4124 t)))
4126 (defun org-activate-footnote-links (limit)
4127 "Run through the buffer and add overlays to links."
4128 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4129 limit t)
4130 (progn
4131 (add-text-properties (match-beginning 2) (match-end 2)
4132 (list 'mouse-face 'highlight
4133 'rear-nonsticky org-nonsticky-props
4134 'keymap org-mouse-map
4135 'help-echo
4136 (if (= (point-at-bol) (match-beginning 2))
4137 "Footnote definition"
4138 "Footnote reference")
4140 t)))
4142 (defun org-activate-bracket-links (limit)
4143 "Run through the buffer and add overlays to bracketed links."
4144 (if (re-search-forward org-bracket-link-regexp limit t)
4145 (let* ((help (concat "LINK: "
4146 (org-match-string-no-properties 1)))
4147 ;; FIXME: above we should remove the escapes.
4148 ;; but that requires another match, protecting match data,
4149 ;; a lot of overhead for font-lock.
4150 (ip (org-maybe-intangible
4151 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4152 'keymap org-mouse-map 'mouse-face 'highlight
4153 'font-lock-multiline t 'help-echo help)))
4154 (vp (list 'rear-nonsticky org-nonsticky-props
4155 'keymap org-mouse-map 'mouse-face 'highlight
4156 'font-lock-multiline t 'help-echo help)))
4157 ;; We need to remove the invisible property here. Table narrowing
4158 ;; may have made some of this invisible.
4159 (remove-text-properties (match-beginning 0) (match-end 0)
4160 '(invisible nil))
4161 (if (match-end 3)
4162 (progn
4163 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4164 (add-text-properties (match-beginning 3) (match-end 3) vp)
4165 (add-text-properties (match-end 3) (match-end 0) ip))
4166 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4167 (add-text-properties (match-beginning 1) (match-end 1) vp)
4168 (add-text-properties (match-end 1) (match-end 0) ip))
4169 t)))
4171 (defun org-activate-dates (limit)
4172 "Run through the buffer and add overlays to dates."
4173 (if (re-search-forward org-tsr-regexp-both limit t)
4174 (progn
4175 (add-text-properties (match-beginning 0) (match-end 0)
4176 (list 'mouse-face 'highlight
4177 'rear-nonsticky org-nonsticky-props
4178 'keymap org-mouse-map))
4179 (when org-display-custom-times
4180 (if (match-end 3)
4181 (org-display-custom-time (match-beginning 3) (match-end 3)))
4182 (org-display-custom-time (match-beginning 1) (match-end 1)))
4183 t)))
4185 (defvar org-target-link-regexp nil
4186 "Regular expression matching radio targets in plain text.")
4187 (make-variable-buffer-local 'org-target-link-regexp)
4188 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4189 "Regular expression matching a link target.")
4190 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4191 "Regular expression matching a radio target.")
4192 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4193 "Regular expression matching any target.")
4195 (defun org-activate-target-links (limit)
4196 "Run through the buffer and add overlays to target matches."
4197 (when org-target-link-regexp
4198 (let ((case-fold-search t))
4199 (if (re-search-forward org-target-link-regexp limit t)
4200 (progn
4201 (add-text-properties (match-beginning 0) (match-end 0)
4202 (list 'mouse-face 'highlight
4203 'rear-nonsticky org-nonsticky-props
4204 'keymap org-mouse-map
4205 'help-echo "Radio target link"
4206 'org-linked-text t))
4207 t)))))
4209 (defun org-update-radio-target-regexp ()
4210 "Find all radio targets in this file and update the regular expression."
4211 (interactive)
4212 (when (memq 'radio org-activate-links)
4213 (setq org-target-link-regexp
4214 (org-make-target-link-regexp (org-all-targets 'radio)))
4215 (org-restart-font-lock)))
4217 (defun org-hide-wide-columns (limit)
4218 (let (s e)
4219 (setq s (text-property-any (point) (or limit (point-max))
4220 'org-cwidth t))
4221 (when s
4222 (setq e (next-single-property-change s 'org-cwidth))
4223 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4224 (goto-char e)
4225 t)))
4227 (defvar org-latex-and-specials-regexp nil
4228 "Regular expression for highlighting export special stuff.")
4229 (defvar org-match-substring-regexp)
4230 (defvar org-match-substring-with-braces-regexp)
4231 (defvar org-export-html-special-string-regexps)
4233 (defun org-compute-latex-and-specials-regexp ()
4234 "Compute regular expression for stuff treated specially by exporters."
4235 (if (not org-highlight-latex-fragments-and-specials)
4236 (org-set-local 'org-latex-and-specials-regexp nil)
4237 (require 'org-exp)
4238 (let*
4239 ((matchers (plist-get org-format-latex-options :matchers))
4240 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4241 org-latex-regexps)))
4242 (options (org-combine-plists (org-default-export-plist)
4243 (org-infile-export-plist)))
4244 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4245 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4246 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4247 (org-export-html-expand (plist-get options :expand-quoted-html))
4248 (org-export-with-special-strings (plist-get options :special-strings))
4249 (re-sub
4250 (cond
4251 ((equal org-export-with-sub-superscripts '{})
4252 (list org-match-substring-with-braces-regexp))
4253 (org-export-with-sub-superscripts
4254 (list org-match-substring-regexp))
4255 (t nil)))
4256 (re-latex
4257 (if org-export-with-LaTeX-fragments
4258 (mapcar (lambda (x) (nth 1 x)) latexs)))
4259 (re-macros
4260 (if org-export-with-TeX-macros
4261 (list (concat "\\\\"
4262 (regexp-opt
4263 (append (mapcar 'car org-html-entities)
4264 (if (boundp 'org-latex-entities)
4265 org-latex-entities nil))
4266 'words))) ; FIXME
4268 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4269 (re-special (if org-export-with-special-strings
4270 (mapcar (lambda (x) (car x))
4271 org-export-html-special-string-regexps)))
4272 (re-rest
4273 (delq nil
4274 (list
4275 (if org-export-html-expand "@<[^>\n]+>")
4276 ))))
4277 (org-set-local
4278 'org-latex-and-specials-regexp
4279 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4280 re-rest) "\\|")))))
4282 (defun org-do-latex-and-special-faces (limit)
4283 "Run through the buffer and add overlays to links."
4284 (when org-latex-and-specials-regexp
4285 (let (rtn d)
4286 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4287 limit t))
4288 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4289 'face))
4290 '(org-code org-verbatim underline)))
4291 (progn
4292 (setq rtn t
4293 d (cond ((member (char-after (1+ (match-beginning 0)))
4294 '(?_ ?^)) 1)
4295 (t 0)))
4296 (font-lock-prepend-text-property
4297 (+ d (match-beginning 0)) (match-end 0)
4298 'face 'org-latex-and-export-specials)
4299 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4300 '(font-lock-multiline t)))))
4301 rtn)))
4303 (defun org-restart-font-lock ()
4304 "Restart font-lock-mode, to force refontification."
4305 (when (and (boundp 'font-lock-mode) font-lock-mode)
4306 (font-lock-mode -1)
4307 (font-lock-mode 1)))
4309 (defun org-all-targets (&optional radio)
4310 "Return a list of all targets in this file.
4311 With optional argument RADIO, only find radio targets."
4312 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4313 rtn)
4314 (save-excursion
4315 (goto-char (point-min))
4316 (while (re-search-forward re nil t)
4317 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4318 rtn)))
4320 (defun org-make-target-link-regexp (targets)
4321 "Make regular expression matching all strings in TARGETS.
4322 The regular expression finds the targets also if there is a line break
4323 between words."
4324 (and targets
4325 (concat
4326 "\\<\\("
4327 (mapconcat
4328 (lambda (x)
4329 (while (string-match " +" x)
4330 (setq x (replace-match "\\s-+" t t x)))
4332 targets
4333 "\\|")
4334 "\\)\\>")))
4336 (defun org-activate-tags (limit)
4337 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4338 (progn
4339 (add-text-properties (match-beginning 1) (match-end 1)
4340 (list 'mouse-face 'highlight
4341 'rear-nonsticky org-nonsticky-props
4342 'keymap org-mouse-map))
4343 t)))
4345 (defun org-outline-level ()
4346 (save-excursion
4347 (looking-at outline-regexp)
4348 (if (match-beginning 1)
4349 (+ (org-get-string-indentation (match-string 1)) 1000)
4350 (1- (- (match-end 0) (match-beginning 0))))))
4352 (defvar org-font-lock-keywords nil)
4354 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4355 "Regular expression matching a property line.")
4357 (defvar org-font-lock-hook nil
4358 "Functions to be called for special font lock stuff.")
4360 (defun org-font-lock-hook (limit)
4361 (run-hook-with-args 'org-font-lock-hook limit))
4363 (defun org-set-font-lock-defaults ()
4364 (let* ((em org-fontify-emphasized-text)
4365 (lk org-activate-links)
4366 (org-font-lock-extra-keywords
4367 (list
4368 ;; Call the hook
4369 '(org-font-lock-hook)
4370 ;; Headlines
4371 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4372 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4373 ;; Table lines
4374 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4375 (1 'org-table t))
4376 ;; Table internals
4377 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4378 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4379 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4380 ;; Drawers
4381 (list org-drawer-regexp '(0 'org-special-keyword t))
4382 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4383 ;; Properties
4384 (list org-property-re
4385 '(1 'org-special-keyword t)
4386 '(3 'org-property-value t))
4387 (if org-format-transports-properties-p
4388 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4389 ;; Links
4390 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4391 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4392 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4393 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4394 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4395 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4396 (if (memq 'footnote lk) '(org-activate-footnote-links
4397 (2 'org-footnote t)))
4398 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4399 '(org-hide-wide-columns (0 nil append))
4400 ;; TODO lines
4401 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4402 '(1 (org-get-todo-face 1) t))
4403 ;; DONE
4404 (if org-fontify-done-headline
4405 (list (concat "^[*]+ +\\<\\("
4406 (mapconcat 'regexp-quote org-done-keywords "\\|")
4407 "\\)\\(.*\\)")
4408 '(2 'org-headline-done t))
4409 nil)
4410 ;; Priorities
4411 '(org-font-lock-add-priority-faces)
4412 ;; Tags
4413 '(org-font-lock-add-tag-faces)
4414 ;; Special keywords
4415 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4416 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4417 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4418 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4419 ;; Emphasis
4420 (if em
4421 (if (featurep 'xemacs)
4422 '(org-do-emphasis-faces (0 nil append))
4423 '(org-do-emphasis-faces)))
4424 ;; Checkboxes
4425 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4426 2 'org-checkbox prepend)
4427 (if org-provide-checkbox-statistics
4428 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4429 (0 (org-get-checkbox-statistics-face) t)))
4430 ;; Description list items
4431 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4432 2 'bold prepend)
4433 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4434 '(1 'org-archived prepend))
4435 ;; Specials
4436 '(org-do-latex-and-special-faces)
4437 ;; Code
4438 '(org-activate-code (1 'org-code t))
4439 ;; COMMENT
4440 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4441 "\\|" org-quote-string "\\)\\>")
4442 '(1 'org-special-keyword t))
4443 '("^#.*" (0 'font-lock-comment-face t))
4445 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4446 ;; Now set the full font-lock-keywords
4447 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4448 (org-set-local 'font-lock-defaults
4449 '(org-font-lock-keywords t nil nil backward-paragraph))
4450 (kill-local-variable 'font-lock-keywords) nil))
4452 (defvar org-m nil)
4453 (defvar org-l nil)
4454 (defvar org-f nil)
4455 (defun org-get-level-face (n)
4456 "Get the right face for match N in font-lock matching of headlines."
4457 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4458 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4459 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4460 (cond
4461 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4462 ((eq n 2) org-f)
4463 (t (if org-level-color-stars-only nil org-f))))
4465 (defun org-get-todo-face (kwd)
4466 "Get the right face for a TODO keyword KWD.
4467 If KWD is a number, get the corresponding match group."
4468 (if (numberp kwd) (setq kwd (match-string kwd)))
4469 (or (cdr (assoc kwd org-todo-keyword-faces))
4470 (and (member kwd org-done-keywords) 'org-done)
4471 'org-todo))
4473 (defun org-font-lock-add-tag-faces (limit)
4474 "Add the special tag faces."
4475 (when (and org-tag-faces org-tags-special-faces-re)
4476 (while (re-search-forward org-tags-special-faces-re limit t)
4477 (add-text-properties (match-beginning 1) (match-end 1)
4478 (list 'face (org-get-tag-face 1)
4479 'font-lock-fontified t))
4480 (backward-char 1))))
4482 (defun org-font-lock-add-priority-faces (limit)
4483 "Add the special priority faces."
4484 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4485 (add-text-properties
4486 (match-beginning 0) (match-end 0)
4487 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4488 org-priority-faces))
4489 'org-special-keyword)
4490 'font-lock-fontified t))))
4492 (defun org-get-tag-face (kwd)
4493 "Get the right face for a TODO keyword KWD.
4494 If KWD is a number, get the corresponding match group."
4495 (if (numberp kwd) (setq kwd (match-string kwd)))
4496 (or (cdr (assoc kwd org-tag-faces))
4497 'org-tag))
4499 (defun org-unfontify-region (beg end &optional maybe_loudly)
4500 "Remove fontification and activation overlays from links."
4501 (font-lock-default-unfontify-region beg end)
4502 (let* ((buffer-undo-list t)
4503 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4504 (inhibit-modification-hooks t)
4505 deactivate-mark buffer-file-name buffer-file-truename)
4506 (remove-text-properties beg end
4507 '(mouse-face t keymap t org-linked-text t
4508 invisible t intangible t))))
4510 ;;;; Visibility cycling, including org-goto and indirect buffer
4512 ;;; Cycling
4514 (defvar org-cycle-global-status nil)
4515 (make-variable-buffer-local 'org-cycle-global-status)
4516 (defvar org-cycle-subtree-status nil)
4517 (make-variable-buffer-local 'org-cycle-subtree-status)
4519 ;;;###autoload
4521 (defvar org-inlinetask-min-level)
4522 (defun org-cycle (&optional arg)
4523 "Visibility cycling for Org-mode.
4525 - When this function is called with a prefix argument, rotate the entire
4526 buffer through 3 states (global cycling)
4527 1. OVERVIEW: Show only top-level headlines.
4528 2. CONTENTS: Show all headlines of all levels, but no body text.
4529 3. SHOW ALL: Show everything.
4530 When called with two C-u C-u prefixes, switch to the startup visibility,
4531 determined by the variable `org-startup-folded', and by any VISIBILITY
4532 properties in the buffer.
4533 When called with three C-u C-u C-u prefixed, show the entire buffer,
4534 including drawers.
4536 - When point is at the beginning of a headline, rotate the subtree started
4537 by this line through 3 different states (local cycling)
4538 1. FOLDED: Only the main headline is shown.
4539 2. CHILDREN: The main headline and the direct children are shown.
4540 From this state, you can move to one of the children
4541 and zoom in further.
4542 3. SUBTREE: Show the entire subtree, including body text.
4544 - When there is a numeric prefix, go up to a heading with level ARG, do
4545 a `show-subtree' and return to the previous cursor position. If ARG
4546 is negative, go up that many levels.
4548 - When point is not at the beginning of a headline, execute the global
4549 binding for TAB, which is re-indenting the line. See the option
4550 `org-cycle-emulate-tab' for details.
4552 - Special case: if point is at the beginning of the buffer and there is
4553 no headline in line 1, this function will act as if called with prefix arg.
4554 But only if also the variable `org-cycle-global-at-bob' is t."
4555 (interactive "P")
4556 (org-load-modules-maybe)
4557 (let* ((limit-level
4558 (or org-cycle-max-level
4559 (and (boundp 'org-inlinetask-min-level)
4560 org-inlinetask-min-level
4561 (1- org-inlinetask-min-level))))
4562 (nstars (and limit-level
4563 (if org-odd-levels-only
4564 (and limit-level (1- (* limit-level 2)))
4565 limit-level)))
4566 (outline-regexp
4567 (cond
4568 ((not (org-mode-p)) outline-regexp)
4569 (org-cycle-include-plain-lists
4570 (concat "\\(?:\\*"
4571 (if nstars (format "\\{1,%d\\} " nstars) "+")
4572 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4573 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4574 (bob-special (and org-cycle-global-at-bob (bobp)
4575 (not (looking-at outline-regexp))))
4576 (org-cycle-hook
4577 (if bob-special
4578 (delq 'org-optimize-window-after-visibility-change
4579 (copy-sequence org-cycle-hook))
4580 org-cycle-hook))
4581 (pos (point)))
4583 (if (or bob-special (equal arg '(4)))
4584 ;; special case: use global cycling
4585 (setq arg t))
4587 (cond
4589 ((equal arg '(16))
4590 (org-set-startup-visibility)
4591 (message "Startup visibility, plus VISIBILITY properties"))
4593 ((equal arg '(64))
4594 (show-all)
4595 (message "Entire buffer visible, including drawers"))
4597 ((org-at-table-p 'any)
4598 ;; Enter the table or move to the next field in the table
4599 (or (org-table-recognize-table.el)
4600 (progn
4601 (if arg (org-table-edit-field t)
4602 (org-table-justify-field-maybe)
4603 (call-interactively 'org-table-next-field)))))
4605 ((eq arg t) ;; Global cycling
4607 (cond
4608 ((and (eq last-command this-command)
4609 (eq org-cycle-global-status 'overview))
4610 ;; We just created the overview - now do table of contents
4611 ;; This can be slow in very large buffers, so indicate action
4612 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4613 (message "CONTENTS...")
4614 (org-content)
4615 (message "CONTENTS...done")
4616 (setq org-cycle-global-status 'contents)
4617 (run-hook-with-args 'org-cycle-hook 'contents))
4619 ((and (eq last-command this-command)
4620 (eq org-cycle-global-status 'contents))
4621 ;; We just showed the table of contents - now show everything
4622 (run-hook-with-args 'org-pre-cycle-hook 'all)
4623 (show-all)
4624 (message "SHOW ALL")
4625 (setq org-cycle-global-status 'all)
4626 (run-hook-with-args 'org-cycle-hook 'all))
4629 ;; Default action: go to overview
4630 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4631 (org-overview)
4632 (message "OVERVIEW")
4633 (setq org-cycle-global-status 'overview)
4634 (run-hook-with-args 'org-cycle-hook 'overview))))
4636 ((and org-drawers org-drawer-regexp
4637 (save-excursion
4638 (beginning-of-line 1)
4639 (looking-at org-drawer-regexp)))
4640 ;; Toggle block visibility
4641 (org-flag-drawer
4642 (not (get-char-property (match-end 0) 'invisible))))
4644 ((integerp arg)
4645 ;; Show-subtree, ARG levels up from here.
4646 (save-excursion
4647 (org-back-to-heading)
4648 (outline-up-heading (if (< arg 0) (- arg)
4649 (- (funcall outline-level) arg)))
4650 (org-show-subtree)))
4652 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4653 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4654 ;; At a heading: rotate between three different views
4655 (org-back-to-heading)
4656 (let ((goal-column 0) eoh eol eos)
4657 ;; First, some boundaries
4658 (save-excursion
4659 (org-back-to-heading)
4660 (save-excursion
4661 (beginning-of-line 2)
4662 (while (and (not (eobp)) ;; this is like `next-line'
4663 (get-char-property (1- (point)) 'invisible))
4664 (beginning-of-line 2)) (setq eol (point)))
4665 (outline-end-of-heading) (setq eoh (point))
4666 (org-end-of-subtree t)
4667 (unless (eobp)
4668 (skip-chars-forward " \t\n")
4669 (beginning-of-line 1) ; in case this is an item
4671 (setq eos (1- (point))))
4672 ;; Find out what to do next and set `this-command'
4673 (cond
4674 ((= eos eoh)
4675 ;; Nothing is hidden behind this heading
4676 (run-hook-with-args 'org-pre-cycle-hook 'empty)
4677 (message "EMPTY ENTRY")
4678 (setq org-cycle-subtree-status nil)
4679 (save-excursion
4680 (goto-char eos)
4681 (outline-next-heading)
4682 (if (org-invisible-p) (org-flag-heading nil))))
4683 ((or (>= eol eos)
4684 (not (string-match "\\S-" (buffer-substring eol eos))))
4685 ;; Entire subtree is hidden in one line: open it
4686 (run-hook-with-args 'org-pre-cycle-hook 'children)
4687 (org-show-entry)
4688 (show-children)
4689 (message "CHILDREN")
4690 (save-excursion
4691 (goto-char eos)
4692 (outline-next-heading)
4693 (if (org-invisible-p) (org-flag-heading nil)))
4694 (setq org-cycle-subtree-status 'children)
4695 (run-hook-with-args 'org-cycle-hook 'children))
4696 ((and (eq last-command this-command)
4697 (eq org-cycle-subtree-status 'children))
4698 ;; We just showed the children, now show everything.
4699 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
4700 (org-show-subtree)
4701 (message "SUBTREE")
4702 (setq org-cycle-subtree-status 'subtree)
4703 (run-hook-with-args 'org-cycle-hook 'subtree))
4705 ;; Default action: hide the subtree.
4706 (run-hook-with-args 'org-pre-cycle-hook 'folded)
4707 (hide-subtree)
4708 (message "FOLDED")
4709 (setq org-cycle-subtree-status 'folded)
4710 (run-hook-with-args 'org-cycle-hook 'folded)))))
4712 ;; TAB emulation and template completion
4713 (buffer-read-only (org-back-to-heading))
4715 ((org-try-structure-completion))
4717 ((org-try-cdlatex-tab))
4719 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4720 (or (not (bolp))
4721 (not (looking-at outline-regexp))))
4722 (call-interactively (global-key-binding "\t")))
4724 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4725 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4726 (or (and (eq org-cycle-emulate-tab 'white)
4727 (= (match-end 0) (point-at-eol)))
4728 (and (eq org-cycle-emulate-tab 'whitestart)
4729 (>= (match-end 0) pos))))
4731 (eq org-cycle-emulate-tab t))
4732 (call-interactively (global-key-binding "\t")))
4734 (t (save-excursion
4735 (org-back-to-heading)
4736 (org-cycle))))))
4738 ;;;###autoload
4739 (defun org-global-cycle (&optional arg)
4740 "Cycle the global visibility. For details see `org-cycle'.
4741 With C-u prefix arg, switch to startup visibility.
4742 With a numeric prefix, show all headlines up to that level."
4743 (interactive "P")
4744 (let ((org-cycle-include-plain-lists
4745 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4746 (cond
4747 ((integerp arg)
4748 (show-all)
4749 (hide-sublevels arg)
4750 (setq org-cycle-global-status 'contents))
4751 ((equal arg '(4))
4752 (org-set-startup-visibility)
4753 (message "Startup visibility, plus VISIBILITY properties."))
4755 (org-cycle '(4))))))
4757 (defun org-set-startup-visibility ()
4758 "Set the visibility required by startup options and properties."
4759 (cond
4760 ((eq org-startup-folded t)
4761 (org-cycle '(4)))
4762 ((eq org-startup-folded 'content)
4763 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4764 (org-cycle '(4)) (org-cycle '(4)))))
4765 (org-set-visibility-according-to-property 'no-cleanup)
4766 (org-cycle-hide-archived-subtrees 'all)
4767 (org-cycle-hide-drawers 'all)
4768 (org-cycle-show-empty-lines 'all))
4770 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4771 "Switch subtree visibilities according to :VISIBILITY: property."
4772 (interactive)
4773 (let (org-show-entry-below state)
4774 (save-excursion
4775 (goto-char (point-min))
4776 (while (re-search-forward
4777 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4778 nil t)
4779 (setq state (match-string 1))
4780 (save-excursion
4781 (org-back-to-heading t)
4782 (hide-subtree)
4783 (org-reveal)
4784 (cond
4785 ((equal state '("fold" "folded"))
4786 (hide-subtree))
4787 ((equal state "children")
4788 (org-show-hidden-entry)
4789 (show-children))
4790 ((equal state "content")
4791 (save-excursion
4792 (save-restriction
4793 (org-narrow-to-subtree)
4794 (org-content))))
4795 ((member state '("all" "showall"))
4796 (show-subtree)))))
4797 (unless no-cleanup
4798 (org-cycle-hide-archived-subtrees 'all)
4799 (org-cycle-hide-drawers 'all)
4800 (org-cycle-show-empty-lines 'all)))))
4802 (defun org-overview ()
4803 "Switch to overview mode, showing only top-level headlines.
4804 Really, this shows all headlines with level equal or greater than the level
4805 of the first headline in the buffer. This is important, because if the
4806 first headline is not level one, then (hide-sublevels 1) gives confusing
4807 results."
4808 (interactive)
4809 (let ((level (save-excursion
4810 (goto-char (point-min))
4811 (if (re-search-forward (concat "^" outline-regexp) nil t)
4812 (progn
4813 (goto-char (match-beginning 0))
4814 (funcall outline-level))))))
4815 (and level (hide-sublevels level))))
4817 (defun org-content (&optional arg)
4818 "Show all headlines in the buffer, like a table of contents.
4819 With numerical argument N, show content up to level N."
4820 (interactive "P")
4821 (save-excursion
4822 ;; Visit all headings and show their offspring
4823 (and (integerp arg) (org-overview))
4824 (goto-char (point-max))
4825 (catch 'exit
4826 (while (and (progn (condition-case nil
4827 (outline-previous-visible-heading 1)
4828 (error (goto-char (point-min))))
4830 (looking-at outline-regexp))
4831 (if (integerp arg)
4832 (show-children (1- arg))
4833 (show-branches))
4834 (if (bobp) (throw 'exit nil))))))
4837 (defun org-optimize-window-after-visibility-change (state)
4838 "Adjust the window after a change in outline visibility.
4839 This function is the default value of the hook `org-cycle-hook'."
4840 (when (get-buffer-window (current-buffer))
4841 (cond
4842 ((eq state 'content) nil)
4843 ((eq state 'all) nil)
4844 ((eq state 'folded) nil)
4845 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4846 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4848 (defun org-compact-display-after-subtree-move ()
4849 "Show a compacter version of the tree of the entry's parent."
4850 (save-excursion
4851 (if (org-up-heading-safe)
4852 (progn
4853 (hide-subtree)
4854 (show-entry)
4855 (show-children)
4856 (org-cycle-show-empty-lines 'children)
4857 (org-cycle-hide-drawers 'children))
4858 (org-overview))))
4860 (defun org-cycle-show-empty-lines (state)
4861 "Show empty lines above all visible headlines.
4862 The region to be covered depends on STATE when called through
4863 `org-cycle-hook'. Lisp program can use t for STATE to get the
4864 entire buffer covered. Note that an empty line is only shown if there
4865 are at least `org-cycle-separator-lines' empty lines before the headline."
4866 (when (> org-cycle-separator-lines 0)
4867 (save-excursion
4868 (let* ((n org-cycle-separator-lines)
4869 (re (cond
4870 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4871 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4872 (t (let ((ns (number-to-string (- n 2))))
4873 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4874 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4875 beg end)
4876 (cond
4877 ((memq state '(overview contents t))
4878 (setq beg (point-min) end (point-max)))
4879 ((memq state '(children folded))
4880 (setq beg (point) end (progn (org-end-of-subtree t t)
4881 (beginning-of-line 2)
4882 (point)))))
4883 (when beg
4884 (goto-char beg)
4885 (while (re-search-forward re end t)
4886 (if (not (get-char-property (match-end 1) 'invisible))
4887 (outline-flag-region
4888 (match-beginning 1) (match-end 1) nil)))))))
4889 ;; Never hide empty lines at the end of the file.
4890 (save-excursion
4891 (goto-char (point-max))
4892 (outline-previous-heading)
4893 (outline-end-of-heading)
4894 (if (and (looking-at "[ \t\n]+")
4895 (= (match-end 0) (point-max)))
4896 (outline-flag-region (point) (match-end 0) nil))))
4898 (defun org-show-empty-lines-in-parent ()
4899 "Move to the parent and re-show empty lines before visible headlines."
4900 (save-excursion
4901 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4902 (org-cycle-show-empty-lines context))))
4904 (defun org-cycle-hide-drawers (state)
4905 "Re-hide all drawers after a visibility state change."
4906 (when (and (org-mode-p)
4907 (not (memq state '(overview folded))))
4908 (save-excursion
4909 (let* ((globalp (memq state '(contents all)))
4910 (beg (if globalp (point-min) (point)))
4911 (end (if globalp (point-max) (org-end-of-subtree t))))
4912 (goto-char beg)
4913 (while (re-search-forward org-drawer-regexp end t)
4914 (org-flag-drawer t))))))
4916 (defun org-flag-drawer (flag)
4917 (save-excursion
4918 (beginning-of-line 1)
4919 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4920 (let ((b (match-end 0))
4921 (outline-regexp org-outline-regexp))
4922 (if (re-search-forward
4923 "^[ \t]*:END:"
4924 (save-excursion (outline-next-heading) (point)) t)
4925 (outline-flag-region b (point-at-eol) flag)
4926 (error ":END: line missing"))))))
4928 (defun org-subtree-end-visible-p ()
4929 "Is the end of the current subtree visible?"
4930 (pos-visible-in-window-p
4931 (save-excursion (org-end-of-subtree t) (point))))
4933 (defun org-first-headline-recenter (&optional N)
4934 "Move cursor to the first headline and recenter the headline.
4935 Optional argument N means, put the headline into the Nth line of the window."
4936 (goto-char (point-min))
4937 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4938 (beginning-of-line)
4939 (recenter (prefix-numeric-value N))))
4941 ;;; Org-goto
4943 (defvar org-goto-window-configuration nil)
4944 (defvar org-goto-marker nil)
4945 (defvar org-goto-map
4946 (let ((map (make-sparse-keymap)))
4947 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4948 (while (setq cmd (pop cmds))
4949 (substitute-key-definition cmd cmd map global-map)))
4950 (suppress-keymap map)
4951 (org-defkey map "\C-m" 'org-goto-ret)
4952 (org-defkey map [(return)] 'org-goto-ret)
4953 (org-defkey map [(left)] 'org-goto-left)
4954 (org-defkey map [(right)] 'org-goto-right)
4955 (org-defkey map [(control ?g)] 'org-goto-quit)
4956 (org-defkey map "\C-i" 'org-cycle)
4957 (org-defkey map [(tab)] 'org-cycle)
4958 (org-defkey map [(down)] 'outline-next-visible-heading)
4959 (org-defkey map [(up)] 'outline-previous-visible-heading)
4960 (if org-goto-auto-isearch
4961 (if (fboundp 'define-key-after)
4962 (define-key-after map [t] 'org-goto-local-auto-isearch)
4963 nil)
4964 (org-defkey map "q" 'org-goto-quit)
4965 (org-defkey map "n" 'outline-next-visible-heading)
4966 (org-defkey map "p" 'outline-previous-visible-heading)
4967 (org-defkey map "f" 'outline-forward-same-level)
4968 (org-defkey map "b" 'outline-backward-same-level)
4969 (org-defkey map "u" 'outline-up-heading))
4970 (org-defkey map "/" 'org-occur)
4971 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4972 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4973 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4974 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4975 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4976 map))
4978 (defconst org-goto-help
4979 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4980 RET=jump to location [Q]uit and return to previous location
4981 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4983 (defvar org-goto-start-pos) ; dynamically scoped parameter
4985 ;; FIXME: Docstring doe not mention both interfaces
4986 (defun org-goto (&optional alternative-interface)
4987 "Look up a different location in the current file, keeping current visibility.
4989 When you want look-up or go to a different location in a document, the
4990 fastest way is often to fold the entire buffer and then dive into the tree.
4991 This method has the disadvantage, that the previous location will be folded,
4992 which may not be what you want.
4994 This command works around this by showing a copy of the current buffer
4995 in an indirect buffer, in overview mode. You can dive into the tree in
4996 that copy, use org-occur and incremental search to find a location.
4997 When pressing RET or `Q', the command returns to the original buffer in
4998 which the visibility is still unchanged. After RET is will also jump to
4999 the location selected in the indirect buffer and expose the
5000 the headline hierarchy above."
5001 (interactive "P")
5002 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5003 (org-refile-use-outline-path t)
5004 (interface
5005 (if (not alternative-interface)
5006 org-goto-interface
5007 (if (eq org-goto-interface 'outline)
5008 'outline-path-completion
5009 'outline)))
5010 (org-goto-start-pos (point))
5011 (selected-point
5012 (if (eq interface 'outline)
5013 (car (org-get-location (current-buffer) org-goto-help))
5014 (nth 3 (org-refile-get-location "Goto: ")))))
5015 (if selected-point
5016 (progn
5017 (org-mark-ring-push org-goto-start-pos)
5018 (goto-char selected-point)
5019 (if (or (org-invisible-p) (org-invisible-p2))
5020 (org-show-context 'org-goto)))
5021 (message "Quit"))))
5023 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5024 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5025 (defvar org-goto-local-auto-isearch-map) ; defined below
5027 (defun org-get-location (buf help)
5028 "Let the user select a location in the Org-mode buffer BUF.
5029 This function uses a recursive edit. It returns the selected position
5030 or nil."
5031 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5032 (isearch-hide-immediately nil)
5033 (isearch-search-fun-function
5034 (lambda () 'org-goto-local-search-headings))
5035 (org-goto-selected-point org-goto-exit-command))
5036 (save-excursion
5037 (save-window-excursion
5038 (delete-other-windows)
5039 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5040 (switch-to-buffer
5041 (condition-case nil
5042 (make-indirect-buffer (current-buffer) "*org-goto*")
5043 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5044 (with-output-to-temp-buffer "*Help*"
5045 (princ help))
5046 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5047 (setq buffer-read-only nil)
5048 (let ((org-startup-truncated t)
5049 (org-startup-folded nil)
5050 (org-startup-align-all-tables nil))
5051 (org-mode)
5052 (org-overview))
5053 (setq buffer-read-only t)
5054 (if (and (boundp 'org-goto-start-pos)
5055 (integer-or-marker-p org-goto-start-pos))
5056 (let ((org-show-hierarchy-above t)
5057 (org-show-siblings t)
5058 (org-show-following-heading t))
5059 (goto-char org-goto-start-pos)
5060 (and (org-invisible-p) (org-show-context)))
5061 (goto-char (point-min)))
5062 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5063 (message "Select location and press RET")
5064 (use-local-map org-goto-map)
5065 (recursive-edit)
5067 (kill-buffer "*org-goto*")
5068 (cons org-goto-selected-point org-goto-exit-command)))
5070 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5071 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5072 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5073 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5075 (defun org-goto-local-search-headings (string bound noerror)
5076 "Search and make sure that any matches are in headlines."
5077 (catch 'return
5078 (while (if isearch-forward
5079 (search-forward string bound noerror)
5080 (search-backward string bound noerror))
5081 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5082 (and (member :headline context)
5083 (not (member :tags context))))
5084 (throw 'return (point))))))
5086 (defun org-goto-local-auto-isearch ()
5087 "Start isearch."
5088 (interactive)
5089 (goto-char (point-min))
5090 (let ((keys (this-command-keys)))
5091 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5092 (isearch-mode t)
5093 (isearch-process-search-char (string-to-char keys)))))
5095 (defun org-goto-ret (&optional arg)
5096 "Finish `org-goto' by going to the new location."
5097 (interactive "P")
5098 (setq org-goto-selected-point (point)
5099 org-goto-exit-command 'return)
5100 (throw 'exit nil))
5102 (defun org-goto-left ()
5103 "Finish `org-goto' by going to the new location."
5104 (interactive)
5105 (if (org-on-heading-p)
5106 (progn
5107 (beginning-of-line 1)
5108 (setq org-goto-selected-point (point)
5109 org-goto-exit-command 'left)
5110 (throw 'exit nil))
5111 (error "Not on a heading")))
5113 (defun org-goto-right ()
5114 "Finish `org-goto' by going to the new location."
5115 (interactive)
5116 (if (org-on-heading-p)
5117 (progn
5118 (setq org-goto-selected-point (point)
5119 org-goto-exit-command 'right)
5120 (throw 'exit nil))
5121 (error "Not on a heading")))
5123 (defun org-goto-quit ()
5124 "Finish `org-goto' without cursor motion."
5125 (interactive)
5126 (setq org-goto-selected-point nil)
5127 (setq org-goto-exit-command 'quit)
5128 (throw 'exit nil))
5130 ;;; Indirect buffer display of subtrees
5132 (defvar org-indirect-dedicated-frame nil
5133 "This is the frame being used for indirect tree display.")
5134 (defvar org-last-indirect-buffer nil)
5136 (defun org-tree-to-indirect-buffer (&optional arg)
5137 "Create indirect buffer and narrow it to current subtree.
5138 With numerical prefix ARG, go up to this level and then take that tree.
5139 If ARG is negative, go up that many levels.
5140 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5141 indirect buffer previously made with this command, to avoid proliferation of
5142 indirect buffers. However, when you call the command with a `C-u' prefix, or
5143 when `org-indirect-buffer-display' is `new-frame', the last buffer
5144 is kept so that you can work with several indirect buffers at the same time.
5145 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5146 requests that a new frame be made for the new buffer, so that the dedicated
5147 frame is not changed."
5148 (interactive "P")
5149 (let ((cbuf (current-buffer))
5150 (cwin (selected-window))
5151 (pos (point))
5152 beg end level heading ibuf)
5153 (save-excursion
5154 (org-back-to-heading t)
5155 (when (numberp arg)
5156 (setq level (org-outline-level))
5157 (if (< arg 0) (setq arg (+ level arg)))
5158 (while (> (setq level (org-outline-level)) arg)
5159 (outline-up-heading 1 t)))
5160 (setq beg (point)
5161 heading (org-get-heading))
5162 (org-end-of-subtree t) (setq end (point)))
5163 (if (and (buffer-live-p org-last-indirect-buffer)
5164 (not (eq org-indirect-buffer-display 'new-frame))
5165 (not arg))
5166 (kill-buffer org-last-indirect-buffer))
5167 (setq ibuf (org-get-indirect-buffer cbuf)
5168 org-last-indirect-buffer ibuf)
5169 (cond
5170 ((or (eq org-indirect-buffer-display 'new-frame)
5171 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5172 (select-frame (make-frame))
5173 (delete-other-windows)
5174 (switch-to-buffer ibuf)
5175 (org-set-frame-title heading))
5176 ((eq org-indirect-buffer-display 'dedicated-frame)
5177 (raise-frame
5178 (select-frame (or (and org-indirect-dedicated-frame
5179 (frame-live-p org-indirect-dedicated-frame)
5180 org-indirect-dedicated-frame)
5181 (setq org-indirect-dedicated-frame (make-frame)))))
5182 (delete-other-windows)
5183 (switch-to-buffer ibuf)
5184 (org-set-frame-title (concat "Indirect: " heading)))
5185 ((eq org-indirect-buffer-display 'current-window)
5186 (switch-to-buffer ibuf))
5187 ((eq org-indirect-buffer-display 'other-window)
5188 (pop-to-buffer ibuf))
5189 (t (error "Invalid value.")))
5190 (if (featurep 'xemacs)
5191 (save-excursion (org-mode) (turn-on-font-lock)))
5192 (narrow-to-region beg end)
5193 (show-all)
5194 (goto-char pos)
5195 (and (window-live-p cwin) (select-window cwin))))
5197 (defun org-get-indirect-buffer (&optional buffer)
5198 (setq buffer (or buffer (current-buffer)))
5199 (let ((n 1) (base (buffer-name buffer)) bname)
5200 (while (buffer-live-p
5201 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5202 (setq n (1+ n)))
5203 (condition-case nil
5204 (make-indirect-buffer buffer bname 'clone)
5205 (error (make-indirect-buffer buffer bname)))))
5207 (defun org-set-frame-title (title)
5208 "Set the title of the current frame to the string TITLE."
5209 ;; FIXME: how to name a single frame in XEmacs???
5210 (unless (featurep 'xemacs)
5211 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5213 ;;;; Structure editing
5215 ;;; Inserting headlines
5217 (defun org-previous-line-empty-p ()
5218 (save-excursion
5219 (and (not (bobp))
5220 (or (beginning-of-line 0) t)
5221 (save-match-data
5222 (looking-at "[ \t]*$")))))
5224 (defun org-insert-heading (&optional force-heading)
5225 "Insert a new heading or item with same depth at point.
5226 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5227 If point is at the beginning of a headline, insert a sibling before the
5228 current headline. If point is not at the beginning, do not split the line,
5229 but create the new headline after the current line."
5230 (interactive "P")
5231 (if (= (buffer-size) 0)
5232 (insert "\n* ")
5233 (when (or force-heading (not (org-insert-item)))
5234 (let* ((empty-line-p nil)
5235 (head (save-excursion
5236 (condition-case nil
5237 (progn
5238 (org-back-to-heading)
5239 (setq empty-line-p (org-previous-line-empty-p))
5240 (match-string 0))
5241 (error "*"))))
5242 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5243 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5244 pos hide-previous previous-pos)
5245 (cond
5246 ((and (org-on-heading-p) (bolp)
5247 (or (bobp)
5248 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5249 ;; insert before the current line
5250 (open-line (if blank 2 1)))
5251 ((and (bolp)
5252 (or (bobp)
5253 (save-excursion
5254 (backward-char 1) (not (org-invisible-p)))))
5255 ;; insert right here
5256 nil)
5258 ;; somewhere in the line
5259 (save-excursion
5260 (setq previous-pos (point-at-bol))
5261 (end-of-line)
5262 (setq hide-previous (org-invisible-p)))
5263 (and org-insert-heading-respect-content (org-show-subtree))
5264 (let ((split
5265 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5266 (save-excursion
5267 (let ((p (point)))
5268 (goto-char (point-at-bol))
5269 (and (looking-at org-complex-heading-regexp)
5270 (> p (match-beginning 4)))))))
5271 tags pos)
5272 (cond
5273 (org-insert-heading-respect-content
5274 (org-end-of-subtree nil t)
5275 (or (bolp) (newline))
5276 (or (org-previous-line-empty-p)
5277 (and blank (newline)))
5278 (open-line 1))
5279 ((org-on-heading-p)
5280 (when hide-previous
5281 (show-children)
5282 (org-show-entry))
5283 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5284 (setq tags (and (match-end 2) (match-string 2)))
5285 (and (match-end 1)
5286 (delete-region (match-beginning 1) (match-end 1)))
5287 (setq pos (point-at-bol))
5288 (or split (end-of-line 1))
5289 (delete-horizontal-space)
5290 (newline (if blank 2 1))
5291 (when tags
5292 (save-excursion
5293 (goto-char pos)
5294 (end-of-line 1)
5295 (insert " " tags)
5296 (org-set-tags nil 'align))))
5298 (or split (end-of-line 1))
5299 (newline (if blank 2 1)))))))
5300 (insert head) (just-one-space)
5301 (setq pos (point))
5302 (end-of-line 1)
5303 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5304 (when (and org-insert-heading-respect-content hide-previous)
5305 (save-excursion
5306 (goto-char previous-pos)
5307 (hide-subtree)))
5308 (run-hooks 'org-insert-heading-hook)))))
5310 (defun org-get-heading (&optional no-tags)
5311 "Return the heading of the current entry, without the stars."
5312 (save-excursion
5313 (org-back-to-heading t)
5314 (if (looking-at
5315 (if no-tags
5316 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5317 "\\*+[ \t]+\\([^\r\n]*\\)"))
5318 (match-string 1) "")))
5320 (defun org-heading-components ()
5321 "Return the components of the current heading.
5322 This is a list with the following elements:
5323 - the level as an integer
5324 - the reduced level, different if `org-odd-levels-only' is set.
5325 - the TODO keyword, or nil
5326 - the priority character, like ?A, or nil if no priority is given
5327 - the headline text itself, or the tags string if no headline text
5328 - the tags string, or nil."
5329 (save-excursion
5330 (org-back-to-heading t)
5331 (if (looking-at org-complex-heading-regexp)
5332 (list (length (match-string 1))
5333 (org-reduced-level (length (match-string 1)))
5334 (org-match-string-no-properties 2)
5335 (and (match-end 3) (aref (match-string 3) 2))
5336 (org-match-string-no-properties 4)
5337 (org-match-string-no-properties 5)))))
5339 (defun org-get-entry ()
5340 "Get the entry text, after heading, entire subtree."
5341 (save-excursion
5342 (org-back-to-heading t)
5343 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5345 (defun org-insert-heading-after-current ()
5346 "Insert a new heading with same level as current, after current subtree."
5347 (interactive)
5348 (org-back-to-heading)
5349 (org-insert-heading)
5350 (org-move-subtree-down)
5351 (end-of-line 1))
5353 (defun org-insert-heading-respect-content ()
5354 (interactive)
5355 (let ((org-insert-heading-respect-content t))
5356 (org-insert-heading t)))
5358 (defun org-insert-todo-heading-respect-content (&optional force-state)
5359 (interactive "P")
5360 (let ((org-insert-heading-respect-content t))
5361 (org-insert-todo-heading force-state t)))
5363 (defun org-insert-todo-heading (arg &optional force-heading)
5364 "Insert a new heading with the same level and TODO state as current heading.
5365 If the heading has no TODO state, or if the state is DONE, use the first
5366 state (TODO by default). Also with prefix arg, force first state."
5367 (interactive "P")
5368 (when (or force-heading (not (org-insert-item 'checkbox)))
5369 (org-insert-heading force-heading)
5370 (save-excursion
5371 (org-back-to-heading)
5372 (outline-previous-heading)
5373 (looking-at org-todo-line-regexp))
5374 (let*
5375 ((new-mark-x
5376 (if (or arg
5377 (not (match-beginning 2))
5378 (member (match-string 2) org-done-keywords))
5379 (car org-todo-keywords-1)
5380 (match-string 2)))
5381 (new-mark
5383 (run-hook-with-args-until-success
5384 'org-todo-get-default-hook new-mark-x nil)
5385 new-mark-x)))
5386 (beginning-of-line 1)
5387 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5388 (insert new-mark " ")))
5389 (when org-provide-todo-statistics
5390 (org-update-parent-todo-statistics))))
5392 (defun org-insert-subheading (arg)
5393 "Insert a new subheading and demote it.
5394 Works for outline headings and for plain lists alike."
5395 (interactive "P")
5396 (org-insert-heading arg)
5397 (cond
5398 ((org-on-heading-p) (org-do-demote))
5399 ((org-at-item-p) (org-indent-item 1))))
5401 (defun org-insert-todo-subheading (arg)
5402 "Insert a new subheading with TODO keyword or checkbox and demote it.
5403 Works for outline headings and for plain lists alike."
5404 (interactive "P")
5405 (org-insert-todo-heading arg)
5406 (cond
5407 ((org-on-heading-p) (org-do-demote))
5408 ((org-at-item-p) (org-indent-item 1))))
5410 ;;; Promotion and Demotion
5412 (defun org-promote-subtree ()
5413 "Promote the entire subtree.
5414 See also `org-promote'."
5415 (interactive)
5416 (save-excursion
5417 (org-map-tree 'org-promote))
5418 (org-fix-position-after-promote))
5420 (defun org-demote-subtree ()
5421 "Demote the entire subtree. See `org-demote'.
5422 See also `org-promote'."
5423 (interactive)
5424 (save-excursion
5425 (org-map-tree 'org-demote))
5426 (org-fix-position-after-promote))
5429 (defun org-do-promote ()
5430 "Promote the current heading higher up the tree.
5431 If the region is active in `transient-mark-mode', promote all headings
5432 in the region."
5433 (interactive)
5434 (save-excursion
5435 (if (org-region-active-p)
5436 (org-map-region 'org-promote (region-beginning) (region-end))
5437 (org-promote)))
5438 (org-fix-position-after-promote))
5440 (defun org-do-demote ()
5441 "Demote the current heading lower down the tree.
5442 If the region is active in `transient-mark-mode', demote all headings
5443 in the region."
5444 (interactive)
5445 (save-excursion
5446 (if (org-region-active-p)
5447 (org-map-region 'org-demote (region-beginning) (region-end))
5448 (org-demote)))
5449 (org-fix-position-after-promote))
5451 (defun org-fix-position-after-promote ()
5452 "Make sure that after pro/demotion cursor position is right."
5453 (let ((pos (point)))
5454 (when (save-excursion
5455 (beginning-of-line 1)
5456 (looking-at org-todo-line-regexp)
5457 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5458 (cond ((eobp) (insert " "))
5459 ((eolp) (insert " "))
5460 ((equal (char-after) ?\ ) (forward-char 1))))))
5462 (defun org-reduced-level (l)
5463 "Compute the effective level of a heading.
5464 This takes into account the setting of `org-odd-levels-only'."
5465 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5467 (defun org-get-valid-level (level &optional change)
5468 "Rectify a level change under the influence of `org-odd-levels-only'
5469 LEVEL is a current level, CHANGE is by how much the level should be
5470 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5471 even level numbers will become the next higher odd number."
5472 (if org-odd-levels-only
5473 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5474 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5475 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5476 (max 1 (+ level (or change 0)))))
5478 (if (boundp 'define-obsolete-function-alias)
5479 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5480 (define-obsolete-function-alias 'org-get-legal-level
5481 'org-get-valid-level)
5482 (define-obsolete-function-alias 'org-get-legal-level
5483 'org-get-valid-level "23.1")))
5485 (defun org-promote ()
5486 "Promote the current heading higher up the tree.
5487 If the region is active in `transient-mark-mode', promote all headings
5488 in the region."
5489 (org-back-to-heading t)
5490 (let* ((level (save-match-data (funcall outline-level)))
5491 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5492 (diff (abs (- level (length up-head) -1))))
5493 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5494 (replace-match up-head nil t)
5495 ;; Fixup tag positioning
5496 (and org-auto-align-tags (org-set-tags nil t))
5497 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5499 (defun org-demote ()
5500 "Demote the current heading lower down the tree.
5501 If the region is active in `transient-mark-mode', demote all headings
5502 in the region."
5503 (org-back-to-heading t)
5504 (let* ((level (save-match-data (funcall outline-level)))
5505 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5506 (diff (abs (- level (length down-head) -1))))
5507 (replace-match down-head nil t)
5508 ;; Fixup tag positioning
5509 (and org-auto-align-tags (org-set-tags nil t))
5510 (if org-adapt-indentation (org-fixup-indentation diff))))
5512 (defun org-map-tree (fun)
5513 "Call FUN for every heading underneath the current one."
5514 (org-back-to-heading)
5515 (let ((level (funcall outline-level)))
5516 (save-excursion
5517 (funcall fun)
5518 (while (and (progn
5519 (outline-next-heading)
5520 (> (funcall outline-level) level))
5521 (not (eobp)))
5522 (funcall fun)))))
5524 (defun org-map-region (fun beg end)
5525 "Call FUN for every heading between BEG and END."
5526 (let ((org-ignore-region t))
5527 (save-excursion
5528 (setq end (copy-marker end))
5529 (goto-char beg)
5530 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5531 (< (point) end))
5532 (funcall fun))
5533 (while (and (progn
5534 (outline-next-heading)
5535 (< (point) end))
5536 (not (eobp)))
5537 (funcall fun)))))
5539 (defun org-fixup-indentation (diff)
5540 "Change the indentation in the current entry by DIFF
5541 However, if any line in the current entry has no indentation, or if it
5542 would end up with no indentation after the change, nothing at all is done."
5543 (save-excursion
5544 (let ((end (save-excursion (outline-next-heading)
5545 (point-marker)))
5546 (prohibit (if (> diff 0)
5547 "^\\S-"
5548 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5549 col)
5550 (unless (save-excursion (end-of-line 1)
5551 (re-search-forward prohibit end t))
5552 (while (and (< (point) end)
5553 (re-search-forward "^[ \t]+" end t))
5554 (goto-char (match-end 0))
5555 (setq col (current-column))
5556 (if (< diff 0) (replace-match ""))
5557 (org-indent-to-column (+ diff col))))
5558 (move-marker end nil))))
5560 (defun org-convert-to-odd-levels ()
5561 "Convert an org-mode file with all levels allowed to one with odd levels.
5562 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5563 level 5 etc."
5564 (interactive)
5565 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5566 (let ((org-odd-levels-only nil) n)
5567 (save-excursion
5568 (goto-char (point-min))
5569 (while (re-search-forward "^\\*\\*+ " nil t)
5570 (setq n (- (length (match-string 0)) 2))
5571 (while (>= (setq n (1- n)) 0)
5572 (org-demote))
5573 (end-of-line 1))))))
5576 (defun org-convert-to-oddeven-levels ()
5577 "Convert an org-mode file with only odd levels to one with odd and even levels.
5578 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5579 section with an even level, conversion would destroy the structure of the file. An error
5580 is signaled in this case."
5581 (interactive)
5582 (goto-char (point-min))
5583 ;; First check if there are no even levels
5584 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5585 (org-show-context t)
5586 (error "Not all levels are odd in this file. Conversion not possible."))
5587 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5588 (let ((org-odd-levels-only nil) n)
5589 (save-excursion
5590 (goto-char (point-min))
5591 (while (re-search-forward "^\\*\\*+ " nil t)
5592 (setq n (/ (1- (length (match-string 0))) 2))
5593 (while (>= (setq n (1- n)) 0)
5594 (org-promote))
5595 (end-of-line 1))))))
5597 (defun org-tr-level (n)
5598 "Make N odd if required."
5599 (if org-odd-levels-only (1+ (/ n 2)) n))
5601 ;;; Vertical tree motion, cutting and pasting of subtrees
5603 (defun org-move-subtree-up (&optional arg)
5604 "Move the current subtree up past ARG headlines of the same level."
5605 (interactive "p")
5606 (org-move-subtree-down (- (prefix-numeric-value arg))))
5608 (defun org-move-subtree-down (&optional arg)
5609 "Move the current subtree down past ARG headlines of the same level."
5610 (interactive "p")
5611 (setq arg (prefix-numeric-value arg))
5612 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5613 'outline-get-last-sibling))
5614 (ins-point (make-marker))
5615 (cnt (abs arg))
5616 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5617 ;; Select the tree
5618 (org-back-to-heading)
5619 (setq beg0 (point))
5620 (save-excursion
5621 (setq ne-beg (org-back-over-empty-lines))
5622 (setq beg (point)))
5623 (save-match-data
5624 (save-excursion (outline-end-of-heading)
5625 (setq folded (org-invisible-p)))
5626 (outline-end-of-subtree))
5627 (outline-next-heading)
5628 (setq ne-end (org-back-over-empty-lines))
5629 (setq end (point))
5630 (goto-char beg0)
5631 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5632 ;; include less whitespace
5633 (save-excursion
5634 (goto-char beg)
5635 (forward-line (- ne-beg ne-end))
5636 (setq beg (point))))
5637 ;; Find insertion point, with error handling
5638 (while (> cnt 0)
5639 (or (and (funcall movfunc) (looking-at outline-regexp))
5640 (progn (goto-char beg0)
5641 (error "Cannot move past superior level or buffer limit")))
5642 (setq cnt (1- cnt)))
5643 (if (> arg 0)
5644 ;; Moving forward - still need to move over subtree
5645 (progn (org-end-of-subtree t t)
5646 (save-excursion
5647 (org-back-over-empty-lines)
5648 (or (bolp) (newline)))))
5649 (setq ne-ins (org-back-over-empty-lines))
5650 (move-marker ins-point (point))
5651 (setq txt (buffer-substring beg end))
5652 (org-save-markers-in-region beg end)
5653 (delete-region beg end)
5654 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5655 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5656 (and (not (bolp)) (looking-at "\n") (forward-char 1))
5657 (let ((bbb (point)))
5658 (insert-before-markers txt)
5659 (org-reinstall-markers-in-region bbb)
5660 (move-marker ins-point bbb))
5661 (or (bolp) (insert "\n"))
5662 (setq ins-end (point))
5663 (goto-char ins-point)
5664 (org-skip-whitespace)
5665 (when (and (< arg 0)
5666 (org-first-sibling-p)
5667 (> ne-ins ne-beg))
5668 ;; Move whitespace back to beginning
5669 (save-excursion
5670 (goto-char ins-end)
5671 (let ((kill-whole-line t))
5672 (kill-line (- ne-ins ne-beg)) (point)))
5673 (insert (make-string (- ne-ins ne-beg) ?\n)))
5674 (move-marker ins-point nil)
5675 (org-compact-display-after-subtree-move)
5676 (org-show-empty-lines-in-parent)
5677 (unless folded
5678 (org-show-entry)
5679 (show-children)
5680 (org-cycle-hide-drawers 'children))))
5682 (defvar org-subtree-clip ""
5683 "Clipboard for cut and paste of subtrees.
5684 This is actually only a copy of the kill, because we use the normal kill
5685 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5687 (defvar org-subtree-clip-folded nil
5688 "Was the last copied subtree folded?
5689 This is used to fold the tree back after pasting.")
5691 (defun org-cut-subtree (&optional n)
5692 "Cut the current subtree into the clipboard.
5693 With prefix arg N, cut this many sequential subtrees.
5694 This is a short-hand for marking the subtree and then cutting it."
5695 (interactive "p")
5696 (org-copy-subtree n 'cut))
5698 (defun org-copy-subtree (&optional n cut force-store-markers)
5699 "Cut the current subtree into the clipboard.
5700 With prefix arg N, cut this many sequential subtrees.
5701 This is a short-hand for marking the subtree and then copying it.
5702 If CUT is non-nil, actually cut the subtree.
5703 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5704 of some markers in the region, even if CUT is non-nil. This is
5705 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5706 (interactive "p")
5707 (let (beg end folded (beg0 (point)))
5708 (if (interactive-p)
5709 (org-back-to-heading nil) ; take what looks like a subtree
5710 (org-back-to-heading t)) ; take what is really there
5711 (org-back-over-empty-lines)
5712 (setq beg (point))
5713 (skip-chars-forward " \t\r\n")
5714 (save-match-data
5715 (save-excursion (outline-end-of-heading)
5716 (setq folded (org-invisible-p)))
5717 (condition-case nil
5718 (outline-forward-same-level (1- n))
5719 (error nil))
5720 (org-end-of-subtree t t))
5721 (org-back-over-empty-lines)
5722 (setq end (point))
5723 (goto-char beg0)
5724 (when (> end beg)
5725 (setq org-subtree-clip-folded folded)
5726 (when (or cut force-store-markers)
5727 (org-save-markers-in-region beg end))
5728 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5729 (setq org-subtree-clip (current-kill 0))
5730 (message "%s: Subtree(s) with %d characters"
5731 (if cut "Cut" "Copied")
5732 (length org-subtree-clip)))))
5734 (defun org-paste-subtree (&optional level tree for-yank)
5735 "Paste the clipboard as a subtree, with modification of headline level.
5736 The entire subtree is promoted or demoted in order to match a new headline
5737 level.
5739 If the cursor is at the beginning of a headline, the same level as
5740 that headline is used to paste the tree
5742 If not, the new level is derived from the *visible* headings
5743 before and after the insertion point, and taken to be the inferior headline
5744 level of the two. So if the previous visible heading is level 3 and the
5745 next is level 4 (or vice versa), level 4 will be used for insertion.
5746 This makes sure that the subtree remains an independent subtree and does
5747 not swallow low level entries.
5749 You can also force a different level, either by using a numeric prefix
5750 argument, or by inserting the heading marker by hand. For example, if the
5751 cursor is after \"*****\", then the tree will be shifted to level 5.
5753 If optional TREE is given, use this text instead of the kill ring.
5755 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5756 move back over whitespace before inserting, and move point to the end of
5757 the inserted text when done."
5758 (interactive "P")
5759 (unless (org-kill-is-subtree-p tree)
5760 (error "%s"
5761 (substitute-command-keys
5762 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5763 (let* ((visp (not (org-invisible-p)))
5764 (txt (or tree (and kill-ring (current-kill 0))))
5765 (^re (concat "^\\(" outline-regexp "\\)"))
5766 (re (concat "\\(" outline-regexp "\\)"))
5767 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5769 (old-level (if (string-match ^re txt)
5770 (- (match-end 0) (match-beginning 0) 1)
5771 -1))
5772 (force-level (cond (level (prefix-numeric-value level))
5773 ((and (looking-at "[ \t]*$")
5774 (string-match
5775 ^re_ (buffer-substring
5776 (point-at-bol) (point))))
5777 (- (match-end 1) (match-beginning 1)))
5778 ((and (bolp)
5779 (looking-at org-outline-regexp))
5780 (- (match-end 0) (point) 1))
5781 (t nil)))
5782 (previous-level (save-excursion
5783 (condition-case nil
5784 (progn
5785 (outline-previous-visible-heading 1)
5786 (if (looking-at re)
5787 (- (match-end 0) (match-beginning 0) 1)
5789 (error 1))))
5790 (next-level (save-excursion
5791 (condition-case nil
5792 (progn
5793 (or (looking-at outline-regexp)
5794 (outline-next-visible-heading 1))
5795 (if (looking-at re)
5796 (- (match-end 0) (match-beginning 0) 1)
5798 (error 1))))
5799 (new-level (or force-level (max previous-level next-level)))
5800 (shift (if (or (= old-level -1)
5801 (= new-level -1)
5802 (= old-level new-level))
5804 (- new-level old-level)))
5805 (delta (if (> shift 0) -1 1))
5806 (func (if (> shift 0) 'org-demote 'org-promote))
5807 (org-odd-levels-only nil)
5808 beg end newend)
5809 ;; Remove the forced level indicator
5810 (if force-level
5811 (delete-region (point-at-bol) (point)))
5812 ;; Paste
5813 (beginning-of-line 1)
5814 (unless for-yank (org-back-over-empty-lines))
5815 (setq beg (point))
5816 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5817 (insert-before-markers txt)
5818 (unless (string-match "\n\\'" txt) (insert "\n"))
5819 (setq newend (point))
5820 (org-reinstall-markers-in-region beg)
5821 (setq end (point))
5822 (goto-char beg)
5823 (skip-chars-forward " \t\n\r")
5824 (setq beg (point))
5825 (if (and (org-invisible-p) visp)
5826 (save-excursion (outline-show-heading)))
5827 ;; Shift if necessary
5828 (unless (= shift 0)
5829 (save-restriction
5830 (narrow-to-region beg end)
5831 (while (not (= shift 0))
5832 (org-map-region func (point-min) (point-max))
5833 (setq shift (+ delta shift)))
5834 (goto-char (point-min))
5835 (setq newend (point-max))))
5836 (when (or (interactive-p) for-yank)
5837 (message "Clipboard pasted as level %d subtree" new-level))
5838 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5839 kill-ring
5840 (eq org-subtree-clip (current-kill 0))
5841 org-subtree-clip-folded)
5842 ;; The tree was folded before it was killed/copied
5843 (hide-subtree))
5844 (and for-yank (goto-char newend))))
5846 (defun org-kill-is-subtree-p (&optional txt)
5847 "Check if the current kill is an outline subtree, or a set of trees.
5848 Returns nil if kill does not start with a headline, or if the first
5849 headline level is not the largest headline level in the tree.
5850 So this will actually accept several entries of equal levels as well,
5851 which is OK for `org-paste-subtree'.
5852 If optional TXT is given, check this string instead of the current kill."
5853 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5854 (start-level (and kill
5855 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5856 org-outline-regexp "\\)")
5857 kill)
5858 (- (match-end 2) (match-beginning 2) 1)))
5859 (re (concat "^" org-outline-regexp))
5860 (start (1+ (or (match-beginning 2) -1))))
5861 (if (not start-level)
5862 (progn
5863 nil) ;; does not even start with a heading
5864 (catch 'exit
5865 (while (setq start (string-match re kill (1+ start)))
5866 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5867 (throw 'exit nil)))
5868 t))))
5870 (defvar org-markers-to-move nil
5871 "Markers that should be moved with a cut-and-paste operation.
5872 Those markers are stored together with their positions relative to
5873 the start of the region.")
5875 (defun org-save-markers-in-region (beg end)
5876 "Check markers in region.
5877 If these markers are between BEG and END, record their position relative
5878 to BEG, so that after moving the block of text, we can put the markers back
5879 into place.
5880 This function gets called just before an entry or tree gets cut from the
5881 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5882 called immediately, to move the markers with the entries."
5883 (setq org-markers-to-move nil)
5884 (when (featurep 'org-clock)
5885 (org-clock-save-markers-for-cut-and-paste beg end))
5886 (when (featurep 'org-agenda)
5887 (org-agenda-save-markers-for-cut-and-paste beg end)))
5889 (defun org-check-and-save-marker (marker beg end)
5890 "Check if MARKER is between BEG and END.
5891 If yes, remember the marker and the distance to BEG."
5892 (when (and (marker-buffer marker)
5893 (equal (marker-buffer marker) (current-buffer)))
5894 (if (and (>= marker beg) (< marker end))
5895 (push (cons marker (- marker beg)) org-markers-to-move))))
5897 (defun org-reinstall-markers-in-region (beg)
5898 "Move all remembered markers to their position relative to BEG."
5899 (mapc (lambda (x)
5900 (move-marker (car x) (+ beg (cdr x))))
5901 org-markers-to-move)
5902 (setq org-markers-to-move nil))
5904 (defun org-narrow-to-subtree ()
5905 "Narrow buffer to the current subtree."
5906 (interactive)
5907 (save-excursion
5908 (save-match-data
5909 (narrow-to-region
5910 (progn (org-back-to-heading) (point))
5911 (progn (org-end-of-subtree t) (point))))))
5913 (defun org-clone-subtree-with-time-shift (n &optional shift)
5914 "Clone the task (subtree) at point N times.
5915 The clones will be inserted as siblings.
5917 In interactive use, the user will be prompted for the number of clones
5918 to be produced, and for a time SHIFT, which may be a repeater as used
5919 in time stamps, for example `+3d'.
5921 When a valid repeater is given and the entry contains any time stamps,
5922 the clones will become a sequence in time, with time stamps in the
5923 subtree shifted for each clone produced. If SHIFT is nil or the
5924 empty string, time stamps will be left alone.
5926 If the original subtree did contain time stamps with a repeater,
5927 the following will happen:
5928 - the repeater will be removed in each clone
5929 - an additional clone will be produced, with the current, unshifted
5930 date(s) in the entry.
5931 - the original entry will be placed *after* all the clones, with
5932 repeater intact.
5933 - the start days in the repeater in the original entry will be shifted
5934 to past the last clone.
5935 I this way you can spell out a number of instances of a repeating task,
5936 and still retain the repeater to cover future instances of the task."
5937 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
5938 (let (beg end template task
5939 shift-n shift-what doshift nmin nmax (n-no-remove -1))
5940 (if (not (and (integerp n) (> n 0)))
5941 (error "Invalid number of replications %s" n))
5942 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
5943 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
5944 shift)))
5945 (error "Invalid shift specification %s" shift))
5946 (when doshift
5947 (setq shift-n (string-to-number (match-string 1 shift))
5948 shift-what (cdr (assoc (match-string 2 shift)
5949 '(("d" . day) ("w" . week)
5950 ("m" . month) ("y" . year))))))
5951 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
5952 (setq nmin 1 nmax n)
5953 (org-back-to-heading t)
5954 (setq beg (point))
5955 (org-end-of-subtree t t)
5956 (setq end (point))
5957 (setq template (buffer-substring beg end))
5958 (when (and doshift
5959 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
5960 (delete-region beg end)
5961 (setq end beg)
5962 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
5963 (goto-char end)
5964 (loop for n from nmin to nmax do
5965 (if (not doshift)
5966 (setq task template)
5967 (with-temp-buffer
5968 (insert template)
5969 (org-mode)
5970 (goto-char (point-min))
5971 (while (re-search-forward org-ts-regexp nil t)
5972 (org-timestamp-change (* n shift-n) shift-what))
5973 (unless (= n n-no-remove)
5974 (goto-char (point-min))
5975 (while (re-search-forward org-ts-regexp nil t)
5976 (save-excursion
5977 (goto-char (match-beginning 0))
5978 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
5979 (delete-region (match-beginning 1) (match-end 1))))))
5980 (setq task (buffer-string))))
5981 (insert task))
5982 (goto-char beg)))
5984 ;;; Outline Sorting
5986 (defun org-sort (with-case)
5987 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5988 Optional argument WITH-CASE means sort case-sensitively.
5989 With a double prefix argument, also remove duplicate entries."
5990 (interactive "P")
5991 (if (org-at-table-p)
5992 (org-call-with-arg 'org-table-sort-lines with-case)
5993 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5995 (defun org-sort-remove-invisible (s)
5996 (remove-text-properties 0 (length s) org-rm-props s)
5997 (while (string-match org-bracket-link-regexp s)
5998 (setq s (replace-match (if (match-end 2)
5999 (match-string 3 s)
6000 (match-string 1 s)) t t s)))
6003 (defvar org-priority-regexp) ; defined later in the file
6005 (defun org-sort-entries-or-items
6006 (&optional with-case sorting-type getkey-func compare-func property)
6007 "Sort entries on a certain level of an outline tree.
6008 If there is an active region, the entries in the region are sorted.
6009 Else, if the cursor is before the first entry, sort the top-level items.
6010 Else, the children of the entry at point are sorted.
6012 Sorting can be alphabetically, numerically, and by date/time as given by
6013 the first time stamp in the entry. The command prompts for the sorting
6014 type unless it has been given to the function through the SORTING-TYPE
6015 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6016 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6017 called with point at the beginning of the record. It must return either
6018 a string or a number that should serve as the sorting key for that record.
6020 Comparing entries ignores case by default. However, with an optional argument
6021 WITH-CASE, the sorting considers case as well."
6022 (interactive "P")
6023 (let ((case-func (if with-case 'identity 'downcase))
6024 start beg end stars re re2
6025 txt what tmp plain-list-p)
6026 ;; Find beginning and end of region to sort
6027 (cond
6028 ((org-region-active-p)
6029 ;; we will sort the region
6030 (setq end (region-end)
6031 what "region")
6032 (goto-char (region-beginning))
6033 (if (not (org-on-heading-p)) (outline-next-heading))
6034 (setq start (point)))
6035 ((org-at-item-p)
6036 ;; we will sort this plain list
6037 (org-beginning-of-item-list) (setq start (point))
6038 (org-end-of-item-list) (setq end (point))
6039 (goto-char start)
6040 (setq plain-list-p t
6041 what "plain list"))
6042 ((or (org-on-heading-p)
6043 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6044 ;; we will sort the children of the current headline
6045 (org-back-to-heading)
6046 (setq start (point)
6047 end (progn (org-end-of-subtree t t)
6048 (org-back-over-empty-lines)
6049 (point))
6050 what "children")
6051 (goto-char start)
6052 (show-subtree)
6053 (outline-next-heading))
6055 ;; we will sort the top-level entries in this file
6056 (goto-char (point-min))
6057 (or (org-on-heading-p) (outline-next-heading))
6058 (setq start (point) end (point-max) what "top-level")
6059 (goto-char start)
6060 (show-all)))
6062 (setq beg (point))
6063 (if (>= beg end) (error "Nothing to sort"))
6065 (unless plain-list-p
6066 (looking-at "\\(\\*+\\)")
6067 (setq stars (match-string 1)
6068 re (concat "^" (regexp-quote stars) " +")
6069 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6070 txt (buffer-substring beg end))
6071 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6072 (if (and (not (equal stars "*")) (string-match re2 txt))
6073 (error "Region to sort contains a level above the first entry")))
6075 (unless sorting-type
6076 (message
6077 (if plain-list-p
6078 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6079 "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:")
6080 what)
6081 (setq sorting-type (read-char-exclusive))
6083 (and (= (downcase sorting-type) ?f)
6084 (setq getkey-func
6085 (org-ido-completing-read "Sort using function: "
6086 obarray 'fboundp t nil nil))
6087 (setq getkey-func (intern getkey-func)))
6089 (and (= (downcase sorting-type) ?r)
6090 (setq property
6091 (org-ido-completing-read "Property: "
6092 (mapcar 'list (org-buffer-property-keys t))
6093 nil t))))
6095 (message "Sorting entries...")
6097 (save-restriction
6098 (narrow-to-region start end)
6100 (let ((dcst (downcase sorting-type))
6101 (case-fold-search nil)
6102 (now (current-time)))
6103 (sort-subr
6104 (/= dcst sorting-type)
6105 ;; This function moves to the beginning character of the "record" to
6106 ;; be sorted.
6107 (if plain-list-p
6108 (lambda nil
6109 (if (org-at-item-p) t (goto-char (point-max))))
6110 (lambda nil
6111 (if (re-search-forward re nil t)
6112 (goto-char (match-beginning 0))
6113 (goto-char (point-max)))))
6114 ;; This function moves to the last character of the "record" being
6115 ;; sorted.
6116 (if plain-list-p
6117 'org-end-of-item
6118 (lambda nil
6119 (save-match-data
6120 (condition-case nil
6121 (outline-forward-same-level 1)
6122 (error
6123 (goto-char (point-max)))))))
6125 ;; This function returns the value that gets sorted against.
6126 (if plain-list-p
6127 (lambda nil
6128 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6129 (cond
6130 ((= dcst ?n)
6131 (string-to-number (buffer-substring (match-end 0)
6132 (point-at-eol))))
6133 ((= dcst ?a)
6134 (buffer-substring (match-end 0) (point-at-eol)))
6135 ((= dcst ?t)
6136 (if (re-search-forward org-ts-regexp
6137 (point-at-eol) t)
6138 (org-time-string-to-time (match-string 0))
6139 now))
6140 ((= dcst ?f)
6141 (if getkey-func
6142 (progn
6143 (setq tmp (funcall getkey-func))
6144 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6145 tmp)
6146 (error "Invalid key function `%s'" getkey-func)))
6147 (t (error "Invalid sorting type `%c'" sorting-type)))))
6148 (lambda nil
6149 (cond
6150 ((= dcst ?n)
6151 (if (looking-at org-complex-heading-regexp)
6152 (string-to-number (match-string 4))
6153 nil))
6154 ((= dcst ?a)
6155 (if (looking-at org-complex-heading-regexp)
6156 (funcall case-func (match-string 4))
6157 nil))
6158 ((= dcst ?t)
6159 (if (re-search-forward org-ts-regexp
6160 (save-excursion
6161 (forward-line 2)
6162 (point)) t)
6163 (org-time-string-to-time (match-string 0))
6164 now))
6165 ((= dcst ?p)
6166 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6167 (string-to-char (match-string 2))
6168 org-default-priority))
6169 ((= dcst ?r)
6170 (or (org-entry-get nil property) ""))
6171 ((= dcst ?o)
6172 (if (looking-at org-complex-heading-regexp)
6173 (- 9999 (length (member (match-string 2)
6174 org-todo-keywords-1)))))
6175 ((= dcst ?f)
6176 (if getkey-func
6177 (progn
6178 (setq tmp (funcall getkey-func))
6179 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6180 tmp)
6181 (error "Invalid key function `%s'" getkey-func)))
6182 (t (error "Invalid sorting type `%c'" sorting-type)))))
6184 (cond
6185 ((= dcst ?a) 'string<)
6186 ((= dcst ?t) 'time-less-p)
6187 ((= dcst ?f) compare-func)
6188 (t nil)))))
6189 (message "Sorting entries...done")))
6191 (defun org-do-sort (table what &optional with-case sorting-type)
6192 "Sort TABLE of WHAT according to SORTING-TYPE.
6193 The user will be prompted for the SORTING-TYPE if the call to this
6194 function does not specify it. WHAT is only for the prompt, to indicate
6195 what is being sorted. The sorting key will be extracted from
6196 the car of the elements of the table.
6197 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6198 (unless sorting-type
6199 (message
6200 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6201 what)
6202 (setq sorting-type (read-char-exclusive)))
6203 (let ((dcst (downcase sorting-type))
6204 extractfun comparefun)
6205 ;; Define the appropriate functions
6206 (cond
6207 ((= dcst ?n)
6208 (setq extractfun 'string-to-number
6209 comparefun (if (= dcst sorting-type) '< '>)))
6210 ((= dcst ?a)
6211 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6212 (lambda(x) (downcase (org-sort-remove-invisible x))))
6213 comparefun (if (= dcst sorting-type)
6214 'string<
6215 (lambda (a b) (and (not (string< a b))
6216 (not (string= a b)))))))
6217 ((= dcst ?t)
6218 (setq extractfun
6219 (lambda (x)
6220 (if (or (string-match org-ts-regexp x)
6221 (string-match org-ts-regexp-both x))
6222 (time-to-seconds
6223 (org-time-string-to-time (match-string 0 x)))
6225 comparefun (if (= dcst sorting-type) '< '>)))
6226 (t (error "Invalid sorting type `%c'" sorting-type)))
6228 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6229 table)
6230 (lambda (a b) (funcall comparefun (car a) (car b))))))
6232 ;;; Editing source examples
6234 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6235 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6236 (defvar org-edit-src-force-single-line nil)
6237 (defvar org-edit-src-from-org-mode nil)
6238 (defvar org-edit-src-picture nil)
6240 (define-minor-mode org-exit-edit-mode
6241 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6243 (defun org-edit-src-code ()
6244 "Edit the source code example at point.
6245 An indirect buffer is created, and that buffer is then narrowed to the
6246 example at point and switched to the correct language mode. When done,
6247 exit by killing the buffer with \\[org-edit-src-exit]."
6248 (interactive)
6249 (let ((line (org-current-line))
6250 (case-fold-search t)
6251 (msg (substitute-command-keys
6252 "Edit, then exit with C-c ' (C-c and single quote)"))
6253 (info (org-edit-src-find-region-and-lang))
6254 (org-mode-p (eq major-mode 'org-mode))
6255 beg end lang lang-f single lfmt)
6256 (if (not info)
6258 (setq beg (nth 0 info)
6259 end (nth 1 info)
6260 lang (nth 2 info)
6261 single (nth 3 info)
6262 lfmt (nth 4 info)
6263 lang-f (intern (concat lang "-mode")))
6264 (unless (functionp lang-f)
6265 (error "No such language mode: %s" lang-f))
6266 (goto-line line)
6267 (if (get-buffer "*Org Edit Src Example*")
6268 (kill-buffer "*Org Edit Src Example*"))
6269 (switch-to-buffer (make-indirect-buffer (current-buffer)
6270 "*Org Edit Src Example*"))
6271 (narrow-to-region beg end)
6272 (remove-text-properties beg end '(display nil invisible nil
6273 intangible nil))
6274 (let ((org-inhibit-startup t))
6275 (funcall lang-f))
6276 (set (make-local-variable 'org-edit-src-force-single-line) single)
6277 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6278 (when lfmt
6279 (set (make-local-variable 'org-coderef-label-format) lfmt))
6280 (when org-mode-p
6281 (goto-char (point-min))
6282 (while (re-search-forward "^," nil t)
6283 (replace-match "")))
6284 (goto-line line)
6285 (org-exit-edit-mode)
6286 (org-set-local 'header-line-format msg)
6287 (message "%s" msg)
6288 t)))
6290 (defun org-edit-fixed-width-region ()
6291 "Edit the fixed-width ascii drawing at point.
6292 This must be a region where each line starts with a colon followed by
6293 a space character.
6294 An indirect buffer is created, and that buffer is then narrowed to the
6295 example at point and switched to artist-mode. When done,
6296 exit by killing the buffer with \\[org-edit-src-exit]."
6297 (interactive)
6298 (let ((line (org-current-line))
6299 (case-fold-search t)
6300 (msg (substitute-command-keys
6301 "Edit, then exit with C-c ' (C-c and single quote)"))
6302 (org-mode-p (eq major-mode 'org-mode))
6303 beg end)
6304 (beginning-of-line 1)
6305 (if (looking-at "[ \t]*[^:\n \t]")
6307 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6308 (setq beg (point) end beg)
6309 (save-excursion
6310 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6311 (setq beg (point-at-bol 2))
6312 (setq beg (point))))
6313 (save-excursion
6314 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6315 (setq end (1- (match-beginning 0)))
6316 (setq end (point))))
6317 (goto-line line))
6318 (if (get-buffer "*Org Edit Picture*")
6319 (kill-buffer "*Org Edit Picture*"))
6320 (switch-to-buffer (make-indirect-buffer (current-buffer)
6321 "*Org Edit Picture*"))
6322 (narrow-to-region beg end)
6323 (remove-text-properties beg end '(display nil invisible nil
6324 intangible nil))
6325 (when (fboundp 'font-lock-unfontify-region)
6326 (font-lock-unfontify-region (point-min) (point-max)))
6327 (cond
6328 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6329 (fundamental-mode)
6330 (artist-mode 1))
6331 (t (funcall org-edit-fixed-width-region-mode)))
6332 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6333 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6334 (set (make-local-variable 'org-edit-src-picture) t)
6335 (goto-char (point-min))
6336 (while (re-search-forward "^[ \t]*: ?" nil t)
6337 (replace-match ""))
6338 (goto-line line)
6339 (org-exit-edit-mode)
6340 (org-set-local 'header-line-format msg)
6341 (message "%s" msg)
6342 t)))
6345 (defun org-edit-src-find-region-and-lang ()
6346 "Find the region and language for a local edit.
6347 Return a list with beginning and end of the region, a string representing
6348 the language, a switch telling of the content should be in a single line."
6349 (let ((re-list
6350 (append
6351 org-edit-src-region-extra
6353 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6354 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6355 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6356 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6357 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6358 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6359 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6360 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6361 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6362 ("^#\\+html:" "\n" "html" single-line)
6363 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6364 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6365 ("^#\\+latex:" "\n" "latex" single-line)
6366 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6367 ("^#\\+ascii:" "\n" "ascii" single-line)
6369 (pos (point))
6370 re1 re2 single beg end lang lfmt match-re1)
6371 (catch 'exit
6372 (while (setq entry (pop re-list))
6373 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6374 single (nth 3 entry))
6375 (save-excursion
6376 (if (or (looking-at re1)
6377 (re-search-backward re1 nil t))
6378 (progn
6379 (setq match-re1 (match-string 0))
6380 (setq beg (match-end 0)
6381 lang (org-edit-src-get-lang lang)
6382 lfmt (org-edit-src-get-label-format match-re1))
6383 (if (and (re-search-forward re2 nil t)
6384 (>= (match-end 0) pos))
6385 (throw 'exit (list beg (match-beginning 0)
6386 lang single lfmt))))
6387 (if (or (looking-at re2)
6388 (re-search-forward re2 nil t))
6389 (progn
6390 (setq end (match-beginning 0))
6391 (if (and (re-search-backward re1 nil t)
6392 (<= (match-beginning 0) pos))
6393 (progn
6394 (setq lfmt (org-edit-src-get-label-format
6395 (match-string 0)))
6396 (throw 'exit
6397 (list (match-end 0) end
6398 (org-edit-src-get-lang lang)
6399 single lfmt))))))))))))
6401 (defun org-edit-src-get-lang (lang)
6402 "Extract the src language."
6403 (let ((m (match-string 0)))
6404 (cond
6405 ((stringp lang) lang)
6406 ((integerp lang) (match-string lang))
6407 ((and (eq lang 'lang)
6408 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6409 (match-string 1 m))
6410 ((and (eq lang 'style)
6411 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6412 (match-string 1 m))
6413 (t "fundamental"))))
6415 (defun org-edit-src-get-label-format (s)
6416 "Extract the label format."
6417 (save-match-data
6418 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6419 (match-string 1 s))))
6421 (defun org-edit-src-exit ()
6422 "Exit special edit and protect problematic lines."
6423 (interactive)
6424 (unless (buffer-base-buffer (current-buffer))
6425 (error "This is not an indirect buffer, something is wrong..."))
6426 (unless (> (point-min) 1)
6427 (error "This buffer is not narrowed, something is wrong..."))
6428 (goto-char (point-min))
6429 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6430 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6431 (when (org-bound-and-true-p org-edit-src-force-single-line)
6432 (goto-char (point-min))
6433 (while (re-search-forward "\n" nil t)
6434 (replace-match " "))
6435 (goto-char (point-min))
6436 (if (looking-at "\\s-*") (replace-match " "))
6437 (if (re-search-forward "\\s-+\\'" nil t)
6438 (replace-match "")))
6439 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6440 (goto-char (point-min))
6441 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6442 (replace-match ",\\1"))
6443 (when font-lock-mode
6444 (font-lock-unfontify-region (point-min) (point-max)))
6445 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6446 (when (org-bound-and-true-p org-edit-src-picture)
6447 (untabify (point-min) (point-max))
6448 (goto-char (point-min))
6449 (while (re-search-forward "^" nil t)
6450 (replace-match ": "))
6451 (when font-lock-mode
6452 (font-lock-unfontify-region (point-min) (point-max)))
6453 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6454 (kill-buffer (current-buffer))
6455 (and (org-mode-p) (org-restart-font-lock)))
6458 ;;; The orgstruct minor mode
6460 ;; Define a minor mode which can be used in other modes in order to
6461 ;; integrate the org-mode structure editing commands.
6463 ;; This is really a hack, because the org-mode structure commands use
6464 ;; keys which normally belong to the major mode. Here is how it
6465 ;; works: The minor mode defines all the keys necessary to operate the
6466 ;; structure commands, but wraps the commands into a function which
6467 ;; tests if the cursor is currently at a headline or a plain list
6468 ;; item. If that is the case, the structure command is used,
6469 ;; temporarily setting many Org-mode variables like regular
6470 ;; expressions for filling etc. However, when any of those keys is
6471 ;; used at a different location, function uses `key-binding' to look
6472 ;; up if the key has an associated command in another currently active
6473 ;; keymap (minor modes, major mode, global), and executes that
6474 ;; command. There might be problems if any of the keys is otherwise
6475 ;; used as a prefix key.
6477 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6478 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6479 ;; addresses this by checking explicitly for both bindings.
6481 (defvar orgstruct-mode-map (make-sparse-keymap)
6482 "Keymap for the minor `orgstruct-mode'.")
6484 (defvar org-local-vars nil
6485 "List of local variables, for use by `orgstruct-mode'")
6487 ;;;###autoload
6488 (define-minor-mode orgstruct-mode
6489 "Toggle the minor more `orgstruct-mode'.
6490 This mode is for using Org-mode structure commands in other modes.
6491 The following key behave as if Org-mode was active, if the cursor
6492 is on a headline, or on a plain list item (both in the definition
6493 of Org-mode).
6495 M-up Move entry/item up
6496 M-down Move entry/item down
6497 M-left Promote
6498 M-right Demote
6499 M-S-up Move entry/item up
6500 M-S-down Move entry/item down
6501 M-S-left Promote subtree
6502 M-S-right Demote subtree
6503 M-q Fill paragraph and items like in Org-mode
6504 C-c ^ Sort entries
6505 C-c - Cycle list bullet
6506 TAB Cycle item visibility
6507 M-RET Insert new heading/item
6508 S-M-RET Insert new TODO heading / Checkbox item
6509 C-c C-c Set tags / toggle checkbox"
6510 nil " OrgStruct" nil
6511 (org-load-modules-maybe)
6512 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6514 ;;;###autoload
6515 (defun turn-on-orgstruct ()
6516 "Unconditionally turn on `orgstruct-mode'."
6517 (orgstruct-mode 1))
6519 (defun orgstruct++-mode (&optional arg)
6520 "Toggle `orgstruct-mode', the enhanced version of it.
6521 In addition to setting orgstruct-mode, this also exports all indentation and
6522 autofilling variables from org-mode into the buffer. It will also
6523 recognize item context in multiline items.
6524 Note that turning off orgstruct-mode will *not* remove the
6525 indentation/paragraph settings. This can only be done by refreshing the
6526 major mode, for example with \[normal-mode]."
6527 (interactive "P")
6528 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6529 (if (< arg 1)
6530 (orgstruct-mode -1)
6531 (orgstruct-mode 1)
6532 (let (var val)
6533 (mapc
6534 (lambda (x)
6535 (when (string-match
6536 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6537 (symbol-name (car x)))
6538 (setq var (car x) val (nth 1 x))
6539 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6540 org-local-vars)
6541 (org-set-local 'orgstruct-is-++ t))))
6543 (defvar orgstruct-is-++ nil
6544 "Is orgstruct-mode in ++ version in the current-buffer?")
6545 (make-variable-buffer-local 'orgstruct-is-++)
6547 ;;;###autoload
6548 (defun turn-on-orgstruct++ ()
6549 "Unconditionally turn on `orgstruct++-mode'."
6550 (orgstruct++-mode 1))
6552 (defun orgstruct-error ()
6553 "Error when there is no default binding for a structure key."
6554 (interactive)
6555 (error "This key has no function outside structure elements"))
6557 (defun orgstruct-setup ()
6558 "Setup orgstruct keymaps."
6559 (let ((nfunc 0)
6560 (bindings
6561 (list
6562 '([(meta up)] org-metaup)
6563 '([(meta down)] org-metadown)
6564 '([(meta left)] org-metaleft)
6565 '([(meta right)] org-metaright)
6566 '([(meta shift up)] org-shiftmetaup)
6567 '([(meta shift down)] org-shiftmetadown)
6568 '([(meta shift left)] org-shiftmetaleft)
6569 '([(meta shift right)] org-shiftmetaright)
6570 '([(shift up)] org-shiftup)
6571 '([(shift down)] org-shiftdown)
6572 '([(shift left)] org-shiftleft)
6573 '([(shift right)] org-shiftright)
6574 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6575 '("\M-q" fill-paragraph)
6576 '("\C-c^" org-sort)
6577 '("\C-c-" org-cycle-list-bullet)))
6578 elt key fun cmd)
6579 (while (setq elt (pop bindings))
6580 (setq nfunc (1+ nfunc))
6581 (setq key (org-key (car elt))
6582 fun (nth 1 elt)
6583 cmd (orgstruct-make-binding fun nfunc key))
6584 (org-defkey orgstruct-mode-map key cmd))
6586 ;; Special treatment needed for TAB and RET
6587 (org-defkey orgstruct-mode-map [(tab)]
6588 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6589 (org-defkey orgstruct-mode-map "\C-i"
6590 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6592 (org-defkey orgstruct-mode-map "\M-\C-m"
6593 (orgstruct-make-binding 'org-insert-heading 105
6594 "\M-\C-m" [(meta return)]))
6595 (org-defkey orgstruct-mode-map [(meta return)]
6596 (orgstruct-make-binding 'org-insert-heading 106
6597 [(meta return)] "\M-\C-m"))
6599 (org-defkey orgstruct-mode-map [(shift meta return)]
6600 (orgstruct-make-binding 'org-insert-todo-heading 107
6601 [(meta return)] "\M-\C-m"))
6603 (unless org-local-vars
6604 (setq org-local-vars (org-get-local-variables)))
6608 (defun orgstruct-make-binding (fun n &rest keys)
6609 "Create a function for binding in the structure minor mode.
6610 FUN is the command to call inside a table. N is used to create a unique
6611 command name. KEYS are keys that should be checked in for a command
6612 to execute outside of tables."
6613 (eval
6614 (list 'defun
6615 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6616 '(arg)
6617 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6618 "Outside of structure, run the binding of `"
6619 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6620 "'.")
6621 '(interactive "p")
6622 (list 'if
6623 `(org-context-p 'headline 'item
6624 (and orgstruct-is-++
6625 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6626 'item-body))
6627 (list 'org-run-like-in-org-mode (list 'quote fun))
6628 (list 'let '(orgstruct-mode)
6629 (list 'call-interactively
6630 (append '(or)
6631 (mapcar (lambda (k)
6632 (list 'key-binding k))
6633 keys)
6634 '('orgstruct-error))))))))
6636 (defun org-context-p (&rest contexts)
6637 "Check if local context is any of CONTEXTS.
6638 Possible values in the list of contexts are `table', `headline', and `item'."
6639 (let ((pos (point)))
6640 (goto-char (point-at-bol))
6641 (prog1 (or (and (memq 'table contexts)
6642 (looking-at "[ \t]*|"))
6643 (and (memq 'headline contexts)
6644 ;;????????? (looking-at "\\*+"))
6645 (looking-at outline-regexp))
6646 (and (memq 'item contexts)
6647 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6648 (and (memq 'item-body contexts)
6649 (org-in-item-p)))
6650 (goto-char pos))))
6652 (defun org-get-local-variables ()
6653 "Return a list of all local variables in an org-mode buffer."
6654 (let (varlist)
6655 (with-current-buffer (get-buffer-create "*Org tmp*")
6656 (erase-buffer)
6657 (org-mode)
6658 (setq varlist (buffer-local-variables)))
6659 (kill-buffer "*Org tmp*")
6660 (delq nil
6661 (mapcar
6662 (lambda (x)
6663 (setq x
6664 (if (symbolp x)
6665 (list x)
6666 (list (car x) (list 'quote (cdr x)))))
6667 (if (string-match
6668 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6669 (symbol-name (car x)))
6670 x nil))
6671 varlist))))
6673 ;;;###autoload
6674 (defun org-run-like-in-org-mode (cmd)
6675 "Run a command, pretending that the current buffer is in Org-mode.
6676 This will temporarily bind local variables that are typically bound in
6677 Org-mode to the values they have in Org-mode, and then interactively
6678 call CMD."
6679 (org-load-modules-maybe)
6680 (unless org-local-vars
6681 (setq org-local-vars (org-get-local-variables)))
6682 (eval (list 'let org-local-vars
6683 (list 'call-interactively (list 'quote cmd)))))
6685 ;;;; Archiving
6687 (defun org-get-category (&optional pos)
6688 "Get the category applying to position POS."
6689 (get-text-property (or pos (point)) 'org-category))
6691 (defun org-refresh-category-properties ()
6692 "Refresh category text properties in the buffer."
6693 (let ((def-cat (cond
6694 ((null org-category)
6695 (if buffer-file-name
6696 (file-name-sans-extension
6697 (file-name-nondirectory buffer-file-name))
6698 "???"))
6699 ((symbolp org-category) (symbol-name org-category))
6700 (t org-category)))
6701 beg end cat pos optionp)
6702 (org-unmodified
6703 (save-excursion
6704 (save-restriction
6705 (widen)
6706 (goto-char (point-min))
6707 (put-text-property (point) (point-max) 'org-category def-cat)
6708 (while (re-search-forward
6709 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6710 (setq pos (match-end 0)
6711 optionp (equal (char-after (match-beginning 0)) ?#)
6712 cat (org-trim (match-string 2)))
6713 (if optionp
6714 (setq beg (point-at-bol) end (point-max))
6715 (org-back-to-heading t)
6716 (setq beg (point) end (org-end-of-subtree t t)))
6717 (put-text-property beg end 'org-category cat)
6718 (goto-char pos)))))))
6721 ;;;; Link Stuff
6723 ;;; Link abbreviations
6725 (defun org-link-expand-abbrev (link)
6726 "Apply replacements as defined in `org-link-abbrev-alist."
6727 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6728 (let* ((key (match-string 1 link))
6729 (as (or (assoc key org-link-abbrev-alist-local)
6730 (assoc key org-link-abbrev-alist)))
6731 (tag (and (match-end 2) (match-string 3 link)))
6732 rpl)
6733 (if (not as)
6734 link
6735 (setq rpl (cdr as))
6736 (cond
6737 ((symbolp rpl) (funcall rpl tag))
6738 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6739 ((string-match "%h" rpl)
6740 (replace-match (url-hexify-string (or tag "")) t t rpl))
6741 (t (concat rpl tag)))))
6742 link))
6744 ;;; Storing and inserting links
6746 (defvar org-insert-link-history nil
6747 "Minibuffer history for links inserted with `org-insert-link'.")
6749 (defvar org-stored-links nil
6750 "Contains the links stored with `org-store-link'.")
6752 (defvar org-store-link-plist nil
6753 "Plist with info about the most recently link created with `org-store-link'.")
6755 (defvar org-link-protocols nil
6756 "Link protocols added to Org-mode using `org-add-link-type'.")
6758 (defvar org-store-link-functions nil
6759 "List of functions that are called to create and store a link.
6760 Each function will be called in turn until one returns a non-nil
6761 value. Each function should check if it is responsible for creating
6762 this link (for example by looking at the major mode).
6763 If not, it must exit and return nil.
6764 If yes, it should return a non-nil value after a calling
6765 `org-store-link-props' with a list of properties and values.
6766 Special properties are:
6768 :type The link prefix. like \"http\". This must be given.
6769 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6770 This is obligatory as well.
6771 :description Optional default description for the second pair
6772 of brackets in an Org-mode link. The user can still change
6773 this when inserting this link into an Org-mode buffer.
6775 In addition to these, any additional properties can be specified
6776 and then used in remember templates.")
6778 (defun org-add-link-type (type &optional follow export)
6779 "Add TYPE to the list of `org-link-types'.
6780 Re-compute all regular expressions depending on `org-link-types'
6782 FOLLOW and EXPORT are two functions.
6784 FOLLOW should take the link path as the single argument and do whatever
6785 is necessary to follow the link, for example find a file or display
6786 a mail message.
6788 EXPORT should format the link path for export to one of the export formats.
6789 It should be a function accepting three arguments:
6791 path the path of the link, the text after the prefix (like \"http:\")
6792 desc the description of the link, if any, nil if there was no description
6793 format the export format, a symbol like `html' or `latex'.
6795 The function may use the FORMAT information to return different values
6796 depending on the format. The return value will be put literally into
6797 the exported file.
6798 Org-mode has a built-in default for exporting links. If you are happy with
6799 this default, there is no need to define an export function for the link
6800 type. For a simple example of an export function, see `org-bbdb.el'."
6801 (add-to-list 'org-link-types type t)
6802 (org-make-link-regexps)
6803 (if (assoc type org-link-protocols)
6804 (setcdr (assoc type org-link-protocols) (list follow export))
6805 (push (list type follow export) org-link-protocols)))
6807 ;;;###autoload
6808 (defun org-store-link (arg)
6809 "\\<org-mode-map>Store an org-link to the current location.
6810 This link is added to `org-stored-links' and can later be inserted
6811 into an org-buffer with \\[org-insert-link].
6813 For some link types, a prefix arg is interpreted:
6814 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6815 For file links, arg negates `org-context-in-file-links'."
6816 (interactive "P")
6817 (org-load-modules-maybe)
6818 (setq org-store-link-plist nil) ; reset
6819 (let (link cpltxt desc description search txt)
6820 (cond
6822 ((run-hook-with-args-until-success 'org-store-link-functions)
6823 (setq link (plist-get org-store-link-plist :link)
6824 desc (or (plist-get org-store-link-plist :description) link)))
6826 ((equal (buffer-name) "*Org Edit Src Example*")
6827 (let (label gc)
6828 (while (or (not label)
6829 (save-excursion
6830 (save-restriction
6831 (widen)
6832 (goto-char (point-min))
6833 (re-search-forward
6834 (regexp-quote (format org-coderef-label-format label))
6835 nil t))))
6836 (when label (message "Label exists already") (sit-for 2))
6837 (setq label (read-string "Code line label: " label)))
6838 (end-of-line 1)
6839 (setq link (format org-coderef-label-format label))
6840 (setq gc (- 79 (length link)))
6841 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6842 (insert link)
6843 (setq link (concat "(" label ")") desc nil)))
6845 ((eq major-mode 'calendar-mode)
6846 (let ((cd (calendar-cursor-to-date)))
6847 (setq link
6848 (format-time-string
6849 (car org-time-stamp-formats)
6850 (apply 'encode-time
6851 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6852 nil nil nil))))
6853 (org-store-link-props :type "calendar" :date cd)))
6855 ((eq major-mode 'w3-mode)
6856 (setq cpltxt (if (and (buffer-name)
6857 (not (string-match "Untitled" (buffer-name))))
6858 (buffer-name)
6859 (url-view-url t))
6860 link (org-make-link (url-view-url t)))
6861 (org-store-link-props :type "w3" :url (url-view-url t)))
6863 ((eq major-mode 'w3m-mode)
6864 (setq cpltxt (or w3m-current-title w3m-current-url)
6865 link (org-make-link w3m-current-url))
6866 (org-store-link-props :type "w3m" :url (url-view-url t)))
6868 ((setq search (run-hook-with-args-until-success
6869 'org-create-file-search-functions))
6870 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6871 "::" search))
6872 (setq cpltxt (or description link)))
6874 ((eq major-mode 'image-mode)
6875 (setq cpltxt (concat "file:"
6876 (abbreviate-file-name buffer-file-name))
6877 link (org-make-link cpltxt))
6878 (org-store-link-props :type "image" :file buffer-file-name))
6880 ((eq major-mode 'dired-mode)
6881 ;; link to the file in the current line
6882 (setq cpltxt (concat "file:"
6883 (abbreviate-file-name
6884 (expand-file-name
6885 (dired-get-filename nil t))))
6886 link (org-make-link cpltxt)))
6888 ((and buffer-file-name (org-mode-p))
6889 (cond
6890 ((org-in-regexp "<<\\(.*?\\)>>")
6891 (setq cpltxt
6892 (concat "file:"
6893 (abbreviate-file-name buffer-file-name)
6894 "::" (match-string 1))
6895 link (org-make-link cpltxt)))
6896 ((and (featurep 'org-id)
6897 (or (eq org-link-to-org-use-id t)
6898 (and (eq org-link-to-org-use-id 'create-if-interactive)
6899 (interactive-p))
6900 (and org-link-to-org-use-id
6901 (condition-case nil
6902 (org-entry-get nil "ID")
6903 (error nil)))))
6904 ;; We can make a link using the ID.
6905 (setq link (condition-case nil
6906 (prog1 (org-id-store-link)
6907 (setq desc (plist-get org-store-link-plist
6908 :description)))
6909 (error
6910 ;; probably before first headline, link to file only
6911 (concat "file:"
6912 (abbreviate-file-name buffer-file-name))))))
6914 ;; Just link to current headline
6915 (setq cpltxt (concat "file:"
6916 (abbreviate-file-name buffer-file-name)))
6917 ;; Add a context search string
6918 (when (org-xor org-context-in-file-links arg)
6919 (setq txt (cond
6920 ((org-on-heading-p) nil)
6921 ((org-region-active-p)
6922 (buffer-substring (region-beginning) (region-end)))
6923 (t nil)))
6924 (when (or (null txt) (string-match "\\S-" txt))
6925 (setq cpltxt
6926 (concat cpltxt "::"
6927 (condition-case nil
6928 (org-make-org-heading-search-string txt)
6929 (error "")))
6930 desc "NONE")))
6931 (if (string-match "::\\'" cpltxt)
6932 (setq cpltxt (substring cpltxt 0 -2)))
6933 (setq link (org-make-link cpltxt)))))
6935 ((buffer-file-name (buffer-base-buffer))
6936 ;; Just link to this file here.
6937 (setq cpltxt (concat "file:"
6938 (abbreviate-file-name
6939 (buffer-file-name (buffer-base-buffer)))))
6940 ;; Add a context string
6941 (when (org-xor org-context-in-file-links arg)
6942 (setq txt (if (org-region-active-p)
6943 (buffer-substring (region-beginning) (region-end))
6944 (buffer-substring (point-at-bol) (point-at-eol))))
6945 ;; Only use search option if there is some text.
6946 (when (string-match "\\S-" txt)
6947 (setq cpltxt
6948 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6949 desc "NONE")))
6950 (setq link (org-make-link cpltxt)))
6952 ((interactive-p)
6953 (error "Cannot link to a buffer which is not visiting a file"))
6955 (t (setq link nil)))
6957 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6958 (setq link (or link cpltxt)
6959 desc (or desc cpltxt))
6960 (if (equal desc "NONE") (setq desc nil))
6962 (if (and (interactive-p) link)
6963 (progn
6964 (setq org-stored-links
6965 (cons (list link desc) org-stored-links))
6966 (message "Stored: %s" (or desc link)))
6967 (and link (org-make-link-string link desc)))))
6969 (defun org-store-link-props (&rest plist)
6970 "Store link properties, extract names and addresses."
6971 (let (x adr)
6972 (when (setq x (plist-get plist :from))
6973 (setq adr (mail-extract-address-components x))
6974 (setq plist (plist-put plist :fromname (car adr)))
6975 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6976 (when (setq x (plist-get plist :to))
6977 (setq adr (mail-extract-address-components x))
6978 (setq plist (plist-put plist :toname (car adr)))
6979 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6980 (let ((from (plist-get plist :from))
6981 (to (plist-get plist :to)))
6982 (when (and from to org-from-is-user-regexp)
6983 (setq plist
6984 (plist-put plist :fromto
6985 (if (string-match org-from-is-user-regexp from)
6986 (concat "to %t")
6987 (concat "from %f"))))))
6988 (setq org-store-link-plist plist))
6990 (defun org-add-link-props (&rest plist)
6991 "Add these properties to the link property list."
6992 (let (key value)
6993 (while plist
6994 (setq key (pop plist) value (pop plist))
6995 (setq org-store-link-plist
6996 (plist-put org-store-link-plist key value)))))
6998 (defun org-email-link-description (&optional fmt)
6999 "Return the description part of an email link.
7000 This takes information from `org-store-link-plist' and formats it
7001 according to FMT (default from `org-email-link-description-format')."
7002 (setq fmt (or fmt org-email-link-description-format))
7003 (let* ((p org-store-link-plist)
7004 (to (plist-get p :toaddress))
7005 (from (plist-get p :fromaddress))
7006 (table
7007 (list
7008 (cons "%c" (plist-get p :fromto))
7009 (cons "%F" (plist-get p :from))
7010 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7011 (cons "%T" (plist-get p :to))
7012 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7013 (cons "%s" (plist-get p :subject))
7014 (cons "%m" (plist-get p :message-id)))))
7015 (when (string-match "%c" fmt)
7016 ;; Check if the user wrote this message
7017 (if (and org-from-is-user-regexp from to
7018 (save-match-data (string-match org-from-is-user-regexp from)))
7019 (setq fmt (replace-match "to %t" t t fmt))
7020 (setq fmt (replace-match "from %f" t t fmt))))
7021 (org-replace-escapes fmt table)))
7023 (defun org-make-org-heading-search-string (&optional string heading)
7024 "Make search string for STRING or current headline."
7025 (interactive)
7026 (let ((s (or string (org-get-heading))))
7027 (unless (and string (not heading))
7028 ;; We are using a headline, clean up garbage in there.
7029 (if (string-match org-todo-regexp s)
7030 (setq s (replace-match "" t t s)))
7031 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7032 (setq s (replace-match "" t t s)))
7033 (setq s (org-trim s))
7034 (if (string-match (concat "^\\(" org-quote-string "\\|"
7035 org-comment-string "\\)") s)
7036 (setq s (replace-match "" t t s)))
7037 (while (string-match org-ts-regexp s)
7038 (setq s (replace-match "" t t s))))
7039 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7040 (setq s (replace-match " " t t s)))
7041 (or string (setq s (concat "*" s))) ; Add * for headlines
7042 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7044 (defun org-make-link (&rest strings)
7045 "Concatenate STRINGS."
7046 (apply 'concat strings))
7048 (defun org-make-link-string (link &optional description)
7049 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7050 (unless (string-match "\\S-" link)
7051 (error "Empty link"))
7052 (when (stringp description)
7053 ;; Remove brackets from the description, they are fatal.
7054 (while (string-match "\\[" description)
7055 (setq description (replace-match "{" t t description)))
7056 (while (string-match "\\]" description)
7057 (setq description (replace-match "}" t t description))))
7058 (when (equal (org-link-escape link) description)
7059 ;; No description needed, it is identical
7060 (setq description nil))
7061 (when (and (not description)
7062 (not (equal link (org-link-escape link))))
7063 (setq description (org-extract-attributes link)))
7064 (concat "[[" (org-link-escape link) "]"
7065 (if description (concat "[" description "]") "")
7066 "]"))
7068 (defconst org-link-escape-chars
7069 '((?\ . "%20")
7070 (?\[ . "%5B")
7071 (?\] . "%5D")
7072 (?\340 . "%E0") ; `a
7073 (?\342 . "%E2") ; ^a
7074 (?\347 . "%E7") ; ,c
7075 (?\350 . "%E8") ; `e
7076 (?\351 . "%E9") ; 'e
7077 (?\352 . "%EA") ; ^e
7078 (?\356 . "%EE") ; ^i
7079 (?\364 . "%F4") ; ^o
7080 (?\371 . "%F9") ; `u
7081 (?\373 . "%FB") ; ^u
7082 (?\; . "%3B")
7083 (?? . "%3F")
7084 (?= . "%3D")
7085 (?+ . "%2B")
7087 "Association list of escapes for some characters problematic in links.
7088 This is the list that is used for internal purposes.")
7090 (defvar org-url-encoding-use-url-hexify nil)
7092 (defconst org-link-escape-chars-browser
7093 '((?\ . "%20")) ; 32 for the SPC char
7094 "Association list of escapes for some characters problematic in links.
7095 This is the list that is used before handing over to the browser.")
7097 (defun org-link-escape (text &optional table)
7098 "Escape characters in TEXT that are problematic for links."
7099 (if org-url-encoding-use-url-hexify
7100 (url-hexify-string text)
7101 (setq table (or table org-link-escape-chars))
7102 (when text
7103 (let ((re (mapconcat (lambda (x) (regexp-quote
7104 (char-to-string (car x))))
7105 table "\\|")))
7106 (while (string-match re text)
7107 (setq text
7108 (replace-match
7109 (cdr (assoc (string-to-char (match-string 0 text))
7110 table))
7111 t t text)))
7112 text))))
7114 (defun org-link-unescape (text &optional table)
7115 "Reverse the action of `org-link-escape'."
7116 (if org-url-encoding-use-url-hexify
7117 (url-unhex-string text)
7118 (setq table (or table org-link-escape-chars))
7119 (when text
7120 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7121 table "\\|")))
7122 (while (string-match re text)
7123 (setq text
7124 (replace-match
7125 (char-to-string (car (rassoc (match-string 0 text) table)))
7126 t t text)))
7127 text))))
7129 (defun org-xor (a b)
7130 "Exclusive or."
7131 (if a (not b) b))
7133 (defun org-fixup-message-id-for-http (s)
7134 "Replace special characters in a message id, so it can be used in an http query."
7135 (while (string-match "<" s)
7136 (setq s (replace-match "%3C" t t s)))
7137 (while (string-match ">" s)
7138 (setq s (replace-match "%3E" t t s)))
7139 (while (string-match "@" s)
7140 (setq s (replace-match "%40" t t s)))
7143 ;;;###autoload
7144 (defun org-insert-link-global ()
7145 "Insert a link like Org-mode does.
7146 This command can be called in any mode to insert a link in Org-mode syntax."
7147 (interactive)
7148 (org-load-modules-maybe)
7149 (org-run-like-in-org-mode 'org-insert-link))
7151 (defun org-insert-link (&optional complete-file link-location)
7152 "Insert a link. At the prompt, enter the link.
7154 Completion can be used to insert any of the link protocol prefixes like
7155 http or ftp in use.
7157 The history can be used to select a link previously stored with
7158 `org-store-link'. When the empty string is entered (i.e. if you just
7159 press RET at the prompt), the link defaults to the most recently
7160 stored link. As SPC triggers completion in the minibuffer, you need to
7161 use M-SPC or C-q SPC to force the insertion of a space character.
7163 You will also be prompted for a description, and if one is given, it will
7164 be displayed in the buffer instead of the link.
7166 If there is already a link at point, this command will allow you to edit link
7167 and description parts.
7169 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7170 be selected using completion. The path to the file will be relative to the
7171 current directory if the file is in the current directory or a subdirectory.
7172 Otherwise, the link will be the absolute path as completed in the minibuffer
7173 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7174 option `org-link-file-path-type'.
7176 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7177 the current directory or below.
7179 With three \\[universal-argument] prefixes, negate the meaning of
7180 `org-keep-stored-link-after-insertion'.
7182 If `org-make-link-description-function' is non-nil, this function will be
7183 called with the link target, and the result will be the default
7184 link description.
7186 If the LINK-LOCATION parameter is non-nil, this value will be
7187 used as the link location instead of reading one interactively."
7188 (interactive "P")
7189 (let* ((wcf (current-window-configuration))
7190 (region (if (org-region-active-p)
7191 (buffer-substring (region-beginning) (region-end))))
7192 (remove (and region (list (region-beginning) (region-end))))
7193 (desc region)
7194 tmphist ; byte-compile incorrectly complains about this
7195 (link link-location)
7196 entry file)
7197 (cond
7198 (link-location) ; specified by arg, just use it.
7199 ((org-in-regexp org-bracket-link-regexp 1)
7200 ;; We do have a link at point, and we are going to edit it.
7201 (setq remove (list (match-beginning 0) (match-end 0)))
7202 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7203 (setq link (read-string "Link: "
7204 (org-link-unescape
7205 (org-match-string-no-properties 1)))))
7206 ((or (org-in-regexp org-angle-link-re)
7207 (org-in-regexp org-plain-link-re))
7208 ;; Convert to bracket link
7209 (setq remove (list (match-beginning 0) (match-end 0))
7210 link (read-string "Link: "
7211 (org-remove-angle-brackets (match-string 0)))))
7212 ((member complete-file '((4) (16)))
7213 ;; Completing read for file names.
7214 (setq file (read-file-name "File: "))
7215 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7216 (pwd1 (file-name-as-directory (abbreviate-file-name
7217 (expand-file-name ".")))))
7218 (cond
7219 ((equal complete-file '(16))
7220 (setq link (org-make-link
7221 "file:"
7222 (abbreviate-file-name (expand-file-name file)))))
7223 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7224 (setq link (org-make-link "file:" (match-string 1 file))))
7225 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7226 (expand-file-name file))
7227 (setq link (org-make-link
7228 "file:" (match-string 1 (expand-file-name file)))))
7229 (t (setq link (org-make-link "file:" file))))))
7231 ;; Read link, with completion for stored links.
7232 (with-output-to-temp-buffer "*Org Links*"
7233 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7234 (when org-stored-links
7235 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7236 (princ (mapconcat
7237 (lambda (x)
7238 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7239 (reverse org-stored-links) "\n"))))
7240 (let ((cw (selected-window)))
7241 (select-window (get-buffer-window "*Org Links*"))
7242 (setq truncate-lines t)
7243 (org-fit-window-to-buffer)
7244 (select-window cw))
7245 ;; Fake a link history, containing the stored links.
7246 (setq tmphist (append (mapcar 'car org-stored-links)
7247 org-insert-link-history))
7248 (unwind-protect
7249 (setq link
7250 (let ((org-completion-use-ido nil))
7251 (org-completing-read
7252 "Link: "
7253 (append
7254 (mapcar (lambda (x) (list (concat (car x) ":")))
7255 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7256 (mapcar (lambda (x) (list (concat x ":")))
7257 org-link-types))
7258 nil nil nil
7259 'tmphist
7260 (or (car (car org-stored-links))))))
7261 (set-window-configuration wcf)
7262 (kill-buffer "*Org Links*"))
7263 (setq entry (assoc link org-stored-links))
7264 (or entry (push link org-insert-link-history))
7265 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7266 (not org-keep-stored-link-after-insertion))
7267 (setq org-stored-links (delq (assoc link org-stored-links)
7268 org-stored-links)))
7269 (setq desc (or desc (nth 1 entry)))))
7271 (if (string-match org-plain-link-re link)
7272 ;; URL-like link, normalize the use of angular brackets.
7273 (setq link (org-make-link (org-remove-angle-brackets link))))
7275 ;; Check if we are linking to the current file with a search option
7276 ;; If yes, simplify the link by using only the search option.
7277 (when (and buffer-file-name
7278 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7279 (let* ((path (match-string 1 link))
7280 (case-fold-search nil)
7281 (search (match-string 2 link)))
7282 (save-match-data
7283 (if (equal (file-truename buffer-file-name) (file-truename path))
7284 ;; We are linking to this same file, with a search option
7285 (setq link search)))))
7287 ;; Check if we can/should use a relative path. If yes, simplify the link
7288 (when (string-match "^file:\\(.*\\)" link)
7289 (let* ((path (match-string 1 link))
7290 (origpath path)
7291 (case-fold-search nil))
7292 (cond
7293 ((or (eq org-link-file-path-type 'absolute)
7294 (equal complete-file '(16)))
7295 (setq path (abbreviate-file-name (expand-file-name path))))
7296 ((eq org-link-file-path-type 'noabbrev)
7297 (setq path (expand-file-name path)))
7298 ((eq org-link-file-path-type 'relative)
7299 (setq path (file-relative-name path)))
7301 (save-match-data
7302 (if (string-match (concat "^" (regexp-quote
7303 (file-name-as-directory
7304 (expand-file-name "."))))
7305 (expand-file-name path))
7306 ;; We are linking a file with relative path name.
7307 (setq path (substring (expand-file-name path)
7308 (match-end 0)))
7309 (setq path (abbreviate-file-name (expand-file-name path)))))))
7310 (setq link (concat "file:" path))
7311 (if (equal desc origpath)
7312 (setq desc path))))
7314 (if org-make-link-description-function
7315 (setq desc (funcall org-make-link-description-function link desc)))
7317 (setq desc (read-string "Description: " desc))
7318 (unless (string-match "\\S-" desc) (setq desc nil))
7319 (if remove (apply 'delete-region remove))
7320 (insert (org-make-link-string link desc))))
7322 (defun org-completing-read (&rest args)
7323 "Completing-read with SPACE being a normal character."
7324 (let ((minibuffer-local-completion-map
7325 (copy-keymap minibuffer-local-completion-map)))
7326 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7327 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7328 (apply 'org-ido-completing-read args)))
7330 (defun org-completing-read-no-ido (&rest args)
7331 (let (org-completion-use-ido)
7332 (apply 'org-completing-read args)))
7334 (defun org-ido-completing-read (&rest args)
7335 "Completing-read using `ido-mode' speedups if available"
7336 (if (and org-completion-use-ido
7337 (fboundp 'ido-completing-read)
7338 (boundp 'ido-mode) ido-mode
7339 (listp (second args)))
7340 (let ((ido-enter-matching-directory nil))
7341 (apply 'ido-completing-read (concat (car args))
7342 (mapcar (lambda (x) (car x)) (nth 1 args))
7343 (cddr args)))
7344 (apply 'completing-read args)))
7346 (defun org-extract-attributes (s)
7347 "Extract the attributes cookie from a string and set as text property."
7348 (let (a attr (start 0) key value)
7349 (save-match-data
7350 (when (string-match "{{\\([^}]+\\)}}$" s)
7351 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7352 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7353 (setq key (match-string 1 a) value (match-string 2 a)
7354 start (match-end 0)
7355 attr (plist-put attr (intern key) value))))
7356 (org-add-props s nil 'org-attr attr))
7359 (defun org-extract-attributes-from-string (tag)
7360 (let (key value attr)
7361 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7362 (setq key (match-string 1 tag) value (match-string 2 tag)
7363 tag (replace-match "" t t tag)
7364 attr (plist-put attr (intern key) value)))
7365 (cons tag attr)))
7367 (defun org-attributes-to-string (plist)
7368 "Format a property list into an HTML attribute list."
7369 (let ((s "") key value)
7370 (while plist
7371 (setq key (pop plist) value (pop plist))
7372 (and value
7373 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7376 ;;; Opening/following a link
7378 (defvar org-link-search-failed nil)
7380 (defun org-next-link ()
7381 "Move forward to the next link.
7382 If the link is in hidden text, expose it."
7383 (interactive)
7384 (when (and org-link-search-failed (eq this-command last-command))
7385 (goto-char (point-min))
7386 (message "Link search wrapped back to beginning of buffer"))
7387 (setq org-link-search-failed nil)
7388 (let* ((pos (point))
7389 (ct (org-context))
7390 (a (assoc :link ct)))
7391 (if a (goto-char (nth 2 a)))
7392 (if (re-search-forward org-any-link-re nil t)
7393 (progn
7394 (goto-char (match-beginning 0))
7395 (if (org-invisible-p) (org-show-context)))
7396 (goto-char pos)
7397 (setq org-link-search-failed t)
7398 (error "No further link found"))))
7400 (defun org-previous-link ()
7401 "Move backward to the previous link.
7402 If the link is in hidden text, expose it."
7403 (interactive)
7404 (when (and org-link-search-failed (eq this-command last-command))
7405 (goto-char (point-max))
7406 (message "Link search wrapped back to end of buffer"))
7407 (setq org-link-search-failed nil)
7408 (let* ((pos (point))
7409 (ct (org-context))
7410 (a (assoc :link ct)))
7411 (if a (goto-char (nth 1 a)))
7412 (if (re-search-backward org-any-link-re nil t)
7413 (progn
7414 (goto-char (match-beginning 0))
7415 (if (org-invisible-p) (org-show-context)))
7416 (goto-char pos)
7417 (setq org-link-search-failed t)
7418 (error "No further link found"))))
7420 (defun org-translate-link (s)
7421 "Translate a link string if a translation function has been defined."
7422 (if (and org-link-translation-function
7423 (fboundp org-link-translation-function)
7424 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7425 (progn
7426 (setq s (funcall org-link-translation-function
7427 (match-string 1) (match-string 2)))
7428 (concat (car s) ":" (cdr s)))
7431 (defun org-translate-link-from-planner (type path)
7432 "Translate a link from Emacs Planner syntax so that Org can follow it.
7433 This is still an experimental function, your mileage may vary."
7434 (cond
7435 ((member type '("http" "https" "news" "ftp"))
7436 ;; standard Internet links are the same.
7437 nil)
7438 ((and (equal type "irc") (string-match "^//" path))
7439 ;; Planner has two / at the beginning of an irc link, we have 1.
7440 ;; We should have zero, actually....
7441 (setq path (substring path 1)))
7442 ((and (equal type "lisp") (string-match "^/" path))
7443 ;; Planner has a slash, we do not.
7444 (setq type "elisp" path (substring path 1)))
7445 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7446 ;; A typical message link. Planner has the id after the fina slash,
7447 ;; we separate it with a hash mark
7448 (setq path (concat (match-string 1 path) "#"
7449 (org-remove-angle-brackets (match-string 2 path)))))
7451 (cons type path))
7453 (defun org-find-file-at-mouse (ev)
7454 "Open file link or URL at mouse."
7455 (interactive "e")
7456 (mouse-set-point ev)
7457 (org-open-at-point 'in-emacs))
7459 (defun org-open-at-mouse (ev)
7460 "Open file link or URL at mouse."
7461 (interactive "e")
7462 (mouse-set-point ev)
7463 (if (eq major-mode 'org-agenda-mode)
7464 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7465 (org-open-at-point))
7467 (defvar org-window-config-before-follow-link nil
7468 "The window configuration before following a link.
7469 This is saved in case the need arises to restore it.")
7471 (defvar org-open-link-marker (make-marker)
7472 "Marker pointing to the location where `org-open-at-point; was called.")
7474 ;;;###autoload
7475 (defun org-open-at-point-global ()
7476 "Follow a link like Org-mode does.
7477 This command can be called in any mode to follow a link that has
7478 Org-mode syntax."
7479 (interactive)
7480 (org-run-like-in-org-mode 'org-open-at-point))
7482 ;;;###autoload
7483 (defun org-open-link-from-string (s &optional arg)
7484 "Open a link in the string S, as if it was in Org-mode."
7485 (interactive "sLink: \nP")
7486 (let ((reference-buffer (current-buffer)))
7487 (with-temp-buffer
7488 (let ((org-inhibit-startup t))
7489 (org-mode)
7490 (insert s)
7491 (goto-char (point-min))
7492 (org-open-at-point arg reference-buffer)))))
7494 (defun org-open-at-point (&optional in-emacs reference-buffer)
7495 "Open link at or after point.
7496 If there is no link at point, this function will search forward up to
7497 the end of the current line.
7498 Normally, files will be opened by an appropriate application. If the
7499 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7500 With a double prefix argument, try to open outside of Emacs, in the
7501 application the system uses for this file type."
7502 (interactive "P")
7503 (org-load-modules-maybe)
7504 (move-marker org-open-link-marker (point))
7505 (setq org-window-config-before-follow-link (current-window-configuration))
7506 (org-remove-occur-highlights nil nil t)
7507 (cond
7508 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7509 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7510 (org-footnote-action))
7512 (let (type path link line search (pos (point)))
7513 (catch 'match
7514 (save-excursion
7515 (skip-chars-forward "^]\n\r")
7516 (when (org-in-regexp org-bracket-link-regexp)
7517 (setq link (org-extract-attributes
7518 (org-link-unescape (org-match-string-no-properties 1))))
7519 (while (string-match " *\n *" link)
7520 (setq link (replace-match " " t t link)))
7521 (setq link (org-link-expand-abbrev link))
7522 (cond
7523 ((or (file-name-absolute-p link)
7524 (string-match "^\\.\\.?/" link))
7525 (setq type "file" path link))
7526 ((string-match org-link-re-with-space3 link)
7527 (setq type (match-string 1 link) path (match-string 2 link)))
7528 (t (setq type "thisfile" path link)))
7529 (throw 'match t)))
7531 (when (get-text-property (point) 'org-linked-text)
7532 (setq type "thisfile"
7533 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7534 (1+ (point)) (point))
7535 path (buffer-substring
7536 (previous-single-property-change pos 'org-linked-text)
7537 (next-single-property-change pos 'org-linked-text)))
7538 (throw 'match t))
7540 (save-excursion
7541 (when (or (org-in-regexp org-angle-link-re)
7542 (org-in-regexp org-plain-link-re))
7543 (setq type (match-string 1) path (match-string 2))
7544 (throw 'match t)))
7545 (save-excursion
7546 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7547 (setq type "tags"
7548 path (match-string 1))
7549 (while (string-match ":" path)
7550 (setq path (replace-match "+" t t path)))
7551 (throw 'match t)))
7552 (when (org-in-regexp "<\\([^><\n]+\\)>")
7553 (setq type "tree-match"
7554 path (match-string 1))
7555 (throw 'match t)))
7556 (unless path
7557 (error "No link found"))
7559 ;; switch back to reference buffer
7560 ;; needed when if called in a temporary buffer through
7561 ;; org-open-link-from-string
7562 (and reference-buffer (switch-to-buffer reference-buffer))
7564 ;; Remove any trailing spaces in path
7565 (if (string-match " +\\'" path)
7566 (setq path (replace-match "" t t path)))
7567 (if (and org-link-translation-function
7568 (fboundp org-link-translation-function))
7569 ;; Check if we need to translate the link
7570 (let ((tmp (funcall org-link-translation-function type path)))
7571 (setq type (car tmp) path (cdr tmp))))
7573 (cond
7575 ((assoc type org-link-protocols)
7576 (funcall (nth 1 (assoc type org-link-protocols)) path))
7578 ((equal type "mailto")
7579 (let ((cmd (car org-link-mailto-program))
7580 (args (cdr org-link-mailto-program)) args1
7581 (address path) (subject "") a)
7582 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7583 (setq address (match-string 1 path)
7584 subject (org-link-escape (match-string 2 path))))
7585 (while args
7586 (cond
7587 ((not (stringp (car args))) (push (pop args) args1))
7588 (t (setq a (pop args))
7589 (if (string-match "%a" a)
7590 (setq a (replace-match address t t a)))
7591 (if (string-match "%s" a)
7592 (setq a (replace-match subject t t a)))
7593 (push a args1))))
7594 (apply cmd (nreverse args1))))
7596 ((member type '("http" "https" "ftp" "news"))
7597 (browse-url (concat type ":" (org-link-escape
7598 path org-link-escape-chars-browser))))
7600 ((member type '("message"))
7601 (browse-url (concat type ":" path)))
7603 ((string= type "tags")
7604 (org-tags-view in-emacs path))
7605 ((string= type "thisfile")
7606 (if in-emacs
7607 (switch-to-buffer-other-window
7608 (org-get-buffer-for-internal-link (current-buffer)))
7609 (org-mark-ring-push))
7610 (let ((cmd `(org-link-search
7611 ,path
7612 ,(cond ((equal in-emacs '(4)) 'occur)
7613 ((equal in-emacs '(16)) 'org-occur)
7614 (t nil))
7615 ,pos)))
7616 (condition-case nil (eval cmd)
7617 (error (progn (widen) (eval cmd))))))
7619 ((string= type "tree-match")
7620 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7622 ((string= type "file")
7623 (if (string-match "::\\([0-9]+\\)\\'" path)
7624 (setq line (string-to-number (match-string 1 path))
7625 path (substring path 0 (match-beginning 0)))
7626 (if (string-match "::\\(.+\\)\\'" path)
7627 (setq search (match-string 1 path)
7628 path (substring path 0 (match-beginning 0)))))
7629 (if (string-match "[*?{]" (file-name-nondirectory path))
7630 (dired path)
7631 (org-open-file path in-emacs line search)))
7633 ((string= type "news")
7634 (require 'org-gnus)
7635 (org-gnus-follow-link path))
7637 ((string= type "shell")
7638 (let ((cmd path))
7639 (if (or (not org-confirm-shell-link-function)
7640 (funcall org-confirm-shell-link-function
7641 (format "Execute \"%s\" in shell? "
7642 (org-add-props cmd nil
7643 'face 'org-warning))))
7644 (progn
7645 (message "Executing %s" cmd)
7646 (shell-command cmd))
7647 (error "Abort"))))
7649 ((string= type "elisp")
7650 (let ((cmd path))
7651 (if (or (not org-confirm-elisp-link-function)
7652 (funcall org-confirm-elisp-link-function
7653 (format "Execute \"%s\" as elisp? "
7654 (org-add-props cmd nil
7655 'face 'org-warning))))
7656 (message "%s => %s" cmd
7657 (if (equal (string-to-char cmd) ?\()
7658 (eval (read cmd))
7659 (call-interactively (read cmd))))
7660 (error "Abort"))))
7663 (browse-url-at-point))))))
7664 (move-marker org-open-link-marker nil)
7665 (run-hook-with-args 'org-follow-link-hook))
7667 ;;;; Time estimates
7669 (defun org-get-effort (&optional pom)
7670 "Get the effort estimate for the current entry."
7671 (org-entry-get pom org-effort-property))
7673 ;;; File search
7675 (defvar org-create-file-search-functions nil
7676 "List of functions to construct the right search string for a file link.
7677 These functions are called in turn with point at the location to
7678 which the link should point.
7680 A function in the hook should first test if it would like to
7681 handle this file type, for example by checking the major-mode or
7682 the file extension. If it decides not to handle this file, it
7683 should just return nil to give other functions a chance. If it
7684 does handle the file, it must return the search string to be used
7685 when following the link. The search string will be part of the
7686 file link, given after a double colon, and `org-open-at-point'
7687 will automatically search for it. If special measures must be
7688 taken to make the search successful, another function should be
7689 added to the companion hook `org-execute-file-search-functions',
7690 which see.
7692 A function in this hook may also use `setq' to set the variable
7693 `description' to provide a suggestion for the descriptive text to
7694 be used for this link when it gets inserted into an Org-mode
7695 buffer with \\[org-insert-link].")
7697 (defvar org-execute-file-search-functions nil
7698 "List of functions to execute a file search triggered by a link.
7700 Functions added to this hook must accept a single argument, the
7701 search string that was part of the file link, the part after the
7702 double colon. The function must first check if it would like to
7703 handle this search, for example by checking the major-mode or the
7704 file extension. If it decides not to handle this search, it
7705 should just return nil to give other functions a chance. If it
7706 does handle the search, it must return a non-nil value to keep
7707 other functions from trying.
7709 Each function can access the current prefix argument through the
7710 variable `current-prefix-argument'. Note that a single prefix is
7711 used to force opening a link in Emacs, so it may be good to only
7712 use a numeric or double prefix to guide the search function.
7714 In case this is needed, a function in this hook can also restore
7715 the window configuration before `org-open-at-point' was called using:
7717 (set-window-configuration org-window-config-before-follow-link)")
7719 (defun org-link-search (s &optional type avoid-pos)
7720 "Search for a link search option.
7721 If S is surrounded by forward slashes, it is interpreted as a
7722 regular expression. In org-mode files, this will create an `org-occur'
7723 sparse tree. In ordinary files, `occur' will be used to list matches.
7724 If the current buffer is in `dired-mode', grep will be used to search
7725 in all files. If AVOID-POS is given, ignore matches near that position."
7726 (let ((case-fold-search t)
7727 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7728 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7729 (append '(("") (" ") ("\t") ("\n"))
7730 org-emphasis-alist)
7731 "\\|") "\\)"))
7732 (pos (point))
7733 (pre nil) (post nil)
7734 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7735 (cond
7736 ;; First check if there are any special
7737 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7738 ;; Now try the builtin stuff
7739 ((save-excursion
7740 (goto-char (point-min))
7741 (and
7742 (re-search-forward
7743 (concat "<<" (regexp-quote s0) ">>") nil t)
7744 (setq type 'dedicated
7745 pos (match-beginning 0))))
7746 ;; There is an exact target for this
7747 (goto-char pos))
7748 ((and (string-match "^(\\(.*\\))$" s0)
7749 (save-excursion
7750 (goto-char (point-min))
7751 (and
7752 (re-search-forward
7753 (concat "[^[]" (regexp-quote
7754 (format org-coderef-label-format
7755 (match-string 1 s0))))
7756 nil t)
7757 (setq type 'dedicated
7758 pos (1+ (match-beginning 0))))))
7759 ;; There is a coderef target for this
7760 (goto-char pos))
7761 ((string-match "^/\\(.*\\)/$" s)
7762 ;; A regular expression
7763 (cond
7764 ((org-mode-p)
7765 (org-occur (match-string 1 s)))
7766 ;;((eq major-mode 'dired-mode)
7767 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7768 (t (org-do-occur (match-string 1 s)))))
7770 ;; A normal search strings
7771 (when (equal (string-to-char s) ?*)
7772 ;; Anchor on headlines, post may include tags.
7773 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7774 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7775 s (substring s 1)))
7776 (remove-text-properties
7777 0 (length s)
7778 '(face nil mouse-face nil keymap nil fontified nil) s)
7779 ;; Make a series of regular expressions to find a match
7780 (setq words (org-split-string s "[ \n\r\t]+")
7782 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7783 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7784 "\\)" markers)
7785 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7786 re2a (concat "[ \t\r\n]" re2a_)
7787 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7788 re4 (concat "[^a-zA-Z_]" re4_)
7790 re1 (concat pre re2 post)
7791 re3 (concat pre (if pre re4_ re4) post)
7792 re5 (concat pre ".*" re4)
7793 re2 (concat pre re2)
7794 re2a (concat pre (if pre re2a_ re2a))
7795 re4 (concat pre (if pre re4_ re4))
7796 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7797 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7798 re5 "\\)"
7800 (cond
7801 ((eq type 'org-occur) (org-occur reall))
7802 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7803 (t (goto-char (point-min))
7804 (setq type 'fuzzy)
7805 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7806 (org-search-not-self 1 re1 nil t)
7807 (org-search-not-self 1 re2 nil t)
7808 (org-search-not-self 1 re2a nil t)
7809 (org-search-not-self 1 re3 nil t)
7810 (org-search-not-self 1 re4 nil t)
7811 (org-search-not-self 1 re5 nil t)
7813 (goto-char (match-beginning 1))
7814 (goto-char pos)
7815 (error "No match")))))
7817 ;; Normal string-search
7818 (goto-char (point-min))
7819 (if (search-forward s nil t)
7820 (goto-char (match-beginning 0))
7821 (error "No match"))))
7822 (and (org-mode-p) (org-show-context 'link-search))
7823 type))
7825 (defun org-search-not-self (group &rest args)
7826 "Execute `re-search-forward', but only accept matches that do not
7827 enclose the position of `org-open-link-marker'."
7828 (let ((m org-open-link-marker))
7829 (catch 'exit
7830 (while (apply 're-search-forward args)
7831 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7832 (goto-char (match-end group))
7833 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7834 (> (match-beginning 0) (marker-position m))
7835 (< (match-end 0) (marker-position m)))
7836 (save-match-data
7837 (or (not (org-in-regexp
7838 org-bracket-link-analytic-regexp 1))
7839 (not (match-end 4)) ; no description
7840 (and (<= (match-beginning 4) (point))
7841 (>= (match-end 4) (point))))))
7842 (throw 'exit (point))))))))
7844 (defun org-get-buffer-for-internal-link (buffer)
7845 "Return a buffer to be used for displaying the link target of internal links."
7846 (cond
7847 ((not org-display-internal-link-with-indirect-buffer)
7848 buffer)
7849 ((string-match "(Clone)$" (buffer-name buffer))
7850 (message "Buffer is already a clone, not making another one")
7851 ;; we also do not modify visibility in this case
7852 buffer)
7853 (t ; make a new indirect buffer for displaying the link
7854 (let* ((bn (buffer-name buffer))
7855 (ibn (concat bn "(Clone)"))
7856 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7857 (with-current-buffer ib (org-overview))
7858 ib))))
7860 (defun org-do-occur (regexp &optional cleanup)
7861 "Call the Emacs command `occur'.
7862 If CLEANUP is non-nil, remove the printout of the regular expression
7863 in the *Occur* buffer. This is useful if the regex is long and not useful
7864 to read."
7865 (occur regexp)
7866 (when cleanup
7867 (let ((cwin (selected-window)) win beg end)
7868 (when (setq win (get-buffer-window "*Occur*"))
7869 (select-window win))
7870 (goto-char (point-min))
7871 (when (re-search-forward "match[a-z]+" nil t)
7872 (setq beg (match-end 0))
7873 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7874 (setq end (1- (match-beginning 0)))))
7875 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7876 (goto-char (point-min))
7877 (select-window cwin))))
7879 ;;; The mark ring for links jumps
7881 (defvar org-mark-ring nil
7882 "Mark ring for positions before jumps in Org-mode.")
7883 (defvar org-mark-ring-last-goto nil
7884 "Last position in the mark ring used to go back.")
7885 ;; Fill and close the ring
7886 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7887 (loop for i from 1 to org-mark-ring-length do
7888 (push (make-marker) org-mark-ring))
7889 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7890 org-mark-ring)
7892 (defun org-mark-ring-push (&optional pos buffer)
7893 "Put the current position or POS into the mark ring and rotate it."
7894 (interactive)
7895 (setq pos (or pos (point)))
7896 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7897 (move-marker (car org-mark-ring)
7898 (or pos (point))
7899 (or buffer (current-buffer)))
7900 (message "%s"
7901 (substitute-command-keys
7902 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7904 (defun org-mark-ring-goto (&optional n)
7905 "Jump to the previous position in the mark ring.
7906 With prefix arg N, jump back that many stored positions. When
7907 called several times in succession, walk through the entire ring.
7908 Org-mode commands jumping to a different position in the current file,
7909 or to another Org-mode file, automatically push the old position
7910 onto the ring."
7911 (interactive "p")
7912 (let (p m)
7913 (if (eq last-command this-command)
7914 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7915 (setq p org-mark-ring))
7916 (setq org-mark-ring-last-goto p)
7917 (setq m (car p))
7918 (switch-to-buffer (marker-buffer m))
7919 (goto-char m)
7920 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7922 (defun org-remove-angle-brackets (s)
7923 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7924 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7926 (defun org-add-angle-brackets (s)
7927 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7928 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7930 (defun org-remove-double-quotes (s)
7931 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7932 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7935 ;;; Following specific links
7937 (defun org-follow-timestamp-link ()
7938 (cond
7939 ((org-at-date-range-p t)
7940 (let ((org-agenda-start-on-weekday)
7941 (t1 (match-string 1))
7942 (t2 (match-string 2)))
7943 (setq t1 (time-to-days (org-time-string-to-time t1))
7944 t2 (time-to-days (org-time-string-to-time t2)))
7945 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7946 ((org-at-timestamp-p t)
7947 (org-agenda-list nil (time-to-days (org-time-string-to-time
7948 (substring (match-string 1) 0 10)))
7950 (t (error "This should not happen"))))
7953 ;;; Following file links
7954 (defvar org-wait nil)
7955 (defun org-open-file (path &optional in-emacs line search)
7956 "Open the file at PATH.
7957 First, this expands any special file name abbreviations. Then the
7958 configuration variable `org-file-apps' is checked if it contains an
7959 entry for this file type, and if yes, the corresponding command is launched.
7961 If no application is found, Emacs simply visits the file.
7963 With optional prefix argument IN-EMACS, Emacs will visit the file.
7964 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7965 and o use an external application to visit the file.
7967 Optional LINE specifies a line to go to, optional SEARCH a string to
7968 search for. If LINE or SEARCH is given, the file will always be
7969 opened in Emacs.
7970 If the file does not exist, an error is thrown."
7971 (setq in-emacs (or in-emacs line search))
7972 (let* ((file (if (equal path "")
7973 buffer-file-name
7974 (substitute-in-file-name (expand-file-name path))))
7975 (apps (append org-file-apps (org-default-apps)))
7976 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7977 (dirp (if remp nil (file-directory-p file)))
7978 (file (if (and dirp org-open-directory-means-index-dot-org)
7979 (concat (file-name-as-directory file) "index.org")
7980 file))
7981 (a-m-a-p (assq 'auto-mode apps))
7982 (dfile (downcase file))
7983 (old-buffer (current-buffer))
7984 (old-pos (point))
7985 (old-mode major-mode)
7986 ext cmd)
7987 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7988 (setq ext (match-string 1 dfile))
7989 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7990 (setq ext (match-string 1 dfile))))
7991 (cond
7992 ((equal in-emacs '(16))
7993 (setq cmd (cdr (assoc 'system apps))))
7994 (in-emacs (setq cmd 'emacs))
7996 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7997 (and dirp (cdr (assoc 'directory apps)))
7998 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7999 'string-match)
8000 (cdr (assoc ext apps))
8001 (cdr (assoc t apps))))))
8002 (when (eq cmd 'system)
8003 (setq cmd (cdr (assoc 'system apps))))
8004 (when (eq cmd 'default)
8005 (setq cmd (cdr (assoc t apps))))
8006 (when (eq cmd 'mailcap)
8007 (require 'mailcap)
8008 (mailcap-parse-mailcaps)
8009 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8010 (command (mailcap-mime-info mime-type)))
8011 (if (stringp command)
8012 (setq cmd command)
8013 (setq cmd 'emacs))))
8014 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8015 (not (file-exists-p file))
8016 (not org-open-non-existing-files))
8017 (error "No such file: %s" file))
8018 (cond
8019 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8020 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8021 (while (string-match "['\"]%s['\"]" cmd)
8022 (setq cmd (replace-match "%s" t t cmd)))
8023 (while (string-match "%s" cmd)
8024 (setq cmd (replace-match
8025 (save-match-data
8026 (shell-quote-argument
8027 (convert-standard-filename file)))
8028 t t cmd)))
8029 (save-window-excursion
8030 (start-process-shell-command cmd nil cmd)
8031 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8033 ((or (stringp cmd)
8034 (eq cmd 'emacs))
8035 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8036 (widen)
8037 (if line (goto-line line)
8038 (if search (org-link-search search))))
8039 ((consp cmd)
8040 (let ((file (convert-standard-filename file)))
8041 (eval cmd)))
8042 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8043 (and (org-mode-p) (eq old-mode 'org-mode)
8044 (or (not (equal old-buffer (current-buffer)))
8045 (not (equal old-pos (point))))
8046 (org-mark-ring-push old-pos old-buffer))))
8048 (defun org-default-apps ()
8049 "Return the default applications for this operating system."
8050 (cond
8051 ((eq system-type 'darwin)
8052 org-file-apps-defaults-macosx)
8053 ((eq system-type 'windows-nt)
8054 org-file-apps-defaults-windowsnt)
8055 (t org-file-apps-defaults-gnu)))
8057 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8058 "Convert extensions to regular expressions in the cars of LIST.
8059 Also, weed out any non-string entries, because the return value is used
8060 only for regexp matching.
8061 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8062 point to the symbol `emacs', indicating that the file should
8063 be opened in Emacs."
8064 (append
8065 (delq nil
8066 (mapcar (lambda (x)
8067 (if (not (stringp (car x)))
8069 (if (string-match "\\W" (car x))
8071 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8072 list))
8073 (if add-auto-mode
8074 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8076 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8077 (defun org-file-remote-p (file)
8078 "Test whether FILE specifies a location on a remote system.
8079 Return non-nil if the location is indeed remote.
8081 For example, the filename \"/user@host:/foo\" specifies a location
8082 on the system \"/user@host:\"."
8083 (cond ((fboundp 'file-remote-p)
8084 (file-remote-p file))
8085 ((fboundp 'tramp-handle-file-remote-p)
8086 (tramp-handle-file-remote-p file))
8087 ((and (boundp 'ange-ftp-name-format)
8088 (string-match (car ange-ftp-name-format) file))
8090 (t nil)))
8093 ;;;; Refiling
8095 (defun org-get-org-file ()
8096 "Read a filename, with default directory `org-directory'."
8097 (let ((default (or org-default-notes-file remember-data-file)))
8098 (read-file-name (format "File name [%s]: " default)
8099 (file-name-as-directory org-directory)
8100 default)))
8102 (defun org-notes-order-reversed-p ()
8103 "Check if the current file should receive notes in reversed order."
8104 (cond
8105 ((not org-reverse-note-order) nil)
8106 ((eq t org-reverse-note-order) t)
8107 ((not (listp org-reverse-note-order)) nil)
8108 (t (catch 'exit
8109 (let ((all org-reverse-note-order)
8110 entry)
8111 (while (setq entry (pop all))
8112 (if (string-match (car entry) buffer-file-name)
8113 (throw 'exit (cdr entry))))
8114 nil)))))
8116 (defvar org-refile-target-table nil
8117 "The list of refile targets, created by `org-refile'.")
8119 (defvar org-agenda-new-buffers nil
8120 "Buffers created to visit agenda files.")
8122 (defun org-get-refile-targets (&optional default-buffer)
8123 "Produce a table with refile targets."
8124 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8125 targets txt re files f desc descre fast-path-p level)
8126 (message "Getting targets...")
8127 (with-current-buffer (or default-buffer (current-buffer))
8128 (while (setq entry (pop entries))
8129 (setq files (car entry) desc (cdr entry))
8130 (setq fast-path-p nil)
8131 (cond
8132 ((null files) (setq files (list (current-buffer))))
8133 ((eq files 'org-agenda-files)
8134 (setq files (org-agenda-files 'unrestricted)))
8135 ((and (symbolp files) (fboundp files))
8136 (setq files (funcall files)))
8137 ((and (symbolp files) (boundp files))
8138 (setq files (symbol-value files))))
8139 (if (stringp files) (setq files (list files)))
8140 (cond
8141 ((eq (car desc) :tag)
8142 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8143 ((eq (car desc) :todo)
8144 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8145 ((eq (car desc) :regexp)
8146 (setq descre (cdr desc)))
8147 ((eq (car desc) :level)
8148 (setq descre (concat "^\\*\\{" (number-to-string
8149 (if org-odd-levels-only
8150 (1- (* 2 (cdr desc)))
8151 (cdr desc)))
8152 "\\}[ \t]")))
8153 ((eq (car desc) :maxlevel)
8154 (setq fast-path-p t)
8155 (setq descre (concat "^\\*\\{1," (number-to-string
8156 (if org-odd-levels-only
8157 (1- (* 2 (cdr desc)))
8158 (cdr desc)))
8159 "\\}[ \t]")))
8160 (t (error "Bad refiling target description %s" desc)))
8161 (while (setq f (pop files))
8162 (save-excursion
8163 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8164 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8165 (setq f (expand-file-name f))
8166 (if (eq org-refile-use-outline-path 'file)
8167 (push (list (file-name-nondirectory f) f nil nil) targets))
8168 (save-excursion
8169 (save-restriction
8170 (widen)
8171 (goto-char (point-min))
8172 (while (re-search-forward descre nil t)
8173 (goto-char (point-at-bol))
8174 (when (looking-at org-complex-heading-regexp)
8175 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8176 txt (org-link-display-format (match-string 4))
8177 re (concat "^" (regexp-quote
8178 (buffer-substring (match-beginning 1)
8179 (match-end 4)))))
8180 (if (match-end 5) (setq re (concat re "[ \t]+"
8181 (regexp-quote
8182 (match-string 5)))))
8183 (setq re (concat re "[ \t]*$"))
8184 (when org-refile-use-outline-path
8185 (setq txt (mapconcat 'org-protect-slash
8186 (append
8187 (if (eq org-refile-use-outline-path 'file)
8188 (list (file-name-nondirectory
8189 (buffer-file-name (buffer-base-buffer))))
8190 (if (eq org-refile-use-outline-path 'full-file-path)
8191 (list (buffer-file-name (buffer-base-buffer)))))
8192 (org-get-outline-path fast-path-p level txt)
8193 (list txt))
8194 "/")))
8195 (push (list txt f re (point)) targets))
8196 (goto-char (point-at-eol))))))))
8197 (message "Getting targets...done")
8198 (nreverse targets))))
8200 (defun org-protect-slash (s)
8201 (while (string-match "/" s)
8202 (setq s (replace-match "\\" t t s)))
8205 (defvar org-olpa (make-vector 20 nil))
8207 (defun org-get-outline-path (&optional fastp level heading)
8208 "Return the outline path to the current entry, as a list."
8209 (if fastp
8210 (progn
8211 (if (> level 19)
8212 (error "Outline path failure, more than 19 levels."))
8213 (loop for i from level upto 19 do
8214 (aset org-olpa i nil))
8215 (prog1
8216 (delq nil (append org-olpa nil))
8217 (aset org-olpa level heading)))
8218 (let (rtn)
8219 (save-excursion
8220 (while (org-up-heading-safe)
8221 (when (looking-at org-complex-heading-regexp)
8222 (push (org-match-string-no-properties 4) rtn)))
8223 rtn))))
8225 (defvar org-refile-history nil
8226 "History for refiling operations.")
8228 (defun org-refile (&optional goto default-buffer)
8229 "Move the entry at point to another heading.
8230 The list of target headings is compiled using the information in
8231 `org-refile-targets', which see. This list is created before each use
8232 and will therefore always be up-to-date.
8234 At the target location, the entry is filed as a subitem of the target heading.
8235 Depending on `org-reverse-note-order', the new subitem will either be the
8236 first or the last subitem.
8238 If there is an active region, all entries in that region will be moved.
8239 However, the region must fulfil the requirement that the first heading
8240 is the first one sets the top-level of the moved text - at most siblings
8241 below it are allowed.
8243 With prefix arg GOTO, the command will only visit the target location,
8244 not actually move anything.
8245 With a double prefix `C-u C-u', go to the location where the last refiling
8246 operation has put the subtree.
8248 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8249 (interactive "P")
8250 (let* ((cbuf (current-buffer))
8251 (regionp (org-region-active-p))
8252 (region-start (and regionp (region-beginning)))
8253 (region-end (and regionp (region-end)))
8254 (region-length (and regionp (- region-end region-start)))
8255 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8256 pos it nbuf file re level reversed)
8257 (when regionp (goto-char region-start)
8258 (unless (org-kill-is-subtree-p
8259 (buffer-substring region-start region-end))
8260 (error "The region is not a (sequence of) subtree(s)")))
8261 (if (equal goto '(16))
8262 (org-refile-goto-last-stored)
8263 (when (setq it (org-refile-get-location
8264 (if goto "Goto: " "Refile to: ") default-buffer))
8265 (setq file (nth 1 it)
8266 re (nth 2 it)
8267 pos (nth 3 it))
8268 (if (and (not goto)
8270 (equal (buffer-file-name) file)
8271 (if regionp
8272 (and (>= pos region-start)
8273 (<= pos region-end))
8274 (and (>= pos (point))
8275 (< pos (save-excursion
8276 (org-end-of-subtree t t))))))
8277 (error "Cannot refile to position inside the tree or region"))
8279 (setq nbuf (or (find-buffer-visiting file)
8280 (find-file-noselect file)))
8281 (if goto
8282 (progn
8283 (switch-to-buffer nbuf)
8284 (goto-char pos)
8285 (org-show-context 'org-goto))
8286 (if regionp
8287 (progn
8288 (kill-new (buffer-substring region-start region-end))
8289 (org-save-markers-in-region region-start region-end))
8290 (org-copy-subtree 1 nil t))
8291 (save-excursion
8292 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8293 (find-file-noselect file))))
8294 (setq reversed (org-notes-order-reversed-p))
8295 (save-excursion
8296 (save-restriction
8297 (widen)
8298 (if pos
8299 (progn
8300 (goto-char pos)
8301 (looking-at outline-regexp)
8302 (setq level (org-get-valid-level (funcall outline-level) 1))
8303 (goto-char
8304 (if reversed
8305 (or (outline-next-heading) (point-max))
8306 (or (save-excursion (outline-get-next-sibling))
8307 (org-end-of-subtree t t)
8308 (point-max)))))
8309 (setq level 1)
8310 (if (not reversed)
8311 (goto-char (point-max))
8312 (goto-char (point-min))
8313 (or (outline-next-heading) (goto-char (point-max)))))
8314 (if (not (bolp)) (newline))
8315 (bookmark-set "org-refile-last-stored")
8316 (org-paste-subtree level))))
8317 (if regionp
8318 (delete-region (point) (+ (point) region-length))
8319 (org-cut-subtree))
8320 (setq org-markers-to-move nil)
8321 (message "Refiled to \"%s\"" (car it)))))))
8323 (defun org-refile-goto-last-stored ()
8324 "Go to the location where the last refile was stored."
8325 (interactive)
8326 (bookmark-jump "org-refile-last-stored")
8327 (message "This is the location of the last refile"))
8329 (defun org-refile-get-location (&optional prompt default-buffer)
8330 "Prompt the user for a refile location, using PROMPT."
8331 (let ((org-refile-targets org-refile-targets)
8332 (org-refile-use-outline-path org-refile-use-outline-path))
8333 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8334 (unless org-refile-target-table
8335 (error "No refile targets"))
8336 (let* ((cbuf (current-buffer))
8337 (partial-completion-mode nil)
8338 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8339 (cfunc (if (and org-refile-use-outline-path
8340 org-outline-path-complete-in-steps)
8341 'org-olpath-completing-read
8342 'org-ido-completing-read))
8343 (extra (if org-refile-use-outline-path "/" ""))
8344 (filename (and cfn (expand-file-name cfn)))
8345 (tbl (mapcar
8346 (lambda (x)
8347 (if (and (not (member org-refile-use-outline-path
8348 '(file full-file-path)))
8349 (not (equal filename (nth 1 x))))
8350 (cons (concat (car x) extra " ("
8351 (file-name-nondirectory (nth 1 x)) ")")
8352 (cdr x))
8353 (cons (concat (car x) extra) (cdr x))))
8354 org-refile-target-table))
8355 (completion-ignore-case t))
8356 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
8357 tbl)))
8359 (defun org-olpath-completing-read (prompt collection &rest args)
8360 "Read an outline path like a file name."
8361 (let ((thetable collection)
8362 (org-completion-use-ido nil)) ; does not work with ido.
8363 (apply
8364 'org-ido-completing-read prompt
8365 (lambda (string predicate &optional flag)
8366 (let (rtn r f (l (length string)))
8367 (cond
8368 ((eq flag nil)
8369 ;; try completion
8370 (try-completion string thetable))
8371 ((eq flag t)
8372 ;; all-completions
8373 (setq rtn (all-completions string thetable predicate))
8374 (mapcar
8375 (lambda (x)
8376 (setq r (substring x l))
8377 (if (string-match " ([^)]*)$" x)
8378 (setq f (match-string 0 x))
8379 (setq f ""))
8380 (if (string-match "/" r)
8381 (concat string (substring r 0 (match-end 0)) f)
8383 rtn))
8384 ((eq flag 'lambda)
8385 ;; exact match?
8386 (assoc string thetable)))
8388 args)))
8390 ;;;; Dynamic blocks
8392 (defun org-find-dblock (name)
8393 "Find the first dynamic block with name NAME in the buffer.
8394 If not found, stay at current position and return nil."
8395 (let (pos)
8396 (save-excursion
8397 (goto-char (point-min))
8398 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8399 nil t)
8400 (match-beginning 0))))
8401 (if pos (goto-char pos))
8402 pos))
8404 (defconst org-dblock-start-re
8405 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8406 "Matches the startline of a dynamic block, with parameters.")
8408 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8409 "Matches the end of a dynamic block.")
8411 (defun org-create-dblock (plist)
8412 "Create a dynamic block section, with parameters taken from PLIST.
8413 PLIST must contain a :name entry which is used as name of the block."
8414 (unless (bolp) (newline))
8415 (let ((name (plist-get plist :name)))
8416 (insert "#+BEGIN: " name)
8417 (while plist
8418 (if (eq (car plist) :name)
8419 (setq plist (cddr plist))
8420 (insert " " (prin1-to-string (pop plist)))))
8421 (insert "\n\n#+END:\n")
8422 (beginning-of-line -2)))
8424 (defun org-prepare-dblock ()
8425 "Prepare dynamic block for refresh.
8426 This empties the block, puts the cursor at the insert position and returns
8427 the property list including an extra property :name with the block name."
8428 (unless (looking-at org-dblock-start-re)
8429 (error "Not at a dynamic block"))
8430 (let* ((begdel (1+ (match-end 0)))
8431 (name (org-no-properties (match-string 1)))
8432 (params (append (list :name name)
8433 (read (concat "(" (match-string 3) ")")))))
8434 (unless (re-search-forward org-dblock-end-re nil t)
8435 (error "Dynamic block not terminated"))
8436 (setq params
8437 (append params
8438 (list :content (buffer-substring
8439 begdel (match-beginning 0)))))
8440 (delete-region begdel (match-beginning 0))
8441 (goto-char begdel)
8442 (open-line 1)
8443 params))
8445 (defun org-map-dblocks (&optional command)
8446 "Apply COMMAND to all dynamic blocks in the current buffer.
8447 If COMMAND is not given, use `org-update-dblock'."
8448 (let ((cmd (or command 'org-update-dblock))
8449 pos)
8450 (save-excursion
8451 (goto-char (point-min))
8452 (while (re-search-forward org-dblock-start-re nil t)
8453 (goto-char (setq pos (match-beginning 0)))
8454 (condition-case nil
8455 (funcall cmd)
8456 (error (message "Error during update of dynamic block")))
8457 (goto-char pos)
8458 (unless (re-search-forward org-dblock-end-re nil t)
8459 (error "Dynamic block not terminated"))))))
8461 (defun org-dblock-update (&optional arg)
8462 "User command for updating dynamic blocks.
8463 Update the dynamic block at point. With prefix ARG, update all dynamic
8464 blocks in the buffer."
8465 (interactive "P")
8466 (if arg
8467 (org-update-all-dblocks)
8468 (or (looking-at org-dblock-start-re)
8469 (org-beginning-of-dblock))
8470 (org-update-dblock)))
8472 (defun org-update-dblock ()
8473 "Update the dynamic block at point
8474 This means to empty the block, parse for parameters and then call
8475 the correct writing function."
8476 (save-window-excursion
8477 (let* ((pos (point))
8478 (line (org-current-line))
8479 (params (org-prepare-dblock))
8480 (name (plist-get params :name))
8481 (cmd (intern (concat "org-dblock-write:" name))))
8482 (message "Updating dynamic block `%s' at line %d..." name line)
8483 (funcall cmd params)
8484 (message "Updating dynamic block `%s' at line %d...done" name line)
8485 (goto-char pos))))
8487 (defun org-beginning-of-dblock ()
8488 "Find the beginning of the dynamic block at point.
8489 Error if there is no such block at point."
8490 (let ((pos (point))
8491 beg)
8492 (end-of-line 1)
8493 (if (and (re-search-backward org-dblock-start-re nil t)
8494 (setq beg (match-beginning 0))
8495 (re-search-forward org-dblock-end-re nil t)
8496 (> (match-end 0) pos))
8497 (goto-char beg)
8498 (goto-char pos)
8499 (error "Not in a dynamic block"))))
8501 (defun org-update-all-dblocks ()
8502 "Update all dynamic blocks in the buffer.
8503 This function can be used in a hook."
8504 (when (org-mode-p)
8505 (org-map-dblocks 'org-update-dblock)))
8508 ;;;; Completion
8510 (defconst org-additional-option-like-keywords
8511 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8512 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8513 "BEGIN_EXAMPLE" "END_EXAMPLE"
8514 "BEGIN_QUOTE" "END_QUOTE"
8515 "BEGIN_VERSE" "END_VERSE"
8516 "BEGIN_CENTER" "END_CENTER"
8517 "BEGIN_SRC" "END_SRC"
8518 "CATEGORY" "COLUMNS"
8519 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8521 (defcustom org-structure-template-alist
8523 ("s" "#+begin_src ?\n\n#+end_src"
8524 "<src lang=\"?\">\n\n</src>")
8525 ("e" "#+begin_example\n?\n#+end_example"
8526 "<example>\n?\n</example>")
8527 ("q" "#+begin_quote\n?\n#+end_quote"
8528 "<quote>\n?\n</quote>")
8529 ("v" "#+begin_verse\n?\n#+end_verse"
8530 "<verse>\n?\n/verse>")
8531 ("c" "#+begin_center\n?\n#+end_center"
8532 "<center>\n?\n/center>")
8533 ("l" "#+begin_latex\n?\n#+end_latex"
8534 "<literal style=\"latex\">\n?\n</literal>")
8535 ("L" "#+latex: "
8536 "<literal style=\"latex\">?</literal>")
8537 ("h" "#+begin_html\n?\n#+end_html"
8538 "<literal style=\"html\">\n?\n</literal>")
8539 ("H" "#+html: "
8540 "<literal style=\"html\">?</literal>")
8541 ("a" "#+begin_ascii\n?\n#+end_ascii")
8542 ("A" "#+ascii: ")
8543 ("i" "#+include %file ?"
8544 "<include file=%file markup=\"?\">")
8546 "Structure completion elements.
8547 This is a list of abbreviation keys and values. The value gets inserted
8548 it you type @samp{.} followed by the key and then the completion key,
8549 usually `M-TAB'. %file will be replaced by a file name after prompting
8550 for the file using completion.
8551 There are two templates for each key, the first uses the original Org syntax,
8552 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8553 the default when the /org-mtags.el/ module has been loaded. See also the
8554 variable `org-mtags-prefer-muse-templates'.
8555 This is an experimental feature, it is undecided if it is going to stay in."
8556 :group 'org-completion
8557 :type '(repeat
8558 (string :tag "Key")
8559 (string :tag "Template")
8560 (string :tag "Muse Template")))
8562 (defun org-try-structure-completion ()
8563 "Try to complete a structure template before point.
8564 This looks for strings like \"<e\" on an otherwise empty line and
8565 expands them."
8566 (let ((l (buffer-substring (point-at-bol) (point)))
8568 (when (and (looking-at "[ \t]*$")
8569 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8570 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8571 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8572 (match-beginning 1)) a)
8573 t)))
8575 (defun org-complete-expand-structure-template (start cell)
8576 "Expand a structure template."
8577 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8578 (rpl (nth (if musep 2 1) cell)))
8579 (delete-region start (point))
8580 (when (string-match "\\`#\\+" rpl)
8581 (cond
8582 ((bolp))
8583 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8584 (delete-region (point-at-bol) (point)))
8585 (t (newline))))
8586 (setq start (point))
8587 (if (string-match "%file" rpl)
8588 (setq rpl (replace-match
8589 (concat
8590 "\""
8591 (save-match-data
8592 (abbreviate-file-name (read-file-name "Include file: ")))
8593 "\"")
8594 t t rpl)))
8595 (insert rpl)
8596 (if (re-search-backward "\\?" start t) (delete-char 1))))
8599 (defun org-complete (&optional arg)
8600 "Perform completion on word at point.
8601 At the beginning of a headline, this completes TODO keywords as given in
8602 `org-todo-keywords'.
8603 If the current word is preceded by a backslash, completes the TeX symbols
8604 that are supported for HTML support.
8605 If the current word is preceded by \"#+\", completes special words for
8606 setting file options.
8607 In the line after \"#+STARTUP:, complete valid keywords.\"
8608 At all other locations, this simply calls the value of
8609 `org-completion-fallback-command'."
8610 (interactive "P")
8611 (org-without-partial-completion
8612 (catch 'exit
8613 (let* ((a nil)
8614 (end (point))
8615 (beg1 (save-excursion
8616 (skip-chars-backward (org-re "[:alnum:]_@"))
8617 (point)))
8618 (beg (save-excursion
8619 (skip-chars-backward "a-zA-Z0-9_:$")
8620 (point)))
8621 (confirm (lambda (x) (stringp (car x))))
8622 (searchhead (equal (char-before beg) ?*))
8623 (struct
8624 (when (and (member (char-before beg1) '(?. ?<))
8625 (setq a (assoc (buffer-substring beg1 (point))
8626 org-structure-template-alist)))
8627 (org-complete-expand-structure-template (1- beg1) a)
8628 (throw 'exit t)))
8629 (tag (and (equal (char-before beg1) ?:)
8630 (equal (char-after (point-at-bol)) ?*)))
8631 (prop (and (equal (char-before beg1) ?:)
8632 (not (equal (char-after (point-at-bol)) ?*))))
8633 (texp (equal (char-before beg) ?\\))
8634 (link (equal (char-before beg) ?\[))
8635 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8636 beg)
8637 "#+"))
8638 (startup (string-match "^#\\+STARTUP:.*"
8639 (buffer-substring (point-at-bol) (point))))
8640 (completion-ignore-case opt)
8641 (type nil)
8642 (tbl nil)
8643 (table (cond
8644 (opt
8645 (setq type :opt)
8646 (require 'org-exp)
8647 (append
8648 (mapcar
8649 (lambda (x)
8650 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8651 (cons (match-string 2 x) (match-string 1 x)))
8652 (org-split-string (org-get-current-options) "\n"))
8653 (mapcar 'list org-additional-option-like-keywords)))
8654 (startup
8655 (setq type :startup)
8656 org-startup-options)
8657 (link (append org-link-abbrev-alist-local
8658 org-link-abbrev-alist))
8659 (texp
8660 (setq type :tex)
8661 org-html-entities)
8662 ((string-match "\\`\\*+[ \t]+\\'"
8663 (buffer-substring (point-at-bol) beg))
8664 (setq type :todo)
8665 (mapcar 'list org-todo-keywords-1))
8666 (searchhead
8667 (setq type :searchhead)
8668 (save-excursion
8669 (goto-char (point-min))
8670 (while (re-search-forward org-todo-line-regexp nil t)
8671 (push (list
8672 (org-make-org-heading-search-string
8673 (match-string 3) t))
8674 tbl)))
8675 tbl)
8676 (tag (setq type :tag beg beg1)
8677 (or org-tag-alist (org-get-buffer-tags)))
8678 (prop (setq type :prop beg beg1)
8679 (mapcar 'list (org-buffer-property-keys nil t t)))
8680 (t (progn
8681 (call-interactively org-completion-fallback-command)
8682 (throw 'exit nil)))))
8683 (pattern (buffer-substring-no-properties beg end))
8684 (completion (try-completion pattern table confirm)))
8685 (cond ((eq completion t)
8686 (if (not (assoc (upcase pattern) table))
8687 (message "Already complete")
8688 (if (and (equal type :opt)
8689 (not (member (car (assoc (upcase pattern) table))
8690 org-additional-option-like-keywords)))
8691 (insert (substring (cdr (assoc (upcase pattern) table))
8692 (length pattern)))
8693 (if (memq type '(:tag :prop)) (insert ":")))))
8694 ((null completion)
8695 (message "Can't find completion for \"%s\"" pattern)
8696 (ding))
8697 ((not (string= pattern completion))
8698 (delete-region beg end)
8699 (if (string-match " +$" completion)
8700 (setq completion (replace-match "" t t completion)))
8701 (insert completion)
8702 (if (get-buffer-window "*Completions*")
8703 (delete-window (get-buffer-window "*Completions*")))
8704 (if (assoc completion table)
8705 (if (eq type :todo) (insert " ")
8706 (if (memq type '(:tag :prop)) (insert ":"))))
8707 (if (and (equal type :opt) (assoc completion table))
8708 (message "%s" (substitute-command-keys
8709 "Press \\[org-complete] again to insert example settings"))))
8711 (message "Making completion list...")
8712 (let ((list (sort (all-completions pattern table confirm)
8713 'string<)))
8714 (with-output-to-temp-buffer "*Completions*"
8715 (condition-case nil
8716 ;; Protection needed for XEmacs and emacs 21
8717 (display-completion-list list pattern)
8718 (error (display-completion-list list)))))
8719 (message "Making completion list...%s" "done")))))))
8721 ;;;; TODO, DEADLINE, Comments
8723 (defun org-toggle-comment ()
8724 "Change the COMMENT state of an entry."
8725 (interactive)
8726 (save-excursion
8727 (org-back-to-heading)
8728 (let (case-fold-search)
8729 (if (looking-at (concat outline-regexp
8730 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8731 (replace-match "" t t nil 1)
8732 (if (looking-at outline-regexp)
8733 (progn
8734 (goto-char (match-end 0))
8735 (insert org-comment-string " ")))))))
8737 (defvar org-last-todo-state-is-todo nil
8738 "This is non-nil when the last TODO state change led to a TODO state.
8739 If the last change removed the TODO tag or switched to DONE, then
8740 this is nil.")
8742 (defvar org-setting-tags nil) ; dynamically skipped
8744 (defun org-parse-local-options (string var)
8745 "Parse STRING for startup setting relevant for variable VAR."
8746 (let ((rtn (symbol-value var))
8747 e opts)
8748 (save-match-data
8749 (if (or (not string) (not (string-match "\\S-" string)))
8751 (setq opts (delq nil (mapcar (lambda (x)
8752 (setq e (assoc x org-startup-options))
8753 (if (eq (nth 1 e) var) e nil))
8754 (org-split-string string "[ \t]+"))))
8755 (if (not opts)
8757 (setq rtn nil)
8758 (while (setq e (pop opts))
8759 (if (not (nth 3 e))
8760 (setq rtn (nth 2 e))
8761 (if (not (listp rtn)) (setq rtn nil))
8762 (push (nth 2 e) rtn)))
8763 rtn)))))
8765 (defvar org-todo-setup-filter-hook nil
8766 "Hook for functions that pre-filter todo specs.
8768 Each function takes a todo spec and returns either `nil' or the spec
8769 transformed into canonical form." )
8771 (defvar org-todo-get-default-hook nil
8772 "Hook for functions that get a default item for todo.
8774 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8775 `nil' or a string to be used for the todo mark." )
8777 (defvar org-agenda-headline-snapshot-before-repeat)
8778 (defun org-todo (&optional arg)
8779 "Change the TODO state of an item.
8780 The state of an item is given by a keyword at the start of the heading,
8781 like
8782 *** TODO Write paper
8783 *** DONE Call mom
8785 The different keywords are specified in the variable `org-todo-keywords'.
8786 By default the available states are \"TODO\" and \"DONE\".
8787 So for this example: when the item starts with TODO, it is changed to DONE.
8788 When it starts with DONE, the DONE is removed. And when neither TODO nor
8789 DONE are present, add TODO at the beginning of the heading.
8791 With C-u prefix arg, use completion to determine the new state.
8792 With numeric prefix arg, switch to that state.
8793 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8794 With a tripple C-u prefix, circumvent any state blocking.
8796 For calling through lisp, arg is also interpreted in the following way:
8797 'none -> empty state
8798 \"\"(empty string) -> switch to empty state
8799 'done -> switch to DONE
8800 'nextset -> switch to the next set of keywords
8801 'previousset -> switch to the previous set of keywords
8802 \"WAITING\" -> switch to the specified keyword, but only if it
8803 really is a member of `org-todo-keywords'."
8804 (interactive "P")
8805 (if (equal arg '(16)) (setq arg 'nextset))
8806 (let ((org-blocker-hook org-blocker-hook)
8807 (case-fold-search nil))
8808 (when (equal arg '(64))
8809 (setq arg nil org-blocker-hook nil))
8810 (when (and org-blocker-hook
8811 (org-entry-get nil "NOBLOCKING"))
8812 (setq org-blocker-hook nil))
8813 (save-excursion
8814 (catch 'exit
8815 (org-back-to-heading)
8816 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8817 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
8818 (looking-at " *"))
8819 (let* ((match-data (match-data))
8820 (startpos (point-at-bol))
8821 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8822 (org-log-done org-log-done)
8823 (org-log-repeat org-log-repeat)
8824 (org-todo-log-states org-todo-log-states)
8825 (this (match-string 1))
8826 (hl-pos (match-beginning 0))
8827 (head (org-get-todo-sequence-head this))
8828 (ass (assoc head org-todo-kwd-alist))
8829 (interpret (nth 1 ass))
8830 (done-word (nth 3 ass))
8831 (final-done-word (nth 4 ass))
8832 (last-state (or this ""))
8833 (completion-ignore-case t)
8834 (member (member this org-todo-keywords-1))
8835 (tail (cdr member))
8836 (state (cond
8837 ((and org-todo-key-trigger
8838 (or (and (equal arg '(4))
8839 (eq org-use-fast-todo-selection 'prefix))
8840 (and (not arg) org-use-fast-todo-selection
8841 (not (eq org-use-fast-todo-selection
8842 'prefix)))))
8843 ;; Use fast selection
8844 (org-fast-todo-selection))
8845 ((and (equal arg '(4))
8846 (or (not org-use-fast-todo-selection)
8847 (not org-todo-key-trigger)))
8848 ;; Read a state with completion
8849 (org-ido-completing-read
8850 "State: " (mapcar (lambda(x) (list x))
8851 org-todo-keywords-1)
8852 nil t))
8853 ((eq arg 'right)
8854 (if this
8855 (if tail (car tail) nil)
8856 (car org-todo-keywords-1)))
8857 ((eq arg 'left)
8858 (if (equal member org-todo-keywords-1)
8860 (if this
8861 (nth (- (length org-todo-keywords-1)
8862 (length tail) 2)
8863 org-todo-keywords-1)
8864 (org-last org-todo-keywords-1))))
8865 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8866 (setq arg nil))) ; hack to fall back to cycling
8867 (arg
8868 ;; user or caller requests a specific state
8869 (cond
8870 ((equal arg "") nil)
8871 ((eq arg 'none) nil)
8872 ((eq arg 'done) (or done-word (car org-done-keywords)))
8873 ((eq arg 'nextset)
8874 (or (car (cdr (member head org-todo-heads)))
8875 (car org-todo-heads)))
8876 ((eq arg 'previousset)
8877 (let ((org-todo-heads (reverse org-todo-heads)))
8878 (or (car (cdr (member head org-todo-heads)))
8879 (car org-todo-heads))))
8880 ((car (member arg org-todo-keywords-1)))
8881 ((nth (1- (prefix-numeric-value arg))
8882 org-todo-keywords-1))))
8883 ((null member) (or head (car org-todo-keywords-1)))
8884 ((equal this final-done-word) nil) ;; -> make empty
8885 ((null tail) nil) ;; -> first entry
8886 ((memq interpret '(type priority))
8887 (if (eq this-command last-command)
8888 (car tail)
8889 (if (> (length tail) 0)
8890 (or done-word (car org-done-keywords))
8891 nil)))
8893 (car tail))))
8894 (state (or
8895 (run-hook-with-args-until-success
8896 'org-todo-get-default-hook state last-state)
8897 state))
8898 (next (if state (concat " " state " ") " "))
8899 (change-plist (list :type 'todo-state-change :from this :to state
8900 :position startpos))
8901 dolog now-done-p)
8902 (when org-blocker-hook
8903 (setq org-last-todo-state-is-todo
8904 (not (member this org-done-keywords)))
8905 (unless (save-excursion
8906 (save-match-data
8907 (run-hook-with-args-until-failure
8908 'org-blocker-hook change-plist)))
8909 (if (interactive-p)
8910 (error "TODO state change from %s to %s blocked" this state)
8911 ;; fail silently
8912 (message "TODO state change from %s to %s blocked" this state)
8913 (throw 'exit nil))))
8914 (store-match-data match-data)
8915 (replace-match next t t)
8916 (unless (pos-visible-in-window-p hl-pos)
8917 (message "TODO state changed to %s" (org-trim next)))
8918 (unless head
8919 (setq head (org-get-todo-sequence-head state)
8920 ass (assoc head org-todo-kwd-alist)
8921 interpret (nth 1 ass)
8922 done-word (nth 3 ass)
8923 final-done-word (nth 4 ass)))
8924 (when (memq arg '(nextset previousset))
8925 (message "Keyword-Set %d/%d: %s"
8926 (- (length org-todo-sets) -1
8927 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8928 (length org-todo-sets)
8929 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8930 (setq org-last-todo-state-is-todo
8931 (not (member state org-done-keywords)))
8932 (setq now-done-p (and (member state org-done-keywords)
8933 (not (member this org-done-keywords))))
8934 (and logging (org-local-logging logging))
8935 (when (and (or org-todo-log-states org-log-done)
8936 (not (memq arg '(nextset previousset))))
8937 ;; we need to look at recording a time and note
8938 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8939 (nth 2 (assoc this org-todo-log-states))))
8940 (when (and state
8941 (member state org-not-done-keywords)
8942 (not (member this org-not-done-keywords)))
8943 ;; This is now a todo state and was not one before
8944 ;; If there was a CLOSED time stamp, get rid of it.
8945 (org-add-planning-info nil nil 'closed))
8946 (when (and now-done-p org-log-done)
8947 ;; It is now done, and it was not done before
8948 (org-add-planning-info 'closed (org-current-time))
8949 (if (and (not dolog) (eq 'note org-log-done))
8950 (org-add-log-setup 'done state this 'findpos 'note)))
8951 (when (and state dolog)
8952 ;; This is a non-nil state, and we need to log it
8953 (org-add-log-setup 'state state this 'findpos dolog)))
8954 ;; Fixup tag positioning
8955 (org-todo-trigger-tag-changes state)
8956 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8957 (when org-provide-todo-statistics
8958 (org-update-parent-todo-statistics))
8959 (run-hooks 'org-after-todo-state-change-hook)
8960 (if (and arg (not (member state org-done-keywords)))
8961 (setq head (org-get-todo-sequence-head state)))
8962 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8963 ;; Do we need to trigger a repeat?
8964 (when now-done-p
8965 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8966 ;; This is for the agenda, take a snapshot of the headline.
8967 (save-match-data
8968 (setq org-agenda-headline-snapshot-before-repeat
8969 (org-get-heading))))
8970 (org-auto-repeat-maybe state))
8971 ;; Fixup cursor location if close to the keyword
8972 (if (and (outline-on-heading-p)
8973 (not (bolp))
8974 (save-excursion (beginning-of-line 1)
8975 (looking-at org-todo-line-regexp))
8976 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8977 (progn
8978 (goto-char (or (match-end 2) (match-end 1)))
8979 (and (looking-at " ") (just-one-space))))
8980 (when org-trigger-hook
8981 (save-excursion
8982 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8984 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
8985 "Block turning an entry into a TODO, using the hierarchy.
8986 This checks whether the current task should be blocked from state
8987 changes. Such blocking occurs when:
8989 1. The task has children which are not all in a completed state.
8991 2. A task has a parent with the property :ORDERED:, and there
8992 are siblings prior to the current task with incomplete
8993 status.
8995 3. The parent of the task is blocked because it has siblings that should
8996 be done first, or is child of a block grandparent TODO entry."
8998 (catch 'dont-block
8999 ;; If this is not a todo state change, or if this entry is already DONE,
9000 ;; do not block
9001 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9002 (member (plist-get change-plist :from)
9003 (cons 'done org-done-keywords))
9004 (member (plist-get change-plist :to)
9005 (cons 'todo org-not-done-keywords)))
9006 (throw 'dont-block t))
9007 ;; If this task has children, and any are undone, it's blocked
9008 (save-excursion
9009 (org-back-to-heading t)
9010 (let ((this-level (funcall outline-level)))
9011 (outline-next-heading)
9012 (let ((child-level (funcall outline-level)))
9013 (while (and (not (eobp))
9014 (> child-level this-level))
9015 ;; this todo has children, check whether they are all
9016 ;; completed
9017 (if (and (not (org-entry-is-done-p))
9018 (org-entry-is-todo-p))
9019 (throw 'dont-block nil))
9020 (outline-next-heading)
9021 (setq child-level (funcall outline-level))))))
9022 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9023 ;; any previous siblings are undone, it's blocked
9024 (save-excursion
9025 (org-back-to-heading t)
9026 (let* ((pos (point))
9027 (parent-pos (and (org-up-heading-safe) (point))))
9028 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9029 (when (and (org-entry-get (point) "ORDERED")
9030 (forward-line 1)
9031 (re-search-forward org-not-done-heading-regexp pos t))
9032 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9033 ;; Search further up the hierarchy, to see if an anchestor is blocked
9034 (while t
9035 (goto-char parent-pos)
9036 (if (not (looking-at org-not-done-heading-regexp))
9037 (throw 'dont-block t)) ; do not block, parent is not a TODO
9038 (setq pos (point))
9039 (setq parent-pos (and (org-up-heading-safe) (point)))
9040 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9041 (when (and (org-entry-get (point) "ORDERED")
9042 (forward-line 1)
9043 (re-search-forward org-not-done-heading-regexp pos t))
9044 (throw 'dont-block nil))))))) ; block, older sibling not done.
9046 (defcustom org-track-ordered-property-with-tag nil
9047 "Should the ORDERED property also be shown as a tag?
9048 The ORDERED property decides if an entry should require subtasks to be
9049 completed in sequence. Since a property is not very visible, setting
9050 this option means that toggling the ORDERED property with the command
9051 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9052 not relevant for the behavior, but it makes things more visible.
9054 Note that toggling the tag with tags commands will not change the property
9055 and therefore not influence behavior!
9057 This can be t, meaning the tag ORDERED should be used, It can also be a
9058 string to select a different tag for this task."
9059 :group 'org-todo
9060 :type '(choice
9061 (const :tag "No tracking" nil)
9062 (const :tag "Track with ORDERED tag" t)
9063 (string :tag "Use other tag")))
9065 (defun org-toggle-ordered-property ()
9066 "Toggle the ORDERED property of the current entry.
9067 For better visibility, you can track the value of this property with a tag.
9068 See variable `org-track-ordered-property-with-tag'."
9069 (interactive)
9070 (let* ((t1 org-track-ordered-property-with-tag)
9071 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9072 (save-excursion
9073 (org-back-to-heading)
9074 (if (org-entry-get nil "ORDERED")
9075 (progn
9076 (org-delete-property "ORDERED")
9077 (and tag (org-toggle-tag tag 'off))
9078 (message "Subtasks can be completed in arbitrary order"))
9079 (org-entry-put nil "ORDERED" "t")
9080 (and tag (org-toggle-tag tag 'on))
9081 (message "Subtasks must be completed in sequence")))))
9083 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9084 (defun org-block-todo-from-checkboxes (change-plist)
9085 "Block turning an entry into a TODO, using checkboxes.
9086 This checks whether the current task should be blocked from state
9087 changes because there are uncheckd boxes in this entry."
9088 (catch 'dont-block
9089 ;; If this is not a todo state change, or if this entry is already DONE,
9090 ;; do not block
9091 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9092 (member (plist-get change-plist :from)
9093 (cons 'done org-done-keywords))
9094 (member (plist-get change-plist :to)
9095 (cons 'todo org-not-done-keywords)))
9096 (throw 'dont-block t))
9097 ;; If this task has checkboxes that are not checked, it's blocked
9098 (save-excursion
9099 (org-back-to-heading t)
9100 (let ((beg (point)) end)
9101 (outline-next-heading)
9102 (setq end (point))
9103 (goto-char beg)
9104 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9105 end t)
9106 (progn
9107 (if (boundp 'org-blocked-by-checkboxes)
9108 (setq org-blocked-by-checkboxes t))
9109 (throw 'dont-block nil)))))
9110 t)) ; do not block
9112 (defun org-update-parent-todo-statistics ()
9113 "Update any statistics cookie in the parent of the current headline."
9114 (interactive)
9115 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9116 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9117 (catch 'exit
9118 (save-excursion
9119 (setq level (org-up-heading-safe))
9120 (unless level
9121 (throw 'exit nil))
9122 (while (re-search-forward box-re (point-at-eol) t)
9123 (setq cnt-all 0 cnt-done 0 cookie-present t)
9124 (setq is-percent (match-end 2))
9125 (save-match-data
9126 (unless (outline-next-heading) (throw 'exit nil))
9127 (while (looking-at org-todo-line-regexp)
9128 (setq kwd (match-string 2))
9129 (and kwd (setq cnt-all (1+ cnt-all)))
9130 (and (member kwd org-done-keywords)
9131 (setq cnt-done (1+ cnt-done)))
9132 (condition-case nil
9133 (org-forward-same-level 1)
9134 (error (end-of-line 1)))))
9135 (replace-match
9136 (if is-percent
9137 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9138 (format "[%d/%d]" cnt-done cnt-all))))
9139 (when cookie-present
9140 (run-hook-with-args 'org-after-todo-statistics-hook
9141 cnt-done (- cnt-all cnt-done)))))))
9143 (defvar org-after-todo-statistics-hook nil
9144 "Hook that is called after a TODO statistics cookie has been updated.
9145 Each function is called with two arguments: the number of not-done entries
9146 and the number of done entries.
9148 For example, the following function, when added to this hook, will switch
9149 an entry to DONE when all children are done, and back to TODO when new
9150 entries are set to a TODO status. Note that this hook is only called
9151 when there is a statistics cookie in the headline!
9153 (defun org-summary-todo (n-done n-not-done)
9154 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9155 (let (org-log-done org-log-states) ; turn off logging
9156 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9159 (defun org-todo-trigger-tag-changes (state)
9160 "Apply the changes defined in `org-todo-state-tags-triggers'."
9161 (let ((l org-todo-state-tags-triggers)
9162 changes)
9163 (when (or (not state) (equal state ""))
9164 (setq changes (append changes (cdr (assoc "" l)))))
9165 (when (and (stringp state) (> (length state) 0))
9166 (setq changes (append changes (cdr (assoc state l)))))
9167 (when (member state org-not-done-keywords)
9168 (setq changes (append changes (cdr (assoc 'todo l)))))
9169 (when (member state org-done-keywords)
9170 (setq changes (append changes (cdr (assoc 'done l)))))
9171 (dolist (c changes)
9172 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9174 (defun org-local-logging (value)
9175 "Get logging settings from a property VALUE."
9176 (let* (words w a)
9177 ;; directly set the variables, they are already local.
9178 (setq org-log-done nil
9179 org-log-repeat nil
9180 org-todo-log-states nil)
9181 (setq words (org-split-string value))
9182 (while (setq w (pop words))
9183 (cond
9184 ((setq a (assoc w org-startup-options))
9185 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9186 (set (nth 1 a) (nth 2 a))))
9187 ((setq a (org-extract-log-state-settings w))
9188 (and (member (car a) org-todo-keywords-1)
9189 (push a org-todo-log-states)))))))
9191 (defun org-get-todo-sequence-head (kwd)
9192 "Return the head of the TODO sequence to which KWD belongs.
9193 If KWD is not set, check if there is a text property remembering the
9194 right sequence."
9195 (let (p)
9196 (cond
9197 ((not kwd)
9198 (or (get-text-property (point-at-bol) 'org-todo-head)
9199 (progn
9200 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9201 nil (point-at-eol)))
9202 (get-text-property p 'org-todo-head))))
9203 ((not (member kwd org-todo-keywords-1))
9204 (car org-todo-keywords-1))
9205 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9207 (defun org-fast-todo-selection ()
9208 "Fast TODO keyword selection with single keys.
9209 Returns the new TODO keyword, or nil if no state change should occur."
9210 (let* ((fulltable org-todo-key-alist)
9211 (done-keywords org-done-keywords) ;; needed for the faces.
9212 (maxlen (apply 'max (mapcar
9213 (lambda (x)
9214 (if (stringp (car x)) (string-width (car x)) 0))
9215 fulltable)))
9216 (expert nil)
9217 (fwidth (+ maxlen 3 1 3))
9218 (ncol (/ (- (window-width) 4) fwidth))
9219 tg cnt e c tbl
9220 groups ingroup)
9221 (save-excursion
9222 (save-window-excursion
9223 (if expert
9224 (set-buffer (get-buffer-create " *Org todo*"))
9225 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9226 (erase-buffer)
9227 (org-set-local 'org-done-keywords done-keywords)
9228 (setq tbl fulltable cnt 0)
9229 (while (setq e (pop tbl))
9230 (cond
9231 ((equal e '(:startgroup))
9232 (push '() groups) (setq ingroup t)
9233 (when (not (= cnt 0))
9234 (setq cnt 0)
9235 (insert "\n"))
9236 (insert "{ "))
9237 ((equal e '(:endgroup))
9238 (setq ingroup nil cnt 0)
9239 (insert "}\n"))
9240 ((equal e '(:newline))
9241 (when (not (= cnt 0))
9242 (setq cnt 0)
9243 (insert "\n")
9244 (setq e (car tbl))
9245 (while (equal (car tbl) '(:newline))
9246 (insert "\n")
9247 (setq tbl (cdr tbl)))))
9249 (setq tg (car e) c (cdr e))
9250 (if ingroup (push tg (car groups)))
9251 (setq tg (org-add-props tg nil 'face
9252 (org-get-todo-face tg)))
9253 (if (and (= cnt 0) (not ingroup)) (insert " "))
9254 (insert "[" c "] " tg (make-string
9255 (- fwidth 4 (length tg)) ?\ ))
9256 (when (= (setq cnt (1+ cnt)) ncol)
9257 (insert "\n")
9258 (if ingroup (insert " "))
9259 (setq cnt 0)))))
9260 (insert "\n")
9261 (goto-char (point-min))
9262 (if (not expert) (org-fit-window-to-buffer))
9263 (message "[a-z..]:Set [SPC]:clear")
9264 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9265 (cond
9266 ((or (= c ?\C-g)
9267 (and (= c ?q) (not (rassoc c fulltable))))
9268 (setq quit-flag t))
9269 ((= c ?\ ) nil)
9270 ((setq e (rassoc c fulltable) tg (car e))
9272 (t (setq quit-flag t)))))))
9274 (defun org-entry-is-todo-p ()
9275 (member (org-get-todo-state) org-not-done-keywords))
9277 (defun org-entry-is-done-p ()
9278 (member (org-get-todo-state) org-done-keywords))
9280 (defun org-get-todo-state ()
9281 (save-excursion
9282 (org-back-to-heading t)
9283 (and (looking-at org-todo-line-regexp)
9284 (match-end 2)
9285 (match-string 2))))
9287 (defun org-at-date-range-p (&optional inactive-ok)
9288 "Is the cursor inside a date range?"
9289 (interactive)
9290 (save-excursion
9291 (catch 'exit
9292 (let ((pos (point)))
9293 (skip-chars-backward "^[<\r\n")
9294 (skip-chars-backward "<[")
9295 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9296 (>= (match-end 0) pos)
9297 (throw 'exit t))
9298 (skip-chars-backward "^<[\r\n")
9299 (skip-chars-backward "<[")
9300 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9301 (>= (match-end 0) pos)
9302 (throw 'exit t)))
9303 nil)))
9305 (defun org-get-repeat ()
9306 "Check if there is a deadline/schedule with repeater in this entry."
9307 (save-match-data
9308 (save-excursion
9309 (org-back-to-heading t)
9310 (if (re-search-forward
9311 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9312 (match-string 1)))))
9314 (defvar org-last-changed-timestamp)
9315 (defvar org-last-inserted-timestamp)
9316 (defvar org-log-post-message)
9317 (defvar org-log-note-purpose)
9318 (defvar org-log-note-how)
9319 (defvar org-log-note-extra)
9320 (defun org-auto-repeat-maybe (done-word)
9321 "Check if the current headline contains a repeated deadline/schedule.
9322 If yes, set TODO state back to what it was and change the base date
9323 of repeating deadline/scheduled time stamps to new date.
9324 This function is run automatically after each state change to a DONE state."
9325 ;; last-state is dynamically scoped into this function
9326 (let* ((repeat (org-get-repeat))
9327 (aa (assoc last-state org-todo-kwd-alist))
9328 (interpret (nth 1 aa))
9329 (head (nth 2 aa))
9330 (whata '(("d" . day) ("m" . month) ("y" . year)))
9331 (msg "Entry repeats: ")
9332 (org-log-done nil)
9333 (org-todo-log-states nil)
9334 (nshiftmax 10) (nshift 0)
9335 re type n what ts time)
9336 (when repeat
9337 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9338 (org-todo (if (eq interpret 'type) last-state head))
9339 (when org-log-repeat
9340 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9341 (memq 'org-add-log-note post-command-hook))
9342 ;; OK, we are already setup for some record
9343 (if (eq org-log-repeat 'note)
9344 ;; make sure we take a note, not only a time stamp
9345 (setq org-log-note-how 'note))
9346 ;; Set up for taking a record
9347 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9348 last-state
9349 'findpos org-log-repeat)))
9350 (org-back-to-heading t)
9351 (org-add-planning-info nil nil 'closed)
9352 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9353 org-deadline-time-regexp "\\)\\|\\("
9354 org-ts-regexp "\\)"))
9355 (while (re-search-forward
9356 re (save-excursion (outline-next-heading) (point)) t)
9357 (setq type (if (match-end 1) org-scheduled-string
9358 (if (match-end 3) org-deadline-string "Plain:"))
9359 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9360 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9361 (setq n (string-to-number (match-string 2 ts))
9362 what (match-string 3 ts))
9363 (if (equal what "w") (setq n (* n 7) what "d"))
9364 ;; Preparation, see if we need to modify the start date for the change
9365 (when (match-end 1)
9366 (setq time (save-match-data (org-time-string-to-time ts)))
9367 (cond
9368 ((equal (match-string 1 ts) ".")
9369 ;; Shift starting date to today
9370 (org-timestamp-change
9371 (- (time-to-days (current-time)) (time-to-days time))
9372 'day))
9373 ((equal (match-string 1 ts) "+")
9374 (while (or (= nshift 0)
9375 (<= (time-to-days time) (time-to-days (current-time))))
9376 (when (= (incf nshift) nshiftmax)
9377 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9378 (error "Abort")))
9379 (org-timestamp-change n (cdr (assoc what whata)))
9380 (org-at-timestamp-p t)
9381 (setq ts (match-string 1))
9382 (setq time (save-match-data (org-time-string-to-time ts))))
9383 (org-timestamp-change (- n) (cdr (assoc what whata)))
9384 ;; rematch, so that we have everything in place for the real shift
9385 (org-at-timestamp-p t)
9386 (setq ts (match-string 1))
9387 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9388 (org-timestamp-change n (cdr (assoc what whata)))
9389 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9390 (setq org-log-post-message msg)
9391 (message "%s" msg))))
9393 (defun org-show-todo-tree (arg)
9394 "Make a compact tree which shows all headlines marked with TODO.
9395 The tree will show the lines where the regexp matches, and all higher
9396 headlines above the match.
9397 With a \\[universal-argument] prefix, also show the DONE entries.
9398 With a numeric prefix N, construct a sparse tree for the Nth element
9399 of `org-todo-keywords-1'."
9400 (interactive "P")
9401 (let ((case-fold-search nil)
9402 (kwd-re
9403 (cond ((null arg) org-not-done-regexp)
9404 ((equal arg '(4))
9405 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9406 (mapcar 'list org-todo-keywords-1))))
9407 (concat "\\("
9408 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9409 "\\)\\>")))
9410 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9411 (regexp-quote (nth (1- (prefix-numeric-value arg))
9412 org-todo-keywords-1)))
9413 (t (error "Invalid prefix argument: %s" arg)))))
9414 (message "%d TODO entries found"
9415 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9417 (defun org-deadline (&optional remove time)
9418 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9419 With argument REMOVE, remove any deadline from the item.
9420 When TIME is set, it should be an internal time specification, and the
9421 scheduling will use the corresponding date."
9422 (interactive "P")
9423 (if remove
9424 (progn
9425 (org-remove-timestamp-with-keyword org-deadline-string)
9426 (message "Item no longer has a deadline."))
9427 (if (org-get-repeat)
9428 (error "Cannot change deadline on task with repeater, please do that by hand")
9429 (org-add-planning-info 'deadline time 'closed)
9430 (message "Deadline on %s" org-last-inserted-timestamp))))
9432 (defun org-schedule (&optional remove time)
9433 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9434 With argument REMOVE, remove any scheduling date from the item.
9435 When TIME is set, it should be an internal time specification, and the
9436 scheduling will use the corresponding date."
9437 (interactive "P")
9438 (if remove
9439 (progn
9440 (org-remove-timestamp-with-keyword org-scheduled-string)
9441 (message "Item is no longer scheduled."))
9442 (if (org-get-repeat)
9443 (error "Cannot reschedule task with repeater, please do that by hand")
9444 (org-add-planning-info 'scheduled time 'closed)
9445 (message "Scheduled to %s" org-last-inserted-timestamp))))
9447 (defun org-get-scheduled-time (pom &optional inherit)
9448 "Get the scheduled time as a time tuple, of a format suitable
9449 for calling org-schedule with, or if there is no scheduling,
9450 returns nil."
9451 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9452 (when time
9453 (apply 'encode-time (org-parse-time-string time)))))
9455 (defun org-get-deadline-time (pom &optional inherit)
9456 "Get the deadine as a time tuple, of a format suitable for
9457 calling org-deadlin with, or if there is no scheduling, returns
9458 nil."
9459 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9460 (when time
9461 (apply 'encode-time (org-parse-time-string time)))))
9463 (defun org-remove-timestamp-with-keyword (keyword)
9464 "Remove all time stamps with KEYWORD in the current entry."
9465 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9466 beg)
9467 (save-excursion
9468 (org-back-to-heading t)
9469 (setq beg (point))
9470 (org-end-of-subtree t t)
9471 (while (re-search-backward re beg t)
9472 (replace-match "")
9473 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9474 (equal (char-before) ?\ ))
9475 (backward-delete-char 1)
9476 (if (string-match "^[ \t]*$" (buffer-substring
9477 (point-at-bol) (point-at-eol)))
9478 (delete-region (point-at-bol)
9479 (min (point-max) (1+ (point-at-eol))))))))))
9481 (defun org-add-planning-info (what &optional time &rest remove)
9482 "Insert new timestamp with keyword in the line directly after the headline.
9483 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9484 If non is given, the user is prompted for a date.
9485 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9486 be removed."
9487 (interactive)
9488 (let (org-time-was-given org-end-time-was-given ts
9489 end default-time default-input)
9491 (catch 'exit
9492 (when (and (not time) (memq what '(scheduled deadline)))
9493 ;; Try to get a default date/time from existing timestamp
9494 (save-excursion
9495 (org-back-to-heading t)
9496 (setq end (save-excursion (outline-next-heading) (point)))
9497 (when (re-search-forward (if (eq what 'scheduled)
9498 org-scheduled-time-regexp
9499 org-deadline-time-regexp)
9500 end t)
9501 (setq ts (match-string 1)
9502 default-time
9503 (apply 'encode-time (org-parse-time-string ts))
9504 default-input (and ts (org-get-compact-tod ts))))))
9505 (when what
9506 ;; If necessary, get the time from the user
9507 (setq time (or time (org-read-date nil 'to-time nil nil
9508 default-time default-input))))
9510 (when (and org-insert-labeled-timestamps-at-point
9511 (member what '(scheduled deadline)))
9512 (insert
9513 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9514 (org-insert-time-stamp time org-time-was-given
9515 nil nil nil (list org-end-time-was-given))
9516 (setq what nil))
9517 (save-excursion
9518 (save-restriction
9519 (let (col list elt ts buffer-invisibility-spec)
9520 (org-back-to-heading t)
9521 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9522 (goto-char (match-end 1))
9523 (setq col (current-column))
9524 (goto-char (match-end 0))
9525 (if (eobp) (insert "\n") (forward-char 1))
9526 (when (and (not what)
9527 (not (looking-at
9528 (concat "[ \t]*"
9529 org-keyword-time-not-clock-regexp))))
9530 ;; Nothing to add, nothing to remove...... :-)
9531 (throw 'exit nil))
9532 (if (and (not (looking-at outline-regexp))
9533 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9534 "[^\r\n]*"))
9535 (not (equal (match-string 1) org-clock-string)))
9536 (narrow-to-region (match-beginning 0) (match-end 0))
9537 (insert-before-markers "\n")
9538 (backward-char 1)
9539 (narrow-to-region (point) (point))
9540 (and org-adapt-indentation (org-indent-to-column col)))
9541 ;; Check if we have to remove something.
9542 (setq list (cons what remove))
9543 (while list
9544 (setq elt (pop list))
9545 (goto-char (point-min))
9546 (when (or (and (eq elt 'scheduled)
9547 (re-search-forward org-scheduled-time-regexp nil t))
9548 (and (eq elt 'deadline)
9549 (re-search-forward org-deadline-time-regexp nil t))
9550 (and (eq elt 'closed)
9551 (re-search-forward org-closed-time-regexp nil t)))
9552 (replace-match "")
9553 (if (looking-at "--+<[^>]+>") (replace-match ""))
9554 (if (looking-at " +") (replace-match ""))))
9555 (goto-char (point-max))
9556 (when what
9557 (insert
9558 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9559 (cond ((eq what 'scheduled) org-scheduled-string)
9560 ((eq what 'deadline) org-deadline-string)
9561 ((eq what 'closed) org-closed-string))
9562 " ")
9563 (setq ts (org-insert-time-stamp
9564 time
9565 (or org-time-was-given
9566 (and (eq what 'closed) org-log-done-with-time))
9567 (eq what 'closed)
9568 nil nil (list org-end-time-was-given)))
9569 (end-of-line 1))
9570 (goto-char (point-min))
9571 (widen)
9572 (if (and (looking-at "[ \t]+\n")
9573 (equal (char-before) ?\n))
9574 (delete-region (1- (point)) (point-at-eol)))
9575 ts))))))
9577 (defvar org-log-note-marker (make-marker))
9578 (defvar org-log-note-purpose nil)
9579 (defvar org-log-note-state nil)
9580 (defvar org-log-note-previous-state nil)
9581 (defvar org-log-note-how nil)
9582 (defvar org-log-note-extra nil)
9583 (defvar org-log-note-window-configuration nil)
9584 (defvar org-log-note-return-to (make-marker))
9585 (defvar org-log-post-message nil
9586 "Message to be displayed after a log note has been stored.
9587 The auto-repeater uses this.")
9589 (defun org-add-note ()
9590 "Add a note to the current entry.
9591 This is done in the same way as adding a state change note."
9592 (interactive)
9593 (org-add-log-setup 'note nil nil 'findpos nil))
9595 (defvar org-property-end-re)
9596 (defun org-add-log-setup (&optional purpose state prev-state
9597 findpos how &optional extra)
9598 "Set up the post command hook to take a note.
9599 If this is about to TODO state change, the new state is expected in STATE.
9600 When FINDPOS is non-nil, find the correct position for the note in
9601 the current entry. If not, assume that it can be inserted at point.
9602 HOW is an indicator what kind of note should be created.
9603 EXTRA is additional text that will be inserted into the notes buffer."
9604 (let ((drawer (cond ((stringp org-log-into-drawer)
9605 org-log-into-drawer)
9606 (org-log-into-drawer "LOGBOOK")
9607 (t nil))))
9608 (save-restriction
9609 (save-excursion
9610 (when findpos
9611 (org-back-to-heading t)
9612 (narrow-to-region (point) (save-excursion
9613 (outline-next-heading) (point)))
9614 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9615 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9616 "[^\r\n]*\\)?"))
9617 (goto-char (match-end 0))
9618 (cond
9619 (drawer
9620 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9621 nil t)
9622 (progn
9623 (goto-char (match-end 0))
9624 (or org-log-states-order-reversed
9625 (and (re-search-forward org-property-end-re nil t)
9626 (goto-char (1- (match-beginning 0))))))
9627 (insert "\n:" drawer ":\n:END:")
9628 (beginning-of-line 0)
9629 (org-indent-line-function)
9630 (beginning-of-line 2)
9631 (org-indent-line-function)
9632 (end-of-line 0)))
9633 ((and org-log-state-notes-insert-after-drawers
9634 (save-excursion
9635 (forward-line) (looking-at org-drawer-regexp)))
9636 (forward-line)
9637 (while (looking-at org-drawer-regexp)
9638 (goto-char (match-end 0))
9639 (re-search-forward org-property-end-re (point-max) t)
9640 (forward-line))
9641 (forward-line -1)))
9642 (unless org-log-states-order-reversed
9643 (and (= (char-after) ?\n) (forward-char 1))
9644 (org-skip-over-state-notes)
9645 (skip-chars-backward " \t\n\r")))
9646 (move-marker org-log-note-marker (point))
9647 (setq org-log-note-purpose purpose
9648 org-log-note-state state
9649 org-log-note-previous-state prev-state
9650 org-log-note-how how
9651 org-log-note-extra extra)
9652 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9654 (defun org-skip-over-state-notes ()
9655 "Skip past the list of State notes in an entry."
9656 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9657 (while (looking-at "[ \t]*- State")
9658 (condition-case nil
9659 (org-next-item)
9660 (error (org-end-of-item)))))
9662 (defun org-add-log-note (&optional purpose)
9663 "Pop up a window for taking a note, and add this note later at point."
9664 (remove-hook 'post-command-hook 'org-add-log-note)
9665 (setq org-log-note-window-configuration (current-window-configuration))
9666 (delete-other-windows)
9667 (move-marker org-log-note-return-to (point))
9668 (switch-to-buffer (marker-buffer org-log-note-marker))
9669 (goto-char org-log-note-marker)
9670 (org-switch-to-buffer-other-window "*Org Note*")
9671 (erase-buffer)
9672 (if (memq org-log-note-how '(time state))
9673 (let (current-prefix-arg) (org-store-log-note))
9674 (let ((org-inhibit-startup t)) (org-mode))
9675 (insert (format "# Insert note for %s.
9676 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9677 (cond
9678 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9679 ((eq org-log-note-purpose 'done) "closed todo item")
9680 ((eq org-log-note-purpose 'state)
9681 (format "state change from \"%s\" to \"%s\""
9682 (or org-log-note-previous-state "")
9683 (or org-log-note-state "")))
9684 ((eq org-log-note-purpose 'note)
9685 "this entry")
9686 (t (error "This should not happen")))))
9687 (if org-log-note-extra (insert org-log-note-extra))
9688 (org-set-local 'org-finish-function 'org-store-log-note)))
9690 (defvar org-note-abort nil) ; dynamically scoped
9691 (defun org-store-log-note ()
9692 "Finish taking a log note, and insert it to where it belongs."
9693 (let ((txt (buffer-string))
9694 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9695 lines ind)
9696 (kill-buffer (current-buffer))
9697 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9698 (setq txt (replace-match "" t t txt)))
9699 (if (string-match "\\s-+\\'" txt)
9700 (setq txt (replace-match "" t t txt)))
9701 (setq lines (org-split-string txt "\n"))
9702 (when (and note (string-match "\\S-" note))
9703 (setq note
9704 (org-replace-escapes
9705 note
9706 (list (cons "%u" (user-login-name))
9707 (cons "%U" user-full-name)
9708 (cons "%t" (format-time-string
9709 (org-time-stamp-format 'long 'inactive)
9710 (current-time)))
9711 (cons "%s" (if org-log-note-state
9712 (concat "\"" org-log-note-state "\"")
9713 ""))
9714 (cons "%S" (if org-log-note-previous-state
9715 (concat "\"" org-log-note-previous-state "\"")
9716 "\"\"")))))
9717 (if lines (setq note (concat note " \\\\")))
9718 (push note lines))
9719 (when (or current-prefix-arg org-note-abort)
9720 (when org-log-into-drawer
9721 (org-remove-empty-drawer-at
9722 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
9723 org-log-note-marker))
9724 (setq lines nil))
9725 (when lines
9726 (save-excursion
9727 (set-buffer (marker-buffer org-log-note-marker))
9728 (save-excursion
9729 (goto-char org-log-note-marker)
9730 (move-marker org-log-note-marker nil)
9731 (end-of-line 1)
9732 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9733 (insert "- " (pop lines))
9734 (org-indent-line-function)
9735 (beginning-of-line 1)
9736 (looking-at "[ \t]*")
9737 (setq ind (concat (match-string 0) " "))
9738 (end-of-line 1)
9739 (while lines (insert "\n" ind (pop lines)))
9740 (message "Note stored")
9741 (org-back-to-heading t)
9742 (org-cycle-hide-drawers 'children)))))
9743 (set-window-configuration org-log-note-window-configuration)
9744 (with-current-buffer (marker-buffer org-log-note-return-to)
9745 (goto-char org-log-note-return-to))
9746 (move-marker org-log-note-return-to nil)
9747 (and org-log-post-message (message "%s" org-log-post-message)))
9749 (defun org-remove-empty-drawer-at (drawer pos)
9750 "Remove an emptyr DARWER drawer at position POS.
9751 POS may also be a marker."
9752 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
9753 (save-excursion
9754 (save-restriction
9755 (widen)
9756 (goto-char pos)
9757 (if (org-in-regexp
9758 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
9759 (replace-match ""))))))
9761 (defun org-sparse-tree (&optional arg)
9762 "Create a sparse tree, prompt for the details.
9763 This command can create sparse trees. You first need to select the type
9764 of match used to create the tree:
9766 t Show entries with a specific TODO keyword.
9767 m Show entries selected by a tags/property match.
9768 p Enter a property name and its value (both with completion on existing
9769 names/values) and show entries with that property.
9770 r Show entries matching a regular expression.
9771 d Show deadlines due within `org-deadline-warning-days'.
9772 b Show deadlines and scheduled items before a date.
9773 a Show deadlines and scheduled items after a date."
9774 (interactive "P")
9775 (let (ans kwd value)
9776 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
9777 (setq ans (read-char-exclusive))
9778 (cond
9779 ((equal ans ?d)
9780 (call-interactively 'org-check-deadlines))
9781 ((equal ans ?b)
9782 (call-interactively 'org-check-before-date))
9783 ((equal ans ?a)
9784 (call-interactively 'org-check-after-date))
9785 ((equal ans ?t)
9786 (org-show-todo-tree '(4)))
9787 ((member ans '(?T ?m))
9788 (call-interactively 'org-match-sparse-tree))
9789 ((member ans '(?p ?P))
9790 (setq kwd (org-ido-completing-read "Property: "
9791 (mapcar 'list (org-buffer-property-keys))))
9792 (setq value (org-ido-completing-read "Value: "
9793 (mapcar 'list (org-property-values kwd))))
9794 (unless (string-match "\\`{.*}\\'" value)
9795 (setq value (concat "\"" value "\"")))
9796 (org-match-sparse-tree arg (concat kwd "=" value)))
9797 ((member ans '(?r ?R ?/))
9798 (call-interactively 'org-occur))
9799 (t (error "No such sparse tree command \"%c\"" ans)))))
9801 (defvar org-occur-highlights nil
9802 "List of overlays used for occur matches.")
9803 (make-variable-buffer-local 'org-occur-highlights)
9804 (defvar org-occur-parameters nil
9805 "Parameters of the active org-occur calls.
9806 This is a list, each call to org-occur pushes as cons cell,
9807 containing the regular expression and the callback, onto the list.
9808 The list can contain several entries if `org-occur' has been called
9809 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9810 will only contain one set of parameters. When the highlights are
9811 removed (for example with `C-c C-c', or with the next edit (depending
9812 on `org-remove-highlights-with-change'), this variable is emptied
9813 as well.")
9814 (make-variable-buffer-local 'org-occur-parameters)
9816 (defun org-occur (regexp &optional keep-previous callback)
9817 "Make a compact tree which shows all matches of REGEXP.
9818 The tree will show the lines where the regexp matches, and all higher
9819 headlines above the match. It will also show the heading after the match,
9820 to make sure editing the matching entry is easy.
9821 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9822 call to `org-occur' will be kept, to allow stacking of calls to this
9823 command.
9824 If CALLBACK is non-nil, it is a function which is called to confirm
9825 that the match should indeed be shown."
9826 (interactive "sRegexp: \nP")
9827 (unless keep-previous
9828 (org-remove-occur-highlights nil nil t))
9829 (push (cons regexp callback) org-occur-parameters)
9830 (let ((cnt 0))
9831 (save-excursion
9832 (goto-char (point-min))
9833 (if (or (not keep-previous) ; do not want to keep
9834 (not org-occur-highlights)) ; no previous matches
9835 ;; hide everything
9836 (org-overview))
9837 (while (re-search-forward regexp nil t)
9838 (when (or (not callback)
9839 (save-match-data (funcall callback)))
9840 (setq cnt (1+ cnt))
9841 (when org-highlight-sparse-tree-matches
9842 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9843 (org-show-context 'occur-tree))))
9844 (when org-remove-highlights-with-change
9845 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9846 nil 'local))
9847 (unless org-sparse-tree-open-archived-trees
9848 (org-hide-archived-subtrees (point-min) (point-max)))
9849 (run-hooks 'org-occur-hook)
9850 (if (interactive-p)
9851 (message "%d match(es) for regexp %s" cnt regexp))
9852 cnt))
9854 (defun org-show-context (&optional key)
9855 "Make sure point and context and visible.
9856 How much context is shown depends upon the variables
9857 `org-show-hierarchy-above', `org-show-following-heading'. and
9858 `org-show-siblings'."
9859 (let ((heading-p (org-on-heading-p t))
9860 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9861 (following-p (org-get-alist-option org-show-following-heading key))
9862 (entry-p (org-get-alist-option org-show-entry-below key))
9863 (siblings-p (org-get-alist-option org-show-siblings key)))
9864 (catch 'exit
9865 ;; Show heading or entry text
9866 (if (and heading-p (not entry-p))
9867 (org-flag-heading nil) ; only show the heading
9868 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9869 (org-show-hidden-entry))) ; show entire entry
9870 (when following-p
9871 ;; Show next sibling, or heading below text
9872 (save-excursion
9873 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9874 (org-flag-heading nil))))
9875 (when siblings-p (org-show-siblings))
9876 (when hierarchy-p
9877 ;; show all higher headings, possibly with siblings
9878 (save-excursion
9879 (while (and (condition-case nil
9880 (progn (org-up-heading-all 1) t)
9881 (error nil))
9882 (not (bobp)))
9883 (org-flag-heading nil)
9884 (when siblings-p (org-show-siblings))))))))
9886 (defun org-reveal (&optional siblings)
9887 "Show current entry, hierarchy above it, and the following headline.
9888 This can be used to show a consistent set of context around locations
9889 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9890 not t for the search context.
9892 With optional argument SIBLINGS, on each level of the hierarchy all
9893 siblings are shown. This repairs the tree structure to what it would
9894 look like when opened with hierarchical calls to `org-cycle'."
9895 (interactive "P")
9896 (let ((org-show-hierarchy-above t)
9897 (org-show-following-heading t)
9898 (org-show-siblings (if siblings t org-show-siblings)))
9899 (org-show-context nil)))
9901 (defun org-highlight-new-match (beg end)
9902 "Highlight from BEG to END and mark the highlight is an occur headline."
9903 (let ((ov (org-make-overlay beg end)))
9904 (org-overlay-put ov 'face 'secondary-selection)
9905 (push ov org-occur-highlights)))
9907 (defun org-remove-occur-highlights (&optional beg end noremove)
9908 "Remove the occur highlights from the buffer.
9909 BEG and END are ignored. If NOREMOVE is nil, remove this function
9910 from the `before-change-functions' in the current buffer."
9911 (interactive)
9912 (unless org-inhibit-highlight-removal
9913 (mapc 'org-delete-overlay org-occur-highlights)
9914 (setq org-occur-highlights nil)
9915 (setq org-occur-parameters nil)
9916 (unless noremove
9917 (remove-hook 'before-change-functions
9918 'org-remove-occur-highlights 'local))))
9920 ;;;; Priorities
9922 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9923 "Regular expression matching the priority indicator.")
9925 (defvar org-remove-priority-next-time nil)
9927 (defun org-priority-up ()
9928 "Increase the priority of the current item."
9929 (interactive)
9930 (org-priority 'up))
9932 (defun org-priority-down ()
9933 "Decrease the priority of the current item."
9934 (interactive)
9935 (org-priority 'down))
9937 (defun org-priority (&optional action)
9938 "Change the priority of an item by ARG.
9939 ACTION can be `set', `up', `down', or a character."
9940 (interactive)
9941 (setq action (or action 'set))
9942 (let (current new news have remove)
9943 (save-excursion
9944 (org-back-to-heading t)
9945 (if (looking-at org-priority-regexp)
9946 (setq current (string-to-char (match-string 2))
9947 have t)
9948 (setq current org-default-priority))
9949 (cond
9950 ((or (eq action 'set)
9951 (if (featurep 'xemacs) (characterp action) (integerp action)))
9952 (if (not (eq action 'set))
9953 (setq new action)
9954 (message "Priority %c-%c, SPC to remove: "
9955 org-highest-priority org-lowest-priority)
9956 (setq new (read-char-exclusive)))
9957 (if (and (= (upcase org-highest-priority) org-highest-priority)
9958 (= (upcase org-lowest-priority) org-lowest-priority))
9959 (setq new (upcase new)))
9960 (cond ((equal new ?\ ) (setq remove t))
9961 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9962 (error "Priority must be between `%c' and `%c'"
9963 org-highest-priority org-lowest-priority))))
9964 ((eq action 'up)
9965 (if (and (not have) (eq last-command this-command))
9966 (setq new org-lowest-priority)
9967 (setq new (if (and org-priority-start-cycle-with-default (not have))
9968 org-default-priority (1- current)))))
9969 ((eq action 'down)
9970 (if (and (not have) (eq last-command this-command))
9971 (setq new org-highest-priority)
9972 (setq new (if (and org-priority-start-cycle-with-default (not have))
9973 org-default-priority (1+ current)))))
9974 (t (error "Invalid action")))
9975 (if (or (< (upcase new) org-highest-priority)
9976 (> (upcase new) org-lowest-priority))
9977 (setq remove t))
9978 (setq news (format "%c" new))
9979 (if have
9980 (if remove
9981 (replace-match "" t t nil 1)
9982 (replace-match news t t nil 2))
9983 (if remove
9984 (error "No priority cookie found in line")
9985 (let ((case-fold-search nil))
9986 (looking-at org-todo-line-regexp))
9987 (if (match-end 2)
9988 (progn
9989 (goto-char (match-end 2))
9990 (insert " [#" news "]"))
9991 (goto-char (match-beginning 3))
9992 (insert "[#" news "] ")))))
9993 (org-preserve-lc (org-set-tags nil 'align))
9994 (if remove
9995 (message "Priority removed")
9996 (message "Priority of current item set to %s" news))))
9999 (defun org-get-priority (s)
10000 "Find priority cookie and return priority."
10001 (save-match-data
10002 (if (not (string-match org-priority-regexp s))
10003 (* 1000 (- org-lowest-priority org-default-priority))
10004 (* 1000 (- org-lowest-priority
10005 (string-to-char (match-string 2 s)))))))
10007 ;;;; Tags
10009 (defvar org-agenda-archives-mode)
10010 (defvar org-map-continue-from nil
10011 "Position from where mapping should continue.
10012 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10014 (defvar org-scanner-tags nil
10015 "The current tag list while the tags scanner is running.")
10016 (defvar org-trust-scanner-tags nil
10017 "Should `org-get-tags-at' use the tags fro the scanner.
10018 This is for internal dynamical scoping only.
10019 When this is non-nil, the function `org-get-tags-at' will return the value
10020 of `org-scanner-tags' instead of building the list by itself. This
10021 can lead to large speed-ups when the tags scanner is used in a file with
10022 many entries, and when the list of tags is retrieved, for example to
10023 obtain a list of properties. Building the tags list for each entry in such
10024 a file becomes an N^2 operation - but with this variable set, it scales
10025 as N.")
10027 (defun org-scan-tags (action matcher &optional todo-only)
10028 "Scan headline tags with inheritance and produce output ACTION.
10030 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10031 or `agenda' to produce an entry list for an agenda view. It can also be
10032 a Lisp form or a function that should be called at each matched headline, in
10033 this case the return value is a list of all return values from these calls.
10035 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10036 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10037 only lines with a TODO keyword are included in the output."
10038 (require 'org-agenda)
10039 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10040 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10041 (org-re
10042 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10043 (props (list 'face 'default
10044 'done-face 'org-agenda-done
10045 'undone-face 'default
10046 'mouse-face 'highlight
10047 'org-not-done-regexp org-not-done-regexp
10048 'org-todo-regexp org-todo-regexp
10049 'keymap org-agenda-keymap
10050 'help-echo
10051 (format "mouse-2 or RET jump to org file %s"
10052 (abbreviate-file-name
10053 (or (buffer-file-name (buffer-base-buffer))
10054 (buffer-name (buffer-base-buffer)))))))
10055 (case-fold-search nil)
10056 (org-map-continue-from nil)
10057 lspos tags tags-list
10058 (tags-alist (list (cons 0 org-file-tags)))
10059 (llast 0) rtn rtn1 level category i txt
10060 todo marker entry priority)
10061 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10062 (setq action (list 'lambda nil action)))
10063 (save-excursion
10064 (goto-char (point-min))
10065 (when (eq action 'sparse-tree)
10066 (org-overview)
10067 (org-remove-occur-highlights))
10068 (while (re-search-forward re nil t)
10069 (catch :skip
10070 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10071 tags (if (match-end 4) (org-match-string-no-properties 4)))
10072 (goto-char (setq lspos (match-beginning 0)))
10073 (setq level (org-reduced-level (funcall outline-level))
10074 category (org-get-category))
10075 (setq i llast llast level)
10076 ;; remove tag lists from same and sublevels
10077 (while (>= i level)
10078 (when (setq entry (assoc i tags-alist))
10079 (setq tags-alist (delete entry tags-alist)))
10080 (setq i (1- i)))
10081 ;; add the next tags
10082 (when tags
10083 (setq tags (org-split-string tags ":")
10084 tags-alist
10085 (cons (cons level tags) tags-alist)))
10086 ;; compile tags for current headline
10087 (setq tags-list
10088 (if org-use-tag-inheritance
10089 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10090 tags)
10091 org-scanner-tags tags-list)
10092 (when org-use-tag-inheritance
10093 (setcdr (car tags-alist)
10094 (mapcar (lambda (x)
10095 (setq x (copy-sequence x))
10096 (org-add-prop-inherited x))
10097 (cdar tags-alist))))
10098 (when (and tags org-use-tag-inheritance
10099 (or (not (eq t org-use-tag-inheritance))
10100 org-tags-exclude-from-inheritance))
10101 ;; selective inheritance, remove uninherited ones
10102 (setcdr (car tags-alist)
10103 (org-remove-uniherited-tags (cdar tags-alist))))
10104 (when (and (or (not todo-only)
10105 (and (member todo org-not-done-keywords)
10106 (or (not org-agenda-tags-todo-honor-ignore-options)
10107 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10108 (let ((case-fold-search t)) (eval matcher))
10110 (not (member org-archive-tag tags-list))
10111 ;; we have an archive tag, should we use this anyway?
10112 (or (not org-agenda-skip-archived-trees)
10113 (and (eq action 'agenda) org-agenda-archives-mode))))
10114 (unless (eq action 'sparse-tree) (org-agenda-skip))
10116 ;; select this headline
10118 (cond
10119 ((eq action 'sparse-tree)
10120 (and org-highlight-sparse-tree-matches
10121 (org-get-heading) (match-end 0)
10122 (org-highlight-new-match
10123 (match-beginning 0) (match-beginning 1)))
10124 (org-show-context 'tags-tree))
10125 ((eq action 'agenda)
10126 (setq txt (org-format-agenda-item
10128 (concat
10129 (if (eq org-tags-match-list-sublevels 'indented)
10130 (make-string (1- level) ?.) "")
10131 (org-get-heading))
10132 category
10133 tags-list
10135 priority (org-get-priority txt))
10136 (goto-char lspos)
10137 (setq marker (org-agenda-new-marker))
10138 (org-add-props txt props
10139 'org-marker marker 'org-hd-marker marker 'org-category category
10140 'todo-state todo
10141 'priority priority 'type "tagsmatch")
10142 (push txt rtn))
10143 ((functionp action)
10144 (setq org-map-continue-from nil)
10145 (save-excursion
10146 (setq rtn1 (funcall action))
10147 (push rtn1 rtn)))
10148 (t (error "Invalid action")))
10150 ;; if we are to skip sublevels, jump to end of subtree
10151 (unless org-tags-match-list-sublevels
10152 (org-end-of-subtree t)
10153 (backward-char 1))))
10154 ;; Get the correct position from where to continue
10155 (if org-map-continue-from
10156 (goto-char org-map-continue-from)
10157 (and (= (point) lspos) (end-of-line 1)))))
10158 (when (and (eq action 'sparse-tree)
10159 (not org-sparse-tree-open-archived-trees))
10160 (org-hide-archived-subtrees (point-min) (point-max)))
10161 (nreverse rtn)))
10163 (defun org-remove-uniherited-tags (tags)
10164 "Remove all tags that are not inherited from the list TAGS."
10165 (cond
10166 ((eq org-use-tag-inheritance t)
10167 (if org-tags-exclude-from-inheritance
10168 (org-delete-all org-tags-exclude-from-inheritance tags)
10169 tags))
10170 ((not org-use-tag-inheritance) nil)
10171 ((stringp org-use-tag-inheritance)
10172 (delq nil (mapcar
10173 (lambda (x)
10174 (if (and (string-match org-use-tag-inheritance x)
10175 (not (member x org-tags-exclude-from-inheritance)))
10176 x nil))
10177 tags)))
10178 ((listp org-use-tag-inheritance)
10179 (delq nil (mapcar
10180 (lambda (x)
10181 (if (member x org-use-tag-inheritance) x nil))
10182 tags)))))
10184 (defvar todo-only) ;; dynamically scoped
10186 (defun org-match-sparse-tree (&optional todo-only match)
10187 "Create a sparse tree according to tags string MATCH.
10188 MATCH can contain positive and negative selection of tags, like
10189 \"+WORK+URGENT-WITHBOSS\".
10190 If optional argument TODO-ONLY is non-nil, only select lines that are
10191 also TODO lines."
10192 (interactive "P")
10193 (org-prepare-agenda-buffers (list (current-buffer)))
10194 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10196 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10198 (defvar org-cached-props nil)
10199 (defun org-cached-entry-get (pom property)
10200 (if (or (eq t org-use-property-inheritance)
10201 (and (stringp org-use-property-inheritance)
10202 (string-match org-use-property-inheritance property))
10203 (and (listp org-use-property-inheritance)
10204 (member property org-use-property-inheritance)))
10205 ;; Caching is not possible, check it directly
10206 (org-entry-get pom property 'inherit)
10207 ;; Get all properties, so that we can do complicated checks easily
10208 (cdr (assoc property (or org-cached-props
10209 (setq org-cached-props
10210 (org-entry-properties pom)))))))
10212 (defun org-global-tags-completion-table (&optional files)
10213 "Return the list of all tags in all agenda buffer/files."
10214 (save-excursion
10215 (org-uniquify
10216 (delq nil
10217 (apply 'append
10218 (mapcar
10219 (lambda (file)
10220 (set-buffer (find-file-noselect file))
10221 (append (org-get-buffer-tags)
10222 (mapcar (lambda (x) (if (stringp (car-safe x))
10223 (list (car-safe x)) nil))
10224 org-tag-alist)))
10225 (if (and files (car files))
10226 files
10227 (org-agenda-files))))))))
10229 (defun org-make-tags-matcher (match)
10230 "Create the TAGS//TODO matcher form for the selection string MATCH."
10231 ;; todo-only is scoped dynamically into this function, and the function
10232 ;; may change it if the matcher asks for it.
10233 (unless match
10234 ;; Get a new match request, with completion
10235 (let ((org-last-tags-completion-table
10236 (org-global-tags-completion-table)))
10237 (setq match (org-completing-read-no-ido
10238 "Match: " 'org-tags-completion-function nil nil nil
10239 'org-tags-history))))
10241 ;; Parse the string and create a lisp form
10242 (let ((match0 match)
10243 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10244 minus tag mm
10245 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10246 orterms term orlist re-p str-p level-p level-op time-p
10247 prop-p pn pv po cat-p gv rest)
10248 (if (string-match "/+" match)
10249 ;; match contains also a todo-matching request
10250 (progn
10251 (setq tagsmatch (substring match 0 (match-beginning 0))
10252 todomatch (substring match (match-end 0)))
10253 (if (string-match "^!" todomatch)
10254 (setq todo-only t todomatch (substring todomatch 1)))
10255 (if (string-match "^\\s-*$" todomatch)
10256 (setq todomatch nil)))
10257 ;; only matching tags
10258 (setq tagsmatch match todomatch nil))
10260 ;; Make the tags matcher
10261 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10262 (setq tagsmatcher t)
10263 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10264 (while (setq term (pop orterms))
10265 (while (and (equal (substring term -1) "\\") orterms)
10266 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10267 (while (string-match re term)
10268 (setq rest (substring term (match-end 0))
10269 minus (and (match-end 1)
10270 (equal (match-string 1 term) "-"))
10271 tag (match-string 2 term)
10272 re-p (equal (string-to-char tag) ?{)
10273 level-p (match-end 4)
10274 prop-p (match-end 5)
10275 mm (cond
10276 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10277 (level-p
10278 (setq level-op (org-op-to-function (match-string 3 term)))
10279 `(,level-op level ,(string-to-number
10280 (match-string 4 term))))
10281 (prop-p
10282 (setq pn (match-string 5 term)
10283 po (match-string 6 term)
10284 pv (match-string 7 term)
10285 cat-p (equal pn "CATEGORY")
10286 re-p (equal (string-to-char pv) ?{)
10287 str-p (equal (string-to-char pv) ?\")
10288 time-p (save-match-data
10289 (string-match "^\"[[<].*[]>]\"$" pv))
10290 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10291 (if time-p (setq pv (org-matcher-time pv)))
10292 (setq po (org-op-to-function po (if time-p 'time str-p)))
10293 (cond
10294 ((equal pn "CATEGORY")
10295 (setq gv '(get-text-property (point) 'org-category)))
10296 ((equal pn "TODO")
10297 (setq gv 'todo))
10299 (setq gv `(org-cached-entry-get nil ,pn))))
10300 (if re-p
10301 (if (eq po 'org<>)
10302 `(not (string-match ,pv (or ,gv "")))
10303 `(string-match ,pv (or ,gv "")))
10304 (if str-p
10305 `(,po (or ,gv "") ,pv)
10306 `(,po (string-to-number (or ,gv ""))
10307 ,(string-to-number pv) ))))
10308 (t `(member ,tag tags-list)))
10309 mm (if minus (list 'not mm) mm)
10310 term rest)
10311 (push mm tagsmatcher))
10312 (push (if (> (length tagsmatcher) 1)
10313 (cons 'and tagsmatcher)
10314 (car tagsmatcher))
10315 orlist)
10316 (setq tagsmatcher nil))
10317 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10318 (setq tagsmatcher
10319 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10320 ;; Make the todo matcher
10321 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10322 (setq todomatcher t)
10323 (setq orterms (org-split-string todomatch "|") orlist nil)
10324 (while (setq term (pop orterms))
10325 (while (string-match re term)
10326 (setq minus (and (match-end 1)
10327 (equal (match-string 1 term) "-"))
10328 kwd (match-string 2 term)
10329 re-p (equal (string-to-char kwd) ?{)
10330 term (substring term (match-end 0))
10331 mm (if re-p
10332 `(string-match ,(substring kwd 1 -1) todo)
10333 (list 'equal 'todo kwd))
10334 mm (if minus (list 'not mm) mm))
10335 (push mm todomatcher))
10336 (push (if (> (length todomatcher) 1)
10337 (cons 'and todomatcher)
10338 (car todomatcher))
10339 orlist)
10340 (setq todomatcher nil))
10341 (setq todomatcher (if (> (length orlist) 1)
10342 (cons 'or orlist) (car orlist))))
10344 ;; Return the string and lisp forms of the matcher
10345 (setq matcher (if todomatcher
10346 (list 'and tagsmatcher todomatcher)
10347 tagsmatcher))
10348 (cons match0 matcher)))
10350 (defun org-op-to-function (op &optional stringp)
10351 "Turn an operator into the appropriate function."
10352 (setq op
10353 (cond
10354 ((equal op "<" ) '(< string< org-time<))
10355 ((equal op ">" ) '(> org-string> org-time>))
10356 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10357 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10358 ((member op '("=" "==")) '(= string= org-time=))
10359 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10360 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10362 (defun org<> (a b) (not (= a b)))
10363 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10364 (defun org-string>= (a b) (not (string< a b)))
10365 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10366 (defun org-string<> (a b) (not (string= a b)))
10367 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10368 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10369 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10370 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10371 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10372 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10373 (defun org-2ft (s)
10374 "Convert S to a floating point time.
10375 If S is already a number, just return it. If it is a string, parse
10376 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10377 (cond
10378 ((numberp s) s)
10379 ((stringp s)
10380 (condition-case nil
10381 (float-time (apply 'encode-time (org-parse-time-string s)))
10382 (error 0.)))
10383 (t 0.)))
10385 (defun org-time-today ()
10386 "Time in seconds today at 0:00.
10387 Returns the float number of seconds since the beginning of the
10388 epoch to the beginning of today (00:00)."
10389 (float-time (apply 'encode-time
10390 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10392 (defun org-matcher-time (s)
10393 "Interpret a time comparison value."
10394 (save-match-data
10395 (cond
10396 ((string= s "<now>") (float-time))
10397 ((string= s "<today>") (org-time-today))
10398 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10399 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10400 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10401 (+ (org-time-today)
10402 (* (string-to-number (match-string 1 s))
10403 (cdr (assoc (match-string 2 s)
10404 '(("d" . 86400.0) ("w" . 604800.0)
10405 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10406 (t (org-2ft s)))))
10408 (defun org-match-any-p (re list)
10409 "Does re match any element of list?"
10410 (setq list (mapcar (lambda (x) (string-match re x)) list))
10411 (delq nil list))
10413 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10414 (defvar org-tags-overlay (org-make-overlay 1 1))
10415 (org-detach-overlay org-tags-overlay)
10417 (defun org-get-local-tags-at (&optional pos)
10418 "Get a list of tags defined in the current headline."
10419 (org-get-tags-at pos 'local))
10421 (defun org-get-local-tags ()
10422 "Get a list of tags defined in the current headline."
10423 (org-get-tags-at nil 'local))
10425 (defun org-get-tags-at (&optional pos local)
10426 "Get a list of all headline tags applicable at POS.
10427 POS defaults to point. If tags are inherited, the list contains
10428 the targets in the same sequence as the headlines appear, i.e.
10429 the tags of the current headline come last.
10430 When LOCAL is non-nil, only return tags from the current headline,
10431 ignore inherited ones."
10432 (interactive)
10433 (if (and org-trust-scanner-tags
10434 (or (not pos) (equal pos (point)))
10435 (not local))
10436 org-scanner-tags
10437 (let (tags ltags lastpos parent)
10438 (save-excursion
10439 (save-restriction
10440 (widen)
10441 (goto-char (or pos (point)))
10442 (save-match-data
10443 (catch 'done
10444 (condition-case nil
10445 (progn
10446 (org-back-to-heading t)
10447 (while (not (equal lastpos (point)))
10448 (setq lastpos (point))
10449 (when (looking-at
10450 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10451 (setq ltags (org-split-string
10452 (org-match-string-no-properties 1) ":"))
10453 (when parent
10454 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10455 (setq tags (append
10456 (if parent
10457 (org-remove-uniherited-tags ltags)
10458 ltags)
10459 tags)))
10460 (or org-use-tag-inheritance (throw 'done t))
10461 (if local (throw 'done t))
10462 (org-up-heading-all 1)
10463 (setq parent t)))
10464 (error nil)))))
10465 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10467 (defun org-add-prop-inherited (s)
10468 (add-text-properties 0 (length s) '(inherited t) s)
10471 (defun org-toggle-tag (tag &optional onoff)
10472 "Toggle the tag TAG for the current line.
10473 If ONOFF is `on' or `off', don't toggle but set to this state."
10474 (let (res current)
10475 (save-excursion
10476 (org-back-to-heading t)
10477 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10478 (point-at-eol) t)
10479 (progn
10480 (setq current (match-string 1))
10481 (replace-match ""))
10482 (setq current ""))
10483 (setq current (nreverse (org-split-string current ":")))
10484 (cond
10485 ((eq onoff 'on)
10486 (setq res t)
10487 (or (member tag current) (push tag current)))
10488 ((eq onoff 'off)
10489 (or (not (member tag current)) (setq current (delete tag current))))
10490 (t (if (member tag current)
10491 (setq current (delete tag current))
10492 (setq res t)
10493 (push tag current))))
10494 (end-of-line 1)
10495 (if current
10496 (progn
10497 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10498 (org-set-tags nil t))
10499 (delete-horizontal-space))
10500 (run-hooks 'org-after-tags-change-hook))
10501 res))
10503 (defun org-align-tags-here (to-col)
10504 ;; Assumes that this is a headline
10505 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10506 (beginning-of-line 1)
10507 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10508 (< pos (match-beginning 2)))
10509 (progn
10510 (setq tags-l (- (match-end 2) (match-beginning 2)))
10511 (goto-char (match-beginning 1))
10512 (insert " ")
10513 (delete-region (point) (1+ (match-beginning 2)))
10514 (setq ncol (max (1+ (current-column))
10515 (1+ col)
10516 (if (> to-col 0)
10517 to-col
10518 (- (abs to-col) tags-l))))
10519 (setq p (point))
10520 (insert (make-string (- ncol (current-column)) ?\ ))
10521 (setq ncol (current-column))
10522 (when indent-tabs-mode (tabify p (point-at-eol)))
10523 (org-move-to-column (min ncol col) t))
10524 (goto-char pos))))
10526 (defun org-set-tags-command (&optional arg just-align)
10527 "Call the set-tags command for the current entry."
10528 (interactive "P")
10529 (if (org-on-heading-p)
10530 (org-set-tags arg just-align)
10531 (save-excursion
10532 (org-back-to-heading t)
10533 (org-set-tags arg just-align))))
10535 (defun org-set-tags (&optional arg just-align)
10536 "Set the tags for the current headline.
10537 With prefix ARG, realign all tags in headings in the current buffer."
10538 (interactive "P")
10539 (let* ((re (concat "^" outline-regexp))
10540 (current (org-get-tags-string))
10541 (col (current-column))
10542 (org-setting-tags t)
10543 table current-tags inherited-tags ; computed below when needed
10544 tags p0 c0 c1 rpl)
10545 (if arg
10546 (save-excursion
10547 (goto-char (point-min))
10548 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10549 (while (re-search-forward re nil t)
10550 (org-set-tags nil t)
10551 (end-of-line 1)))
10552 (message "All tags realigned to column %d" org-tags-column))
10553 (if just-align
10554 (setq tags current)
10555 ;; Get a new set of tags from the user
10556 (save-excursion
10557 (setq table (append org-tag-persistent-alist
10558 (or org-tag-alist (org-get-buffer-tags)))
10559 org-last-tags-completion-table table
10560 current-tags (org-split-string current ":")
10561 inherited-tags (nreverse
10562 (nthcdr (length current-tags)
10563 (nreverse (org-get-tags-at))))
10564 tags
10565 (if (or (eq t org-use-fast-tag-selection)
10566 (and org-use-fast-tag-selection
10567 (delq nil (mapcar 'cdr table))))
10568 (org-fast-tag-selection
10569 current-tags inherited-tags table
10570 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10571 (let ((org-add-colon-after-tag-completion t))
10572 (org-trim
10573 (org-without-partial-completion
10574 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10575 nil nil current 'org-tags-history)))))))
10576 (while (string-match "[-+&]+" tags)
10577 ;; No boolean logic, just a list
10578 (setq tags (replace-match ":" t t tags))))
10580 (if (string-match "\\`[\t ]*\\'" tags)
10581 (setq tags "")
10582 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10583 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10585 ;; Insert new tags at the correct column
10586 (beginning-of-line 1)
10587 (cond
10588 ((and (equal current "") (equal tags "")))
10589 ((re-search-forward
10590 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10591 (point-at-eol) t)
10592 (if (equal tags "")
10593 (setq rpl "")
10594 (goto-char (match-beginning 0))
10595 (setq c0 (current-column) p0 (point)
10596 c1 (max (1+ c0) (if (> org-tags-column 0)
10597 org-tags-column
10598 (- (- org-tags-column) (length tags))))
10599 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10600 (replace-match rpl t t)
10601 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10602 tags)
10603 (t (error "Tags alignment failed")))
10604 (org-move-to-column col)
10605 (unless just-align
10606 (run-hooks 'org-after-tags-change-hook)))))
10608 (defun org-change-tag-in-region (beg end tag off)
10609 "Add or remove TAG for each entry in the region.
10610 This works in the agenda, and also in an org-mode buffer."
10611 (interactive
10612 (list (region-beginning) (region-end)
10613 (let ((org-last-tags-completion-table
10614 (if (org-mode-p)
10615 (org-get-buffer-tags)
10616 (org-global-tags-completion-table))))
10617 (org-ido-completing-read
10618 "Tag: " 'org-tags-completion-function nil nil nil
10619 'org-tags-history))
10620 (progn
10621 (message "[s]et or [r]emove? ")
10622 (equal (read-char-exclusive) ?r))))
10623 (if (fboundp 'deactivate-mark) (deactivate-mark))
10624 (let ((agendap (equal major-mode 'org-agenda-mode))
10625 l1 l2 m buf pos newhead (cnt 0))
10626 (goto-char end)
10627 (setq l2 (1- (org-current-line)))
10628 (goto-char beg)
10629 (setq l1 (org-current-line))
10630 (loop for l from l1 to l2 do
10631 (goto-line l)
10632 (setq m (get-text-property (point) 'org-hd-marker))
10633 (when (or (and (org-mode-p) (org-on-heading-p))
10634 (and agendap m))
10635 (setq buf (if agendap (marker-buffer m) (current-buffer))
10636 pos (if agendap m (point)))
10637 (with-current-buffer buf
10638 (save-excursion
10639 (save-restriction
10640 (goto-char pos)
10641 (setq cnt (1+ cnt))
10642 (org-toggle-tag tag (if off 'off 'on))
10643 (setq newhead (org-get-heading)))))
10644 (and agendap (org-agenda-change-all-lines newhead m))))
10645 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10647 (defun org-tags-completion-function (string predicate &optional flag)
10648 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10649 (confirm (lambda (x) (stringp (car x)))))
10650 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10651 (setq s1 (match-string 1 string)
10652 s2 (match-string 2 string))
10653 (setq s1 "" s2 string))
10654 (cond
10655 ((eq flag nil)
10656 ;; try completion
10657 (setq rtn (try-completion s2 ctable confirm))
10658 (if (stringp rtn)
10659 (setq rtn
10660 (concat s1 s2 (substring rtn (length s2))
10661 (if (and org-add-colon-after-tag-completion
10662 (assoc rtn ctable))
10663 ":" ""))))
10664 rtn)
10665 ((eq flag t)
10666 ;; all-completions
10667 (all-completions s2 ctable confirm)
10669 ((eq flag 'lambda)
10670 ;; exact match?
10671 (assoc s2 ctable)))
10674 (defun org-fast-tag-insert (kwd tags face &optional end)
10675 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10676 (insert (format "%-12s" (concat kwd ":"))
10677 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10678 (or end "")))
10680 (defun org-fast-tag-show-exit (flag)
10681 (save-excursion
10682 (goto-line 3)
10683 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10684 (replace-match ""))
10685 (when flag
10686 (end-of-line 1)
10687 (org-move-to-column (- (window-width) 19) t)
10688 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10690 (defun org-set-current-tags-overlay (current prefix)
10691 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10692 (if (featurep 'xemacs)
10693 (org-overlay-display org-tags-overlay (concat prefix s)
10694 'secondary-selection)
10695 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10696 (org-overlay-display org-tags-overlay (concat prefix s)))))
10698 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10699 "Fast tag selection with single keys.
10700 CURRENT is the current list of tags in the headline, INHERITED is the
10701 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10702 possibly with grouping information. TODO-TABLE is a similar table with
10703 TODO keywords, should these have keys assigned to them.
10704 If the keys are nil, a-z are automatically assigned.
10705 Returns the new tags string, or nil to not change the current settings."
10706 (let* ((fulltable (append table todo-table))
10707 (maxlen (apply 'max (mapcar
10708 (lambda (x)
10709 (if (stringp (car x)) (string-width (car x)) 0))
10710 fulltable)))
10711 (buf (current-buffer))
10712 (expert (eq org-fast-tag-selection-single-key 'expert))
10713 (buffer-tags nil)
10714 (fwidth (+ maxlen 3 1 3))
10715 (ncol (/ (- (window-width) 4) fwidth))
10716 (i-face 'org-done)
10717 (c-face 'org-todo)
10718 tg cnt e c char c1 c2 ntable tbl rtn
10719 ov-start ov-end ov-prefix
10720 (exit-after-next org-fast-tag-selection-single-key)
10721 (done-keywords org-done-keywords)
10722 groups ingroup)
10723 (save-excursion
10724 (beginning-of-line 1)
10725 (if (looking-at
10726 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10727 (setq ov-start (match-beginning 1)
10728 ov-end (match-end 1)
10729 ov-prefix "")
10730 (setq ov-start (1- (point-at-eol))
10731 ov-end (1+ ov-start))
10732 (skip-chars-forward "^\n\r")
10733 (setq ov-prefix
10734 (concat
10735 (buffer-substring (1- (point)) (point))
10736 (if (> (current-column) org-tags-column)
10738 (make-string (- org-tags-column (current-column)) ?\ ))))))
10739 (org-move-overlay org-tags-overlay ov-start ov-end)
10740 (save-window-excursion
10741 (if expert
10742 (set-buffer (get-buffer-create " *Org tags*"))
10743 (delete-other-windows)
10744 (split-window-vertically)
10745 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10746 (erase-buffer)
10747 (org-set-local 'org-done-keywords done-keywords)
10748 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10749 (org-fast-tag-insert "Current" current c-face "\n\n")
10750 (org-fast-tag-show-exit exit-after-next)
10751 (org-set-current-tags-overlay current ov-prefix)
10752 (setq tbl fulltable char ?a cnt 0)
10753 (while (setq e (pop tbl))
10754 (cond
10755 ((equal e '(:startgroup))
10756 (push '() groups) (setq ingroup t)
10757 (when (not (= cnt 0))
10758 (setq cnt 0)
10759 (insert "\n"))
10760 (insert "{ "))
10761 ((equal e '(:endgroup))
10762 (setq ingroup nil cnt 0)
10763 (insert "}\n"))
10764 ((equal e '(:newline))
10765 (when (not (= cnt 0))
10766 (setq cnt 0)
10767 (insert "\n")
10768 (setq e (car tbl))
10769 (while (equal (car tbl) '(:newline))
10770 (insert "\n")
10771 (setq tbl (cdr tbl)))))
10773 (setq tg (car e) c2 nil)
10774 (if (cdr e)
10775 (setq c (cdr e))
10776 ;; automatically assign a character.
10777 (setq c1 (string-to-char
10778 (downcase (substring
10779 tg (if (= (string-to-char tg) ?@) 1 0)))))
10780 (if (or (rassoc c1 ntable) (rassoc c1 table))
10781 (while (or (rassoc char ntable) (rassoc char table))
10782 (setq char (1+ char)))
10783 (setq c2 c1))
10784 (setq c (or c2 char)))
10785 (if ingroup (push tg (car groups)))
10786 (setq tg (org-add-props tg nil 'face
10787 (cond
10788 ((not (assoc tg table))
10789 (org-get-todo-face tg))
10790 ((member tg current) c-face)
10791 ((member tg inherited) i-face)
10792 (t nil))))
10793 (if (and (= cnt 0) (not ingroup)) (insert " "))
10794 (insert "[" c "] " tg (make-string
10795 (- fwidth 4 (length tg)) ?\ ))
10796 (push (cons tg c) ntable)
10797 (when (= (setq cnt (1+ cnt)) ncol)
10798 (insert "\n")
10799 (if ingroup (insert " "))
10800 (setq cnt 0)))))
10801 (setq ntable (nreverse ntable))
10802 (insert "\n")
10803 (goto-char (point-min))
10804 (if (not expert) (org-fit-window-to-buffer))
10805 (setq rtn
10806 (catch 'exit
10807 (while t
10808 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10809 (if groups " [!] no groups" " [!]groups")
10810 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10811 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10812 (cond
10813 ((= c ?\r) (throw 'exit t))
10814 ((= c ?!)
10815 (setq groups (not groups))
10816 (goto-char (point-min))
10817 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10818 ((= c ?\C-c)
10819 (if (not expert)
10820 (org-fast-tag-show-exit
10821 (setq exit-after-next (not exit-after-next)))
10822 (setq expert nil)
10823 (delete-other-windows)
10824 (split-window-vertically)
10825 (org-switch-to-buffer-other-window " *Org tags*")
10826 (org-fit-window-to-buffer)))
10827 ((or (= c ?\C-g)
10828 (and (= c ?q) (not (rassoc c ntable))))
10829 (org-detach-overlay org-tags-overlay)
10830 (setq quit-flag t))
10831 ((= c ?\ )
10832 (setq current nil)
10833 (if exit-after-next (setq exit-after-next 'now)))
10834 ((= c ?\t)
10835 (condition-case nil
10836 (setq tg (org-ido-completing-read
10837 "Tag: "
10838 (or buffer-tags
10839 (with-current-buffer buf
10840 (org-get-buffer-tags)))))
10841 (quit (setq tg "")))
10842 (when (string-match "\\S-" tg)
10843 (add-to-list 'buffer-tags (list tg))
10844 (if (member tg current)
10845 (setq current (delete tg current))
10846 (push tg current)))
10847 (if exit-after-next (setq exit-after-next 'now)))
10848 ((setq e (rassoc c todo-table) tg (car e))
10849 (with-current-buffer buf
10850 (save-excursion (org-todo tg)))
10851 (if exit-after-next (setq exit-after-next 'now)))
10852 ((setq e (rassoc c ntable) tg (car e))
10853 (if (member tg current)
10854 (setq current (delete tg current))
10855 (loop for g in groups do
10856 (if (member tg g)
10857 (mapc (lambda (x)
10858 (setq current (delete x current)))
10859 g)))
10860 (push tg current))
10861 (if exit-after-next (setq exit-after-next 'now))))
10863 ;; Create a sorted list
10864 (setq current
10865 (sort current
10866 (lambda (a b)
10867 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10868 (if (eq exit-after-next 'now) (throw 'exit t))
10869 (goto-char (point-min))
10870 (beginning-of-line 2)
10871 (delete-region (point) (point-at-eol))
10872 (org-fast-tag-insert "Current" current c-face)
10873 (org-set-current-tags-overlay current ov-prefix)
10874 (while (re-search-forward
10875 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10876 (setq tg (match-string 1))
10877 (add-text-properties
10878 (match-beginning 1) (match-end 1)
10879 (list 'face
10880 (cond
10881 ((member tg current) c-face)
10882 ((member tg inherited) i-face)
10883 (t (get-text-property (match-beginning 1) 'face))))))
10884 (goto-char (point-min)))))
10885 (org-detach-overlay org-tags-overlay)
10886 (if rtn
10887 (mapconcat 'identity current ":")
10888 nil))))
10890 (defun org-get-tags-string ()
10891 "Get the TAGS string in the current headline."
10892 (unless (org-on-heading-p t)
10893 (error "Not on a heading"))
10894 (save-excursion
10895 (beginning-of-line 1)
10896 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10897 (org-match-string-no-properties 1)
10898 "")))
10900 (defun org-get-tags ()
10901 "Get the list of tags specified in the current headline."
10902 (org-split-string (org-get-tags-string) ":"))
10904 (defun org-get-buffer-tags ()
10905 "Get a table of all tags used in the buffer, for completion."
10906 (let (tags)
10907 (save-excursion
10908 (goto-char (point-min))
10909 (while (re-search-forward
10910 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10911 (when (equal (char-after (point-at-bol 0)) ?*)
10912 (mapc (lambda (x) (add-to-list 'tags x))
10913 (org-split-string (org-match-string-no-properties 1) ":")))))
10914 (mapcar 'list tags)))
10916 ;;;; The mapping API
10918 ;;;###autoload
10919 (defun org-map-entries (func &optional match scope &rest skip)
10920 "Call FUNC at each headline selected by MATCH in SCOPE.
10922 FUNC is a function or a lisp form. The function will be called without
10923 arguments, with the cursor positioned at the beginning of the headline.
10924 The return values of all calls to the function will be collected and
10925 returned as a list.
10927 The call to FUNC will be wrapped into a save-excursion form, so FUNC
10928 does not need to preserve point. After evaluaton, the cursor will be
10929 moved to the end of the line (presumably of the headline of the
10930 processed entry) and search continues from there. Under some
10931 circumstances, this may not produce the wanted results. For example,
10932 if you have removed (e.g. archived) the current (sub)tree it could
10933 mean that the next entry will be skipped entirely. In such cases, you
10934 can specify the position from where search should continue by making
10935 FUNC set the variable `org-map-continue-from' to the desired buffer
10936 position.
10938 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10939 Only headlines that are matched by this query will be considered during
10940 the iteration. When MATCH is nil or t, all headlines will be
10941 visited by the iteration.
10943 SCOPE determines the scope of this command. It can be any of:
10945 nil The current buffer, respecting the restriction if any
10946 tree The subtree started with the entry at point
10947 file The current buffer, without restriction
10948 file-with-archives
10949 The current buffer, and any archives associated with it
10950 agenda All agenda files
10951 agenda-with-archives
10952 All agenda files with any archive files associated with them
10953 \(file1 file2 ...)
10954 If this is a list, all files in the list will be scanned
10956 The remaining args are treated as settings for the skipping facilities of
10957 the scanner. The following items can be given here:
10959 archive skip trees with the archive tag.
10960 comment skip trees with the COMMENT keyword
10961 function or Emacs Lisp form:
10962 will be used as value for `org-agenda-skip-function', so whenever
10963 the the function returns t, FUNC will not be called for that
10964 entry and search will continue from the point where the
10965 function leaves it.
10967 If your function needs to retrieve the tags including inherited tags
10968 at the *current* entry, you can use the value of the variable
10969 `org-scanner-tags' which will be much faster than getting the value
10970 with `org-get-tags-at'. If your function gets properties with
10971 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
10972 to t around the call to `org-entry-properties' to get the same speedup.
10973 Note that if your function moves around to retrieve tags and properties at
10974 a *different* entry, you cannot use these techniques."
10975 (let* ((org-agenda-archives-mode nil) ; just to make sure
10976 (org-agenda-skip-archived-trees (memq 'archive skip))
10977 (org-agenda-skip-comment-trees (memq 'comment skip))
10978 (org-agenda-skip-function
10979 (car (org-delete-all '(comment archive) skip)))
10980 (org-tags-match-list-sublevels t)
10981 matcher file res
10982 org-todo-keywords-for-agenda
10983 org-done-keywords-for-agenda
10984 org-todo-keyword-alist-for-agenda
10985 org-tag-alist-for-agenda)
10987 (cond
10988 ((eq match t) (setq matcher t))
10989 ((eq match nil) (setq matcher t))
10990 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10992 (save-excursion
10993 (save-restriction
10994 (when (eq scope 'tree)
10995 (org-back-to-heading t)
10996 (org-narrow-to-subtree)
10997 (setq scope nil))
10999 (if (not scope)
11000 (progn
11001 (org-prepare-agenda-buffers
11002 (list (buffer-file-name (current-buffer))))
11003 (setq res (org-scan-tags func matcher)))
11004 ;; Get the right scope
11005 (cond
11006 ((and scope (listp scope) (symbolp (car scope)))
11007 (setq scope (eval scope)))
11008 ((eq scope 'agenda)
11009 (setq scope (org-agenda-files t)))
11010 ((eq scope 'agenda-with-archives)
11011 (setq scope (org-agenda-files t))
11012 (setq scope (org-add-archive-files scope)))
11013 ((eq scope 'file)
11014 (setq scope (list (buffer-file-name))))
11015 ((eq scope 'file-with-archives)
11016 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11017 (org-prepare-agenda-buffers scope)
11018 (while (setq file (pop scope))
11019 (with-current-buffer (org-find-base-buffer-visiting file)
11020 (save-excursion
11021 (save-restriction
11022 (widen)
11023 (goto-char (point-min))
11024 (setq res (append res (org-scan-tags func matcher))))))))))
11025 res))
11027 ;;;; Properties
11029 ;;; Setting and retrieving properties
11031 (defconst org-special-properties
11032 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11033 "TIMESTAMP" "TIMESTAMP_IA")
11034 "The special properties valid in Org-mode.
11036 These are properties that are not defined in the property drawer,
11037 but in some other way.")
11039 (defconst org-default-properties
11040 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
11041 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11042 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11043 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
11044 "Some properties that are used by Org-mode for various purposes.
11045 Being in this list makes sure that they are offered for completion.")
11047 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11048 "Regular expression matching the first line of a property drawer.")
11050 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11051 "Regular expression matching the first line of a property drawer.")
11053 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11054 "Regular expression matching the first line of a property drawer.")
11056 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11057 "Regular expression matching the first line of a property drawer.")
11059 (defconst org-property-drawer-re
11060 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11061 org-property-end-re "\\)\n?")
11062 "Matches an entire property drawer.")
11064 (defconst org-clock-drawer-re
11065 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11066 org-property-end-re "\\)\n?")
11067 "Matches an entire clock drawer.")
11069 (defun org-property-action ()
11070 "Do an action on properties."
11071 (interactive)
11072 (let (c)
11073 (org-at-property-p)
11074 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11075 (setq c (read-char-exclusive))
11076 (cond
11077 ((equal c ?s)
11078 (call-interactively 'org-set-property))
11079 ((equal c ?d)
11080 (call-interactively 'org-delete-property))
11081 ((equal c ?D)
11082 (call-interactively 'org-delete-property-globally))
11083 ((equal c ?c)
11084 (call-interactively 'org-compute-property-at-point))
11085 (t (error "No such property action %c" c)))))
11087 (defun org-at-property-p ()
11088 "Is the cursor in a property line?"
11089 ;; FIXME: Does not check if we are actually in the drawer.
11090 ;; FIXME: also returns true on any drawers.....
11091 ;; This is used by C-c C-c for property action.
11092 (save-excursion
11093 (beginning-of-line 1)
11094 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11096 (defun org-get-property-block (&optional beg end force)
11097 "Return the (beg . end) range of the body of the property drawer.
11098 BEG and END can be beginning and end of subtree, if not given
11099 they will be found.
11100 If the drawer does not exist and FORCE is non-nil, create the drawer."
11101 (catch 'exit
11102 (save-excursion
11103 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11104 (end (or end (progn (outline-next-heading) (point)))))
11105 (goto-char beg)
11106 (if (re-search-forward org-property-start-re end t)
11107 (setq beg (1+ (match-end 0)))
11108 (if force
11109 (save-excursion
11110 (org-insert-property-drawer)
11111 (setq end (progn (outline-next-heading) (point))))
11112 (throw 'exit nil))
11113 (goto-char beg)
11114 (if (re-search-forward org-property-start-re end t)
11115 (setq beg (1+ (match-end 0)))))
11116 (if (re-search-forward org-property-end-re end t)
11117 (setq end (match-beginning 0))
11118 (or force (throw 'exit nil))
11119 (goto-char beg)
11120 (setq end beg)
11121 (org-indent-line-function)
11122 (insert ":END:\n"))
11123 (cons beg end)))))
11125 (defun org-entry-properties (&optional pom which)
11126 "Get all properties of the entry at point-or-marker POM.
11127 This includes the TODO keyword, the tags, time strings for deadline,
11128 scheduled, and clocking, and any additional properties defined in the
11129 entry. The return value is an alist, keys may occur multiple times
11130 if the property key was used several times.
11131 POM may also be nil, in which case the current entry is used.
11132 If WHICH is nil or `all', get all properties. If WHICH is
11133 `special' or `standard', only get that subclass."
11134 (setq which (or which 'all))
11135 (org-with-point-at pom
11136 (let ((clockstr (substring org-clock-string 0 -1))
11137 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11138 beg end range props sum-props key value string clocksum)
11139 (save-excursion
11140 (when (condition-case nil
11141 (and (org-mode-p) (org-back-to-heading t))
11142 (error nil))
11143 (setq beg (point))
11144 (setq sum-props (get-text-property (point) 'org-summaries))
11145 (setq clocksum (get-text-property (point) :org-clock-minutes))
11146 (outline-next-heading)
11147 (setq end (point))
11148 (when (memq which '(all special))
11149 ;; Get the special properties, like TODO and tags
11150 (goto-char beg)
11151 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11152 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11153 (when (looking-at org-priority-regexp)
11154 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11155 (when (and (setq value (org-get-tags-string))
11156 (string-match "\\S-" value))
11157 (push (cons "TAGS" value) props))
11158 (when (setq value (org-get-tags-at))
11159 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11160 props))
11161 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11162 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11163 string (if (equal key clockstr)
11164 (org-no-properties
11165 (org-trim
11166 (buffer-substring
11167 (match-beginning 3) (goto-char (point-at-eol)))))
11168 (substring (org-match-string-no-properties 3) 1 -1)))
11169 (unless key
11170 (if (= (char-after (match-beginning 3)) ?\[)
11171 (setq key "TIMESTAMP_IA")
11172 (setq key "TIMESTAMP")))
11173 (when (or (equal key clockstr) (not (assoc key props)))
11174 (push (cons key string) props)))
11178 (when (memq which '(all standard))
11179 ;; Get the standard properties, like :PROP: ...
11180 (setq range (org-get-property-block beg end))
11181 (when range
11182 (goto-char (car range))
11183 (while (re-search-forward
11184 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11185 (cdr range) t)
11186 (setq key (org-match-string-no-properties 1)
11187 value (org-trim (or (org-match-string-no-properties 2) "")))
11188 (unless (member key excluded)
11189 (push (cons key (or value "")) props)))))
11190 (if clocksum
11191 (push (cons "CLOCKSUM"
11192 (org-columns-number-to-string (/ (float clocksum) 60.)
11193 'add_times))
11194 props))
11195 (unless (assoc "CATEGORY" props)
11196 (setq value (or (org-get-category)
11197 (progn (org-refresh-category-properties)
11198 (org-get-category))))
11199 (push (cons "CATEGORY" value) props))
11200 (append sum-props (nreverse props)))))))
11202 (defun org-entry-get (pom property &optional inherit)
11203 "Get value of PROPERTY for entry at point-or-marker POM.
11204 If INHERIT is non-nil and the entry does not have the property,
11205 then also check higher levels of the hierarchy.
11206 If INHERIT is the symbol `selective', use inheritance only if the setting
11207 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11208 If the property is present but empty, the return value is the empty string.
11209 If the property is not present at all, nil is returned."
11210 (org-with-point-at pom
11211 (if (and inherit (if (eq inherit 'selective)
11212 (org-property-inherit-p property)
11214 (org-entry-get-with-inheritance property)
11215 (if (member property org-special-properties)
11216 ;; We need a special property. Use brute force, get all properties.
11217 (cdr (assoc property (org-entry-properties nil 'special)))
11218 (let ((range (org-get-property-block)))
11219 (if (and range
11220 (goto-char (car range))
11221 (re-search-forward
11222 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11223 (cdr range) t))
11224 ;; Found the property, return it.
11225 (if (match-end 1)
11226 (org-match-string-no-properties 1)
11227 "")))))))
11229 (defun org-property-or-variable-value (var &optional inherit)
11230 "Check if there is a property fixing the value of VAR.
11231 If yes, return this value. If not, return the current value of the variable."
11232 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11233 (if (and prop (stringp prop) (string-match "\\S-" prop))
11234 (read prop)
11235 (symbol-value var))))
11237 (defun org-entry-delete (pom property)
11238 "Delete the property PROPERTY from entry at point-or-marker POM."
11239 (org-with-point-at pom
11240 (if (member property org-special-properties)
11241 nil ; cannot delete these properties.
11242 (let ((range (org-get-property-block)))
11243 (if (and range
11244 (goto-char (car range))
11245 (re-search-forward
11246 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11247 (cdr range) t))
11248 (progn
11249 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11251 nil)))))
11253 ;; Multi-values properties are properties that contain multiple values
11254 ;; These values are assumed to be single words, separated by whitespace.
11255 (defun org-entry-add-to-multivalued-property (pom property value)
11256 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11257 (let* ((old (org-entry-get pom property))
11258 (values (and old (org-split-string old "[ \t]"))))
11259 (setq value (org-entry-protect-space value))
11260 (unless (member value values)
11261 (setq values (cons value values))
11262 (org-entry-put pom property
11263 (mapconcat 'identity values " ")))))
11265 (defun org-entry-remove-from-multivalued-property (pom property value)
11266 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11267 (let* ((old (org-entry-get pom property))
11268 (values (and old (org-split-string old "[ \t]"))))
11269 (setq value (org-entry-protect-space value))
11270 (when (member value values)
11271 (setq values (delete value values))
11272 (org-entry-put pom property
11273 (mapconcat 'identity values " ")))))
11275 (defun org-entry-member-in-multivalued-property (pom property value)
11276 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11277 (let* ((old (org-entry-get pom property))
11278 (values (and old (org-split-string old "[ \t]"))))
11279 (setq value (org-entry-protect-space value))
11280 (member value values)))
11282 (defun org-entry-get-multivalued-property (pom property)
11283 "Return a list of values in a multivalued property."
11284 (let* ((value (org-entry-get pom property))
11285 (values (and value (org-split-string value "[ \t]"))))
11286 (mapcar 'org-entry-restore-space values)))
11288 (defun org-entry-put-multivalued-property (pom property &rest values)
11289 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11290 VALUES should be a list of strings. Spaces will be protected."
11291 (org-entry-put pom property
11292 (mapconcat 'org-entry-protect-space values " "))
11293 (let* ((value (org-entry-get pom property))
11294 (values (and value (org-split-string value "[ \t]"))))
11295 (mapcar 'org-entry-restore-space values)))
11297 (defun org-entry-protect-space (s)
11298 "Protect spaces and newline in string S."
11299 (while (string-match " " s)
11300 (setq s (replace-match "%20" t t s)))
11301 (while (string-match "\n" s)
11302 (setq s (replace-match "%0A" t t s)))
11305 (defun org-entry-restore-space (s)
11306 "Restore spaces and newline in string S."
11307 (while (string-match "%20" s)
11308 (setq s (replace-match " " t t s)))
11309 (while (string-match "%0A" s)
11310 (setq s (replace-match "\n" t t s)))
11313 (defvar org-entry-property-inherited-from (make-marker)
11314 "Marker pointing to the entry from where a property was inherited.
11315 Each call to `org-entry-get-with-inheritance' will set this marker to the
11316 location of the entry where the inheritance search matched. If there was
11317 no match, the marker will point nowhere.
11318 Note that also `org-entry-get' calls this function, if the INHERIT flag
11319 is set.")
11321 (defun org-entry-get-with-inheritance (property)
11322 "Get entry property, and search higher levels if not present."
11323 (move-marker org-entry-property-inherited-from nil)
11324 (let (tmp)
11325 (save-excursion
11326 (save-restriction
11327 (widen)
11328 (catch 'ex
11329 (while t
11330 (when (setq tmp (org-entry-get nil property))
11331 (org-back-to-heading t)
11332 (move-marker org-entry-property-inherited-from (point))
11333 (throw 'ex tmp))
11334 (or (org-up-heading-safe) (throw 'ex nil)))))
11335 (or tmp
11336 (cdr (assoc property org-file-properties))
11337 (cdr (assoc property org-global-properties))
11338 (cdr (assoc property org-global-properties-fixed))))))
11340 (defun org-entry-put (pom property value)
11341 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11342 (org-with-point-at pom
11343 (org-back-to-heading t)
11344 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11345 range)
11346 (cond
11347 ((equal property "TODO")
11348 (when (and (stringp value) (string-match "\\S-" value)
11349 (not (member value org-todo-keywords-1)))
11350 (error "\"%s\" is not a valid TODO state" value))
11351 (if (or (not value)
11352 (not (string-match "\\S-" value)))
11353 (setq value 'none))
11354 (org-todo value)
11355 (org-set-tags nil 'align))
11356 ((equal property "PRIORITY")
11357 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11358 (string-to-char value) ?\ ))
11359 (org-set-tags nil 'align))
11360 ((equal property "SCHEDULED")
11361 (if (re-search-forward org-scheduled-time-regexp end t)
11362 (cond
11363 ((eq value 'earlier) (org-timestamp-change -1 'day))
11364 ((eq value 'later) (org-timestamp-change 1 'day))
11365 (t (call-interactively 'org-schedule)))
11366 (call-interactively 'org-schedule)))
11367 ((equal property "DEADLINE")
11368 (if (re-search-forward org-deadline-time-regexp end t)
11369 (cond
11370 ((eq value 'earlier) (org-timestamp-change -1 'day))
11371 ((eq value 'later) (org-timestamp-change 1 'day))
11372 (t (call-interactively 'org-deadline)))
11373 (call-interactively 'org-deadline)))
11374 ((member property org-special-properties)
11375 (error "The %s property can not yet be set with `org-entry-put'"
11376 property))
11377 (t ; a non-special property
11378 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11379 (setq range (org-get-property-block beg end 'force))
11380 (goto-char (car range))
11381 (if (re-search-forward
11382 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11383 (progn
11384 (delete-region (match-beginning 1) (match-end 1))
11385 (goto-char (match-beginning 1)))
11386 (goto-char (cdr range))
11387 (insert "\n")
11388 (backward-char 1)
11389 (org-indent-line-function)
11390 (insert ":" property ":"))
11391 (and value (insert " " value))
11392 (org-indent-line-function)))))))
11394 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11395 "Get all property keys in the current buffer.
11396 With INCLUDE-SPECIALS, also list the special properties that reflect things
11397 like tags and TODO state.
11398 With INCLUDE-DEFAULTS, also include properties that has special meaning
11399 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11400 With INCLUDE-COLUMNS, also include property names given in COLUMN
11401 formats in the current buffer."
11402 (let (rtn range cfmt s p)
11403 (save-excursion
11404 (save-restriction
11405 (widen)
11406 (goto-char (point-min))
11407 (while (re-search-forward org-property-start-re nil t)
11408 (setq range (org-get-property-block))
11409 (goto-char (car range))
11410 (while (re-search-forward
11411 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11412 (cdr range) t)
11413 (add-to-list 'rtn (org-match-string-no-properties 1)))
11414 (outline-next-heading))))
11416 (when include-specials
11417 (setq rtn (append org-special-properties rtn)))
11419 (when include-defaults
11420 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11422 (when include-columns
11423 (save-excursion
11424 (save-restriction
11425 (widen)
11426 (goto-char (point-min))
11427 (while (re-search-forward
11428 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11429 nil t)
11430 (setq cfmt (match-string 2) s 0)
11431 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11432 cfmt s)
11433 (setq s (match-end 0)
11434 p (match-string 1 cfmt))
11435 (unless (or (equal p "ITEM")
11436 (member p org-special-properties))
11437 (add-to-list 'rtn (match-string 1 cfmt))))))))
11439 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11441 (defun org-property-values (key)
11442 "Return a list of all values of property KEY."
11443 (save-excursion
11444 (save-restriction
11445 (widen)
11446 (goto-char (point-min))
11447 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11448 values)
11449 (while (re-search-forward re nil t)
11450 (add-to-list 'values (org-trim (match-string 1))))
11451 (delete "" values)))))
11453 (defun org-insert-property-drawer ()
11454 "Insert a property drawer into the current entry."
11455 (interactive)
11456 (org-back-to-heading t)
11457 (looking-at outline-regexp)
11458 (let ((indent (- (match-end 0)(match-beginning 0)))
11459 (beg (point))
11460 (re (concat "^[ \t]*" org-keyword-time-regexp))
11461 end hiddenp)
11462 (outline-next-heading)
11463 (setq end (point))
11464 (goto-char beg)
11465 (while (re-search-forward re end t))
11466 (setq hiddenp (org-invisible-p))
11467 (end-of-line 1)
11468 (and (equal (char-after) ?\n) (forward-char 1))
11469 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11470 (if (member (match-string 1) '("CLOCK:" ":END:"))
11471 ;; just skip this line
11472 (beginning-of-line 2)
11473 ;; Drawer start, find the end
11474 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11475 (beginning-of-line 1)))
11476 (org-skip-over-state-notes)
11477 (skip-chars-backward " \t\n\r")
11478 (if (eq (char-before) ?*) (forward-char 1))
11479 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11480 (beginning-of-line 0)
11481 (org-indent-to-column indent)
11482 (beginning-of-line 2)
11483 (org-indent-to-column indent)
11484 (beginning-of-line 0)
11485 (if hiddenp
11486 (save-excursion
11487 (org-back-to-heading t)
11488 (hide-entry))
11489 (org-flag-drawer t))))
11491 (defun org-set-property (property value)
11492 "In the current entry, set PROPERTY to VALUE.
11493 When called interactively, this will prompt for a property name, offering
11494 completion on existing and default properties. And then it will prompt
11495 for a value, offering completion either on allowed values (via an inherited
11496 xxx_ALL property) or on existing values in other instances of this property
11497 in the current file."
11498 (interactive
11499 (let* ((completion-ignore-case t)
11500 (keys (org-buffer-property-keys nil t t))
11501 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11502 (prop (if (member prop0 keys)
11503 prop0
11504 (or (cdr (assoc (downcase prop0)
11505 (mapcar (lambda (x) (cons (downcase x) x))
11506 keys)))
11507 prop0)))
11508 (cur (org-entry-get nil prop))
11509 (allowed (org-property-get-allowed-values nil prop 'table))
11510 (existing (mapcar 'list (org-property-values prop)))
11511 (val (if allowed
11512 (org-completing-read "Value: " allowed nil 'req-match)
11513 (let (org-completion-use-ido)
11514 (org-completing-read
11515 (concat "Value" (if (and cur (string-match "\\S-" cur))
11516 (concat "[" cur "]") "")
11517 ": ")
11518 existing nil nil "" nil cur)))))
11519 (list prop (if (equal val "") cur val))))
11520 (unless (equal (org-entry-get nil property) value)
11521 (org-entry-put nil property value)))
11523 (defun org-delete-property (property)
11524 "In the current entry, delete PROPERTY."
11525 (interactive
11526 (let* ((completion-ignore-case t)
11527 (prop (org-ido-completing-read
11528 "Property: " (org-entry-properties nil 'standard))))
11529 (list prop)))
11530 (message "Property %s %s" property
11531 (if (org-entry-delete nil property)
11532 "deleted"
11533 "was not present in the entry")))
11535 (defun org-delete-property-globally (property)
11536 "Remove PROPERTY globally, from all entries."
11537 (interactive
11538 (let* ((completion-ignore-case t)
11539 (prop (org-ido-completing-read
11540 "Globally remove property: "
11541 (mapcar 'list (org-buffer-property-keys)))))
11542 (list prop)))
11543 (save-excursion
11544 (save-restriction
11545 (widen)
11546 (goto-char (point-min))
11547 (let ((cnt 0))
11548 (while (re-search-forward
11549 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11550 nil t)
11551 (setq cnt (1+ cnt))
11552 (replace-match ""))
11553 (message "Property \"%s\" removed from %d entries" property cnt)))))
11555 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11557 (defun org-compute-property-at-point ()
11558 "Compute the property at point.
11559 This looks for an enclosing column format, extracts the operator and
11560 then applies it to the property in the column format's scope."
11561 (interactive)
11562 (unless (org-at-property-p)
11563 (error "Not at a property"))
11564 (let ((prop (org-match-string-no-properties 2)))
11565 (org-columns-get-format-and-top-level)
11566 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11567 (error "No operator defined for property %s" prop))
11568 (org-columns-compute prop)))
11570 (defun org-property-get-allowed-values (pom property &optional table)
11571 "Get allowed values for the property PROPERTY.
11572 When TABLE is non-nil, return an alist that can directly be used for
11573 completion."
11574 (let (vals)
11575 (cond
11576 ((equal property "TODO")
11577 (setq vals (org-with-point-at pom
11578 (append org-todo-keywords-1 '("")))))
11579 ((equal property "PRIORITY")
11580 (let ((n org-lowest-priority))
11581 (while (>= n org-highest-priority)
11582 (push (char-to-string n) vals)
11583 (setq n (1- n)))))
11584 ((member property org-special-properties))
11586 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11588 (when (and vals (string-match "\\S-" vals))
11589 (setq vals (car (read-from-string (concat "(" vals ")"))))
11590 (setq vals (mapcar (lambda (x)
11591 (cond ((stringp x) x)
11592 ((numberp x) (number-to-string x))
11593 ((symbolp x) (symbol-name x))
11594 (t "???")))
11595 vals)))))
11596 (if table (mapcar 'list vals) vals)))
11598 (defun org-property-previous-allowed-value (&optional previous)
11599 "Switch to the next allowed value for this property."
11600 (interactive)
11601 (org-property-next-allowed-value t))
11603 (defun org-property-next-allowed-value (&optional previous)
11604 "Switch to the next allowed value for this property."
11605 (interactive)
11606 (unless (org-at-property-p)
11607 (error "Not at a property"))
11608 (let* ((key (match-string 2))
11609 (value (match-string 3))
11610 (allowed (or (org-property-get-allowed-values (point) key)
11611 (and (member value '("[ ]" "[-]" "[X]"))
11612 '("[ ]" "[X]"))))
11613 nval)
11614 (unless allowed
11615 (error "Allowed values for this property have not been defined"))
11616 (if previous (setq allowed (reverse allowed)))
11617 (if (member value allowed)
11618 (setq nval (car (cdr (member value allowed)))))
11619 (setq nval (or nval (car allowed)))
11620 (if (equal nval value)
11621 (error "Only one allowed value for this property"))
11622 (org-at-property-p)
11623 (replace-match (concat " :" key ": " nval) t t)
11624 (org-indent-line-function)
11625 (beginning-of-line 1)
11626 (skip-chars-forward " \t")))
11628 (defun org-find-entry-with-id (ident)
11629 "Locate the entry that contains the ID property with exact value IDENT.
11630 IDENT can be a string, a symbol or a number, this function will search for
11631 the string representation of it.
11632 Return the position where this entry starts, or nil if there is no such entry."
11633 (interactive "sID: ")
11634 (let ((id (cond
11635 ((stringp ident) ident)
11636 ((symbol-name ident) (symbol-name ident))
11637 ((numberp ident) (number-to-string ident))
11638 (t (error "IDENT %s must be a string, symbol or number" ident))))
11639 (case-fold-search nil))
11640 (save-excursion
11641 (save-restriction
11642 (widen)
11643 (goto-char (point-min))
11644 (when (re-search-forward
11645 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11646 nil t)
11647 (org-back-to-heading)
11648 (point))))))
11650 ;;;; Timestamps
11652 (defvar org-last-changed-timestamp nil)
11653 (defvar org-last-inserted-timestamp nil
11654 "The last time stamp inserted with `org-insert-time-stamp'.")
11655 (defvar org-time-was-given) ; dynamically scoped parameter
11656 (defvar org-end-time-was-given) ; dynamically scoped parameter
11657 (defvar org-ts-what) ; dynamically scoped parameter
11659 (defun org-time-stamp (arg &optional inactive)
11660 "Prompt for a date/time and insert a time stamp.
11661 If the user specifies a time like HH:MM, or if this command is called
11662 with a prefix argument, the time stamp will contain date and time.
11663 Otherwise, only the date will be included. All parts of a date not
11664 specified by the user will be filled in from the current date/time.
11665 So if you press just return without typing anything, the time stamp
11666 will represent the current date/time. If there is already a timestamp
11667 at the cursor, it will be modified."
11668 (interactive "P")
11669 (let* ((ts nil)
11670 (default-time
11671 ;; Default time is either today, or, when entering a range,
11672 ;; the range start.
11673 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11674 (save-excursion
11675 (re-search-backward
11676 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11677 (- (point) 20) t)))
11678 (apply 'encode-time (org-parse-time-string (match-string 1)))
11679 (current-time)))
11680 (default-input (and ts (org-get-compact-tod ts)))
11681 org-time-was-given org-end-time-was-given time)
11682 (cond
11683 ((and (org-at-timestamp-p t)
11684 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11685 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11686 (insert "--")
11687 (setq time (let ((this-command this-command))
11688 (org-read-date arg 'totime nil nil
11689 default-time default-input)))
11690 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11691 ((org-at-timestamp-p t)
11692 (setq time (let ((this-command this-command))
11693 (org-read-date arg 'totime nil nil default-time default-input)))
11694 (when (org-at-timestamp-p t) ; just to get the match data
11695 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11696 (replace-match "")
11697 (setq org-last-changed-timestamp
11698 (org-insert-time-stamp
11699 time (or org-time-was-given arg)
11700 inactive nil nil (list org-end-time-was-given))))
11701 (message "Timestamp updated"))
11703 (setq time (let ((this-command this-command))
11704 (org-read-date arg 'totime nil nil default-time default-input)))
11705 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11706 nil nil (list org-end-time-was-given))))))
11708 ;; FIXME: can we use this for something else, like computing time differences?
11709 (defun org-get-compact-tod (s)
11710 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11711 (let* ((t1 (match-string 1 s))
11712 (h1 (string-to-number (match-string 2 s)))
11713 (m1 (string-to-number (match-string 3 s)))
11714 (t2 (and (match-end 4) (match-string 5 s)))
11715 (h2 (and t2 (string-to-number (match-string 6 s))))
11716 (m2 (and t2 (string-to-number (match-string 7 s))))
11717 dh dm)
11718 (if (not t2)
11720 (setq dh (- h2 h1) dm (- m2 m1))
11721 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11722 (concat t1 "+" (number-to-string dh)
11723 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11725 (defun org-time-stamp-inactive (&optional arg)
11726 "Insert an inactive time stamp.
11727 An inactive time stamp is enclosed in square brackets instead of angle
11728 brackets. It is inactive in the sense that it does not trigger agenda entries,
11729 does not link to the calendar and cannot be changed with the S-cursor keys.
11730 So these are more for recording a certain time/date."
11731 (interactive "P")
11732 (org-time-stamp arg 'inactive))
11734 (defvar org-date-ovl (org-make-overlay 1 1))
11735 (org-overlay-put org-date-ovl 'face 'org-warning)
11736 (org-detach-overlay org-date-ovl)
11738 (defvar org-ans1) ; dynamically scoped parameter
11739 (defvar org-ans2) ; dynamically scoped parameter
11741 (defvar org-plain-time-of-day-regexp) ; defined below
11743 (defvar org-overriding-default-time nil) ; dynamically scoped
11744 (defvar org-read-date-overlay nil)
11745 (defvar org-dcst nil) ; dynamically scoped
11746 (defvar org-read-date-history nil)
11748 (defun org-read-date (&optional with-time to-time from-string prompt
11749 default-time default-input)
11750 "Read a date, possibly a time, and make things smooth for the user.
11751 The prompt will suggest to enter an ISO date, but you can also enter anything
11752 which will at least partially be understood by `parse-time-string'.
11753 Unrecognized parts of the date will default to the current day, month, year,
11754 hour and minute. If this command is called to replace a timestamp at point,
11755 of to enter the second timestamp of a range, the default time is taken from the
11756 existing stamp. For example,
11757 3-2-5 --> 2003-02-05
11758 feb 15 --> currentyear-02-15
11759 sep 12 9 --> 2009-09-12
11760 12:45 --> today 12:45
11761 22 sept 0:34 --> currentyear-09-22 0:34
11762 12 --> currentyear-currentmonth-12
11763 Fri --> nearest Friday (today or later)
11764 etc.
11766 Furthermore you can specify a relative date by giving, as the *first* thing
11767 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11768 change in days weeks, months, years.
11769 With a single plus or minus, the date is relative to today. With a double
11770 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11771 +4d --> four days from today
11772 +4 --> same as above
11773 +2w --> two weeks from today
11774 ++5 --> five days from default date
11776 The function understands only English month and weekday abbreviations,
11777 but this can be configured with the variables `parse-time-months' and
11778 `parse-time-weekdays'.
11780 While prompting, a calendar is popped up - you can also select the
11781 date with the mouse (button 1). The calendar shows a period of three
11782 months. To scroll it to other months, use the keys `>' and `<'.
11783 If you don't like the calendar, turn it off with
11784 \(setq org-read-date-popup-calendar nil)
11786 With optional argument TO-TIME, the date will immediately be converted
11787 to an internal time.
11788 With an optional argument WITH-TIME, the prompt will suggest to also
11789 insert a time. Note that when WITH-TIME is not set, you can still
11790 enter a time, and this function will inform the calling routine about
11791 this change. The calling routine may then choose to change the format
11792 used to insert the time stamp into the buffer to include the time.
11793 With optional argument FROM-STRING, read from this string instead from
11794 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11795 the time/date that is used for everything that is not specified by the
11796 user."
11797 (require 'parse-time)
11798 (let* ((org-time-stamp-rounding-minutes
11799 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11800 (org-dcst org-display-custom-times)
11801 (ct (org-current-time))
11802 (def (or org-overriding-default-time default-time ct))
11803 (defdecode (decode-time def))
11804 (dummy (progn
11805 (when (< (nth 2 defdecode) org-extend-today-until)
11806 (setcar (nthcdr 2 defdecode) -1)
11807 (setcar (nthcdr 1 defdecode) 59)
11808 (setq def (apply 'encode-time defdecode)
11809 defdecode (decode-time def)))))
11810 (calendar-move-hook nil)
11811 (calendar-view-diary-initially-flag nil)
11812 (view-diary-entries-initially nil)
11813 (calendar-view-holidays-initially-flag nil)
11814 (view-calendar-holidays-initially nil)
11815 (timestr (format-time-string
11816 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11817 (prompt (concat (if prompt (concat prompt " ") "")
11818 (format "Date+time [%s]: " timestr)))
11819 ans (org-ans0 "") org-ans1 org-ans2 final)
11821 (cond
11822 (from-string (setq ans from-string))
11823 (org-read-date-popup-calendar
11824 (save-excursion
11825 (save-window-excursion
11826 (calendar)
11827 (calendar-forward-day (- (time-to-days def)
11828 (calendar-absolute-from-gregorian
11829 (calendar-current-date))))
11830 (org-eval-in-calendar nil t)
11831 (let* ((old-map (current-local-map))
11832 (map (copy-keymap calendar-mode-map))
11833 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11834 (org-defkey map (kbd "RET") 'org-calendar-select)
11835 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11836 'org-calendar-select-mouse)
11837 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11838 'org-calendar-select-mouse)
11839 (org-defkey minibuffer-local-map [(meta shift left)]
11840 (lambda () (interactive)
11841 (org-eval-in-calendar '(calendar-backward-month 1))))
11842 (org-defkey minibuffer-local-map [(meta shift right)]
11843 (lambda () (interactive)
11844 (org-eval-in-calendar '(calendar-forward-month 1))))
11845 (org-defkey minibuffer-local-map [(meta shift up)]
11846 (lambda () (interactive)
11847 (org-eval-in-calendar '(calendar-backward-year 1))))
11848 (org-defkey minibuffer-local-map [(meta shift down)]
11849 (lambda () (interactive)
11850 (org-eval-in-calendar '(calendar-forward-year 1))))
11851 (org-defkey minibuffer-local-map [(shift up)]
11852 (lambda () (interactive)
11853 (org-eval-in-calendar '(calendar-backward-week 1))))
11854 (org-defkey minibuffer-local-map [(shift down)]
11855 (lambda () (interactive)
11856 (org-eval-in-calendar '(calendar-forward-week 1))))
11857 (org-defkey minibuffer-local-map [(shift left)]
11858 (lambda () (interactive)
11859 (org-eval-in-calendar '(calendar-backward-day 1))))
11860 (org-defkey minibuffer-local-map [(shift right)]
11861 (lambda () (interactive)
11862 (org-eval-in-calendar '(calendar-forward-day 1))))
11863 (org-defkey minibuffer-local-map ">"
11864 (lambda () (interactive)
11865 (org-eval-in-calendar '(scroll-calendar-left 1))))
11866 (org-defkey minibuffer-local-map "<"
11867 (lambda () (interactive)
11868 (org-eval-in-calendar '(scroll-calendar-right 1))))
11869 (run-hooks 'org-read-date-minibuffer-setup-hook)
11870 (unwind-protect
11871 (progn
11872 (use-local-map map)
11873 (add-hook 'post-command-hook 'org-read-date-display)
11874 (setq org-ans0 (read-string prompt default-input
11875 'org-read-date-history nil))
11876 ;; org-ans0: from prompt
11877 ;; org-ans1: from mouse click
11878 ;; org-ans2: from calendar motion
11879 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11880 (remove-hook 'post-command-hook 'org-read-date-display)
11881 (use-local-map old-map)
11882 (when org-read-date-overlay
11883 (org-delete-overlay org-read-date-overlay)
11884 (setq org-read-date-overlay nil)))))))
11886 (t ; Naked prompt only
11887 (unwind-protect
11888 (setq ans (read-string prompt default-input
11889 'org-read-date-history timestr))
11890 (when org-read-date-overlay
11891 (org-delete-overlay org-read-date-overlay)
11892 (setq org-read-date-overlay nil)))))
11894 (setq final (org-read-date-analyze ans def defdecode))
11896 (if to-time
11897 (apply 'encode-time final)
11898 (if (and (boundp 'org-time-was-given) org-time-was-given)
11899 (format "%04d-%02d-%02d %02d:%02d"
11900 (nth 5 final) (nth 4 final) (nth 3 final)
11901 (nth 2 final) (nth 1 final))
11902 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11903 (defvar def)
11904 (defvar defdecode)
11905 (defvar with-time)
11906 (defun org-read-date-display ()
11907 "Display the current date prompt interpretation in the minibuffer."
11908 (when org-read-date-display-live
11909 (when org-read-date-overlay
11910 (org-delete-overlay org-read-date-overlay))
11911 (let ((p (point)))
11912 (end-of-line 1)
11913 (while (not (equal (buffer-substring
11914 (max (point-min) (- (point) 4)) (point))
11915 " "))
11916 (insert " "))
11917 (goto-char p))
11918 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11919 " " (or org-ans1 org-ans2)))
11920 (org-end-time-was-given nil)
11921 (f (org-read-date-analyze ans def defdecode))
11922 (fmts (if org-dcst
11923 org-time-stamp-custom-formats
11924 org-time-stamp-formats))
11925 (fmt (if (or with-time
11926 (and (boundp 'org-time-was-given) org-time-was-given))
11927 (cdr fmts)
11928 (car fmts)))
11929 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11930 (when (and org-end-time-was-given
11931 (string-match org-plain-time-of-day-regexp txt))
11932 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11933 org-end-time-was-given
11934 (substring txt (match-end 0)))))
11935 (setq org-read-date-overlay
11936 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11937 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11939 (defun org-read-date-analyze (ans def defdecode)
11940 "Analyse the combined answer of the date prompt."
11941 ;; FIXME: cleanup and comment
11942 (let (delta deltan deltaw deltadef year month day
11943 hour minute second wday pm h2 m2 tl wday1
11944 iso-year iso-weekday iso-week iso-year iso-date)
11946 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11947 (setq ans "+0"))
11949 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11950 (setq ans (replace-match "" t t ans)
11951 deltan (car delta)
11952 deltaw (nth 1 delta)
11953 deltadef (nth 2 delta)))
11955 ;; Check if there is an iso week date in there
11956 ;; If yes, sore the info and postpone interpreting it until the rest
11957 ;; of the parsing is done
11958 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11959 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11960 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11961 iso-week (string-to-number (match-string 2 ans)))
11962 (setq ans (replace-match "" t t ans)))
11964 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11965 (when (string-match
11966 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11967 (setq year (if (match-end 2)
11968 (string-to-number (match-string 2 ans))
11969 (string-to-number (format-time-string "%Y")))
11970 month (string-to-number (match-string 3 ans))
11971 day (string-to-number (match-string 4 ans)))
11972 (if (< year 100) (setq year (+ 2000 year)))
11973 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11974 t nil ans)))
11975 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11976 ;; If there is a time with am/pm, and *no* time without it, we convert
11977 ;; so that matching will be successful.
11978 (loop for i from 1 to 2 do ; twice, for end time as well
11979 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11980 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11981 (setq hour (string-to-number (match-string 1 ans))
11982 minute (if (match-end 3)
11983 (string-to-number (match-string 3 ans))
11985 pm (equal ?p
11986 (string-to-char (downcase (match-string 4 ans)))))
11987 (if (and (= hour 12) (not pm))
11988 (setq hour 0)
11989 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11990 (setq ans (replace-match (format "%02d:%02d" hour minute)
11991 t t ans))))
11993 ;; Check if a time range is given as a duration
11994 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11995 (setq hour (string-to-number (match-string 1 ans))
11996 h2 (+ hour (string-to-number (match-string 3 ans)))
11997 minute (string-to-number (match-string 2 ans))
11998 m2 (+ minute (if (match-end 5) (string-to-number
11999 (match-string 5 ans))0)))
12000 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12001 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12002 t t ans)))
12004 ;; Check if there is a time range
12005 (when (boundp 'org-end-time-was-given)
12006 (setq org-time-was-given nil)
12007 (when (and (string-match org-plain-time-of-day-regexp ans)
12008 (match-end 8))
12009 (setq org-end-time-was-given (match-string 8 ans))
12010 (setq ans (concat (substring ans 0 (match-beginning 7))
12011 (substring ans (match-end 7))))))
12013 (setq tl (parse-time-string ans)
12014 day (or (nth 3 tl) (nth 3 defdecode))
12015 month (or (nth 4 tl)
12016 (if (and org-read-date-prefer-future
12017 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12018 (1+ (nth 4 defdecode))
12019 (nth 4 defdecode)))
12020 year (or (nth 5 tl)
12021 (if (and org-read-date-prefer-future
12022 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12023 (1+ (nth 5 defdecode))
12024 (nth 5 defdecode)))
12025 hour (or (nth 2 tl) (nth 2 defdecode))
12026 minute (or (nth 1 tl) (nth 1 defdecode))
12027 second (or (nth 0 tl) 0)
12028 wday (nth 6 tl))
12030 ;; Special date definitions below
12031 (cond
12032 (iso-week
12033 ;; There was an iso week
12034 (setq year (or iso-year year)
12035 day (or iso-weekday wday 1)
12036 wday nil ; to make sure that the trigger below does not match
12037 iso-date (calendar-gregorian-from-absolute
12038 (calendar-absolute-from-iso
12039 (list iso-week day year))))
12040 ; FIXME: Should we also push ISO weeks into the future?
12041 ; (when (and org-read-date-prefer-future
12042 ; (not iso-year)
12043 ; (< (calendar-absolute-from-gregorian iso-date)
12044 ; (time-to-days (current-time))))
12045 ; (setq year (1+ year)
12046 ; iso-date (calendar-gregorian-from-absolute
12047 ; (calendar-absolute-from-iso
12048 ; (list iso-week day year)))))
12049 (setq month (car iso-date)
12050 year (nth 2 iso-date)
12051 day (nth 1 iso-date)))
12052 (deltan
12053 (unless deltadef
12054 (let ((now (decode-time (current-time))))
12055 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12056 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12057 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12058 ((equal deltaw "m") (setq month (+ month deltan)))
12059 ((equal deltaw "y") (setq year (+ year deltan)))))
12060 ((and wday (not (nth 3 tl)))
12061 ;; Weekday was given, but no day, so pick that day in the week
12062 ;; on or after the derived date.
12063 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12064 (unless (equal wday wday1)
12065 (setq day (+ day (% (- wday wday1 -7) 7))))))
12066 (if (and (boundp 'org-time-was-given)
12067 (nth 2 tl))
12068 (setq org-time-was-given t))
12069 (if (< year 100) (setq year (+ 2000 year)))
12070 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12071 (list second minute hour day month year)))
12073 (defvar parse-time-weekdays)
12075 (defun org-read-date-get-relative (s today default)
12076 "Check string S for special relative date string.
12077 TODAY and DEFAULT are internal times, for today and for a default.
12078 Return shift list (N what def-flag)
12079 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12080 N is the number of WHATs to shift.
12081 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12082 the DEFAULT date rather than TODAY."
12083 (when (and
12084 (string-match
12085 (concat
12086 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12087 "\\([0-9]+\\)?"
12088 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12089 "\\([ \t]\\|$\\)") s)
12090 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12091 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12092 (string-to-char (substring (match-string 1 s) -1))
12093 ?+))
12094 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12095 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12096 (what (if (match-end 3) (match-string 3 s) "d"))
12097 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12098 (date (if rel default today))
12099 (wday (nth 6 (decode-time date)))
12100 delta)
12101 (if wday1
12102 (progn
12103 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12104 (if (= dir ?-) (setq delta (- delta 7)))
12105 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12106 (list delta "d" rel))
12107 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12109 (defun org-eval-in-calendar (form &optional keepdate)
12110 "Eval FORM in the calendar window and return to current window.
12111 Also, store the cursor date in variable org-ans2."
12112 (let ((sw (selected-window)))
12113 (select-window (get-buffer-window "*Calendar*"))
12114 (eval form)
12115 (when (and (not keepdate) (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-ans2 (format-time-string "%Y-%m-%d" time))))
12119 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12120 (select-window sw)))
12122 (defun org-calendar-select ()
12123 "Return to `org-read-date' with the date currently selected.
12124 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12125 (interactive)
12126 (when (calendar-cursor-to-date)
12127 (let* ((date (calendar-cursor-to-date))
12128 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12129 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12130 (if (active-minibuffer-window) (exit-minibuffer))))
12132 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12133 "Insert a date stamp for the date given by the internal TIME.
12134 WITH-HM means, use the stamp format that includes the time of the day.
12135 INACTIVE means use square brackets instead of angular ones, so that the
12136 stamp will not contribute to the agenda.
12137 PRE and POST are optional strings to be inserted before and after the
12138 stamp.
12139 The command returns the inserted time stamp."
12140 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12141 stamp)
12142 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12143 (insert-before-markers (or pre ""))
12144 (insert-before-markers (setq stamp (format-time-string fmt time)))
12145 (when (listp extra)
12146 (setq extra (car extra))
12147 (if (and (stringp extra)
12148 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12149 (setq extra (format "-%02d:%02d"
12150 (string-to-number (match-string 1 extra))
12151 (string-to-number (match-string 2 extra))))
12152 (setq extra nil)))
12153 (when extra
12154 (backward-char 1)
12155 (insert-before-markers extra)
12156 (forward-char 1))
12157 (insert-before-markers (or post ""))
12158 (setq org-last-inserted-timestamp stamp)))
12160 (defun org-toggle-time-stamp-overlays ()
12161 "Toggle the use of custom time stamp formats."
12162 (interactive)
12163 (setq org-display-custom-times (not org-display-custom-times))
12164 (unless org-display-custom-times
12165 (let ((p (point-min)) (bmp (buffer-modified-p)))
12166 (while (setq p (next-single-property-change p 'display))
12167 (if (and (get-text-property p 'display)
12168 (eq (get-text-property p 'face) 'org-date))
12169 (remove-text-properties
12170 p (setq p (next-single-property-change p 'display))
12171 '(display t))))
12172 (set-buffer-modified-p bmp)))
12173 (if (featurep 'xemacs)
12174 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12175 (org-restart-font-lock)
12176 (setq org-table-may-need-update t)
12177 (if org-display-custom-times
12178 (message "Time stamps are overlayed with custom format")
12179 (message "Time stamp overlays removed")))
12181 (defun org-display-custom-time (beg end)
12182 "Overlay modified time stamp format over timestamp between BEG and END."
12183 (let* ((ts (buffer-substring beg end))
12184 t1 w1 with-hm tf time str w2 (off 0))
12185 (save-match-data
12186 (setq t1 (org-parse-time-string ts t))
12187 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12188 (setq off (- (match-end 0) (match-beginning 0)))))
12189 (setq end (- end off))
12190 (setq w1 (- end beg)
12191 with-hm (and (nth 1 t1) (nth 2 t1))
12192 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12193 time (org-fix-decoded-time t1)
12194 str (org-add-props
12195 (format-time-string
12196 (substring tf 1 -1) (apply 'encode-time time))
12197 nil 'mouse-face 'highlight)
12198 w2 (length str))
12199 (if (not (= w2 w1))
12200 (add-text-properties (1+ beg) (+ 2 beg)
12201 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12202 (if (featurep 'xemacs)
12203 (progn
12204 (put-text-property beg end 'invisible t)
12205 (put-text-property beg end 'end-glyph (make-glyph str)))
12206 (put-text-property beg end 'display str))))
12208 (defun org-translate-time (string)
12209 "Translate all timestamps in STRING to custom format.
12210 But do this only if the variable `org-display-custom-times' is set."
12211 (when org-display-custom-times
12212 (save-match-data
12213 (let* ((start 0)
12214 (re org-ts-regexp-both)
12215 t1 with-hm inactive tf time str beg end)
12216 (while (setq start (string-match re string start))
12217 (setq beg (match-beginning 0)
12218 end (match-end 0)
12219 t1 (save-match-data
12220 (org-parse-time-string (substring string beg end) t))
12221 with-hm (and (nth 1 t1) (nth 2 t1))
12222 inactive (equal (substring string beg (1+ beg)) "[")
12223 tf (funcall (if with-hm 'cdr 'car)
12224 org-time-stamp-custom-formats)
12225 time (org-fix-decoded-time t1)
12226 str (format-time-string
12227 (concat
12228 (if inactive "[" "<") (substring tf 1 -1)
12229 (if inactive "]" ">"))
12230 (apply 'encode-time time))
12231 string (replace-match str t t string)
12232 start (+ start (length str)))))))
12233 string)
12235 (defun org-fix-decoded-time (time)
12236 "Set 0 instead of nil for the first 6 elements of time.
12237 Don't touch the rest."
12238 (let ((n 0))
12239 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12241 (defun org-days-to-time (timestamp-string)
12242 "Difference between TIMESTAMP-STRING and now in days."
12243 (- (time-to-days (org-time-string-to-time timestamp-string))
12244 (time-to-days (current-time))))
12246 (defun org-deadline-close (timestamp-string &optional ndays)
12247 "Is the time in TIMESTAMP-STRING close to the current date?"
12248 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12249 (and (< (org-days-to-time timestamp-string) ndays)
12250 (not (org-entry-is-done-p))))
12252 (defun org-get-wdays (ts)
12253 "Get the deadline lead time appropriate for timestring TS."
12254 (cond
12255 ((<= org-deadline-warning-days 0)
12256 ;; 0 or negative, enforce this value no matter what
12257 (- org-deadline-warning-days))
12258 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12259 ;; lead time is specified.
12260 (floor (* (string-to-number (match-string 1 ts))
12261 (cdr (assoc (match-string 2 ts)
12262 '(("d" . 1) ("w" . 7)
12263 ("m" . 30.4) ("y" . 365.25)))))))
12264 ;; go for the default.
12265 (t org-deadline-warning-days)))
12267 (defun org-calendar-select-mouse (ev)
12268 "Return to `org-read-date' with the date currently selected.
12269 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12270 (interactive "e")
12271 (mouse-set-point ev)
12272 (when (calendar-cursor-to-date)
12273 (let* ((date (calendar-cursor-to-date))
12274 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12275 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12276 (if (active-minibuffer-window) (exit-minibuffer))))
12278 (defun org-check-deadlines (ndays)
12279 "Check if there are any deadlines due or past due.
12280 A deadline is considered due if it happens within `org-deadline-warning-days'
12281 days from today's date. If the deadline appears in an entry marked DONE,
12282 it is not shown. The prefix arg NDAYS can be used to test that many
12283 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12284 (interactive "P")
12285 (let* ((org-warn-days
12286 (cond
12287 ((equal ndays '(4)) 100000)
12288 (ndays (prefix-numeric-value ndays))
12289 (t (abs org-deadline-warning-days))))
12290 (case-fold-search nil)
12291 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12292 (callback
12293 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12295 (message "%d deadlines past-due or due within %d days"
12296 (org-occur regexp nil callback)
12297 org-warn-days)))
12299 (defun org-check-before-date (date)
12300 "Check if there are deadlines or scheduled entries before DATE."
12301 (interactive (list (org-read-date)))
12302 (let ((case-fold-search nil)
12303 (regexp (concat "\\<\\(" org-deadline-string
12304 "\\|" org-scheduled-string
12305 "\\) *<\\([^>]+\\)>"))
12306 (callback
12307 (lambda () (time-less-p
12308 (org-time-string-to-time (match-string 2))
12309 (org-time-string-to-time date)))))
12310 (message "%d entries before %s"
12311 (org-occur regexp nil callback) date)))
12313 (defun org-check-after-date (date)
12314 "Check if there are deadlines or scheduled entries after DATE."
12315 (interactive (list (org-read-date)))
12316 (let ((case-fold-search nil)
12317 (regexp (concat "\\<\\(" org-deadline-string
12318 "\\|" org-scheduled-string
12319 "\\) *<\\([^>]+\\)>"))
12320 (callback
12321 (lambda () (not
12322 (time-less-p
12323 (org-time-string-to-time (match-string 2))
12324 (org-time-string-to-time date))))))
12325 (message "%d entries after %s"
12326 (org-occur regexp nil callback) date)))
12328 (defun org-evaluate-time-range (&optional to-buffer)
12329 "Evaluate a time range by computing the difference between start and end.
12330 Normally the result is just printed in the echo area, but with prefix arg
12331 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12332 If the time range is actually in a table, the result is inserted into the
12333 next column.
12334 For time difference computation, a year is assumed to be exactly 365
12335 days in order to avoid rounding problems."
12336 (interactive "P")
12338 (org-clock-update-time-maybe)
12339 (save-excursion
12340 (unless (org-at-date-range-p t)
12341 (goto-char (point-at-bol))
12342 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12343 (if (not (org-at-date-range-p t))
12344 (error "Not at a time-stamp range, and none found in current line")))
12345 (let* ((ts1 (match-string 1))
12346 (ts2 (match-string 2))
12347 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12348 (match-end (match-end 0))
12349 (time1 (org-time-string-to-time ts1))
12350 (time2 (org-time-string-to-time ts2))
12351 (t1 (time-to-seconds time1))
12352 (t2 (time-to-seconds time2))
12353 (diff (abs (- t2 t1)))
12354 (negative (< (- t2 t1) 0))
12355 ;; (ys (floor (* 365 24 60 60)))
12356 (ds (* 24 60 60))
12357 (hs (* 60 60))
12358 (fy "%dy %dd %02d:%02d")
12359 (fy1 "%dy %dd")
12360 (fd "%dd %02d:%02d")
12361 (fd1 "%dd")
12362 (fh "%02d:%02d")
12363 y d h m align)
12364 (if havetime
12365 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12367 d (floor (/ diff ds)) diff (mod diff ds)
12368 h (floor (/ diff hs)) diff (mod diff hs)
12369 m (floor (/ diff 60)))
12370 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12372 d (floor (+ (/ diff ds) 0.5))
12373 h 0 m 0))
12374 (if (not to-buffer)
12375 (message "%s" (org-make-tdiff-string y d h m))
12376 (if (org-at-table-p)
12377 (progn
12378 (goto-char match-end)
12379 (setq align t)
12380 (and (looking-at " *|") (goto-char (match-end 0))))
12381 (goto-char match-end))
12382 (if (looking-at
12383 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12384 (replace-match ""))
12385 (if negative (insert " -"))
12386 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12387 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12388 (insert " " (format fh h m))))
12389 (if align (org-table-align))
12390 (message "Time difference inserted")))))
12392 (defun org-make-tdiff-string (y d h m)
12393 (let ((fmt "")
12394 (l nil))
12395 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12396 l (push y l)))
12397 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12398 l (push d l)))
12399 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12400 l (push h l)))
12401 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12402 l (push m l)))
12403 (apply 'format fmt (nreverse l))))
12405 (defun org-time-string-to-time (s)
12406 (apply 'encode-time (org-parse-time-string s)))
12408 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12409 "Convert a time stamp to an absolute day number.
12410 If there is a specifyer for a cyclic time stamp, get the closest date to
12411 DAYNR.
12412 PREFER and SHOW-ALL are passed through to `org-closest-date'."
12413 (cond
12414 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12415 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12416 daynr
12417 (+ daynr 1000)))
12418 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12419 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12420 (time-to-days (current-time))) (match-string 0 s)
12421 prefer show-all))
12422 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12424 (defun org-days-to-iso-week (days)
12425 "Return the iso week number."
12426 (require 'cal-iso)
12427 (car (calendar-iso-from-absolute days)))
12429 (defun org-small-year-to-year (year)
12430 "Convert 2-digit years into 4-digit years.
12431 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12432 The year 2000 cannot be abbreviated. Any year larger than 99
12433 is returned unchanged."
12434 (if (< year 38)
12435 (setq year (+ 2000 year))
12436 (if (< year 100)
12437 (setq year (+ 1900 year))))
12438 year)
12440 (defun org-time-from-absolute (d)
12441 "Return the time corresponding to date D.
12442 D may be an absolute day number, or a calendar-type list (month day year)."
12443 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12444 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12446 (defun org-calendar-holiday ()
12447 "List of holidays, for Diary display in Org-mode."
12448 (require 'holidays)
12449 (let ((hl (funcall
12450 (if (fboundp 'calendar-check-holidays)
12451 'calendar-check-holidays 'check-calendar-holidays) date)))
12452 (if hl (mapconcat 'identity hl "; "))))
12454 (defun org-diary-sexp-entry (sexp entry date)
12455 "Process a SEXP diary ENTRY for DATE."
12456 (require 'diary-lib)
12457 (let ((result (if calendar-debug-sexp
12458 (let ((stack-trace-on-error t))
12459 (eval (car (read-from-string sexp))))
12460 (condition-case nil
12461 (eval (car (read-from-string sexp)))
12462 (error
12463 (beep)
12464 (message "Bad sexp at line %d in %s: %s"
12465 (org-current-line)
12466 (buffer-file-name) sexp)
12467 (sleep-for 2))))))
12468 (cond ((stringp result) result)
12469 ((and (consp result)
12470 (stringp (cdr result))) (cdr result))
12471 (result entry)
12472 (t nil))))
12474 (defun org-diary-to-ical-string (frombuf)
12475 "Get iCalendar entries from diary entries in buffer FROMBUF.
12476 This uses the icalendar.el library."
12477 (let* ((tmpdir (if (featurep 'xemacs)
12478 (temp-directory)
12479 temporary-file-directory))
12480 (tmpfile (make-temp-name
12481 (expand-file-name "orgics" tmpdir)))
12482 buf rtn b e)
12483 (save-excursion
12484 (set-buffer frombuf)
12485 (icalendar-export-region (point-min) (point-max) tmpfile)
12486 (setq buf (find-buffer-visiting tmpfile))
12487 (set-buffer buf)
12488 (goto-char (point-min))
12489 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12490 (setq b (match-beginning 0)))
12491 (goto-char (point-max))
12492 (if (re-search-backward "^END:VEVENT" nil t)
12493 (setq e (match-end 0)))
12494 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12495 (kill-buffer buf)
12496 (delete-file tmpfile)
12497 rtn))
12499 (defun org-closest-date (start current change prefer show-all)
12500 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12501 When PREFER is `past' return a date that is either CURRENT or past.
12502 When PREFER is `future', return a date that is either CURRENT or future.
12503 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12504 ;; Make the proper lists from the dates
12505 (catch 'exit
12506 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12507 dn dw sday cday n1 n2 n0
12508 d m y y1 y2 date1 date2 nmonths nm ny m2)
12510 (setq start (org-date-to-gregorian start)
12511 current (org-date-to-gregorian
12512 (if show-all
12513 current
12514 (time-to-days (current-time))))
12515 sday (calendar-absolute-from-gregorian start)
12516 cday (calendar-absolute-from-gregorian current))
12518 (if (<= cday sday) (throw 'exit sday))
12520 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12521 (setq dn (string-to-number (match-string 1 change))
12522 dw (cdr (assoc (match-string 2 change) a1)))
12523 (error "Invalid change specifyer: %s" change))
12524 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12525 (cond
12526 ((eq dw 'day)
12527 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12528 n2 (+ n1 dn)))
12529 ((eq dw 'year)
12530 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12531 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12532 (setq date1 (list m d y1)
12533 n1 (calendar-absolute-from-gregorian date1)
12534 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12535 n2 (calendar-absolute-from-gregorian date2)))
12536 ((eq dw 'month)
12537 ;; approx number of month between the two dates
12538 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12539 ;; How often does dn fit in there?
12540 (setq d (nth 1 start) m (car start) y (nth 2 start)
12541 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12542 m (+ m nm)
12543 ny (floor (/ m 12))
12544 y (+ y ny)
12545 m (- m (* ny 12)))
12546 (while (> m 12) (setq m (- m 12) y (1+ y)))
12547 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12548 (setq m2 (+ m dn) y2 y)
12549 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12550 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12551 (while (<= n2 cday)
12552 (setq n1 n2 m m2 y y2)
12553 (setq m2 (+ m dn) y2 y)
12554 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12555 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12556 ;; Make sure n1 is the earlier date
12557 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12558 (if show-all
12559 (cond
12560 ((eq prefer 'past) n1)
12561 ((eq prefer 'future) (if (= cday n1) n1 n2))
12562 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12563 (cond
12564 ((eq prefer 'past) n1)
12565 ((eq prefer 'future) (if (= cday n1) n1 n2))
12566 (t (if (= cday n1) n1 n2)))))))
12568 (defun org-date-to-gregorian (date)
12569 "Turn any specification of DATE into a gregorian date for the calendar."
12570 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12571 ((and (listp date) (= (length date) 3)) date)
12572 ((stringp date)
12573 (setq date (org-parse-time-string date))
12574 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12575 ((listp date)
12576 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12578 (defun org-parse-time-string (s &optional nodefault)
12579 "Parse the standard Org-mode time string.
12580 This should be a lot faster than the normal `parse-time-string'.
12581 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12582 hour and minute fields will be nil if not given."
12583 (if (string-match org-ts-regexp0 s)
12584 (list 0
12585 (if (or (match-beginning 8) (not nodefault))
12586 (string-to-number (or (match-string 8 s) "0")))
12587 (if (or (match-beginning 7) (not nodefault))
12588 (string-to-number (or (match-string 7 s) "0")))
12589 (string-to-number (match-string 4 s))
12590 (string-to-number (match-string 3 s))
12591 (string-to-number (match-string 2 s))
12592 nil nil nil)
12593 (make-list 9 0)))
12595 (defun org-timestamp-up (&optional arg)
12596 "Increase the date item at the cursor by one.
12597 If the cursor is on the year, change the year. If it is on the month or
12598 the day, change that.
12599 With prefix ARG, change by that many units."
12600 (interactive "p")
12601 (org-timestamp-change (prefix-numeric-value arg)))
12603 (defun org-timestamp-down (&optional arg)
12604 "Decrease the date item at the cursor by one.
12605 If the cursor is on the year, change the year. If it is on the month or
12606 the day, change that.
12607 With prefix ARG, change by that many units."
12608 (interactive "p")
12609 (org-timestamp-change (- (prefix-numeric-value arg))))
12611 (defun org-timestamp-up-day (&optional arg)
12612 "Increase the date in the time stamp by one day.
12613 With prefix ARG, change that many days."
12614 (interactive "p")
12615 (if (and (not (org-at-timestamp-p t))
12616 (org-on-heading-p))
12617 (org-todo 'up)
12618 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12620 (defun org-timestamp-down-day (&optional arg)
12621 "Decrease the date in the time stamp by one day.
12622 With prefix ARG, change that many days."
12623 (interactive "p")
12624 (if (and (not (org-at-timestamp-p t))
12625 (org-on-heading-p))
12626 (org-todo 'down)
12627 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12629 (defun org-at-timestamp-p (&optional inactive-ok)
12630 "Determine if the cursor is in or at a timestamp."
12631 (interactive)
12632 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12633 (pos (point))
12634 (ans (or (looking-at tsr)
12635 (save-excursion
12636 (skip-chars-backward "^[<\n\r\t")
12637 (if (> (point) (point-min)) (backward-char 1))
12638 (and (looking-at tsr)
12639 (> (- (match-end 0) pos) -1))))))
12640 (and ans
12641 (boundp 'org-ts-what)
12642 (setq org-ts-what
12643 (cond
12644 ((= pos (match-beginning 0)) 'bracket)
12645 ((= pos (1- (match-end 0))) 'bracket)
12646 ((org-pos-in-match-range pos 2) 'year)
12647 ((org-pos-in-match-range pos 3) 'month)
12648 ((org-pos-in-match-range pos 7) 'hour)
12649 ((org-pos-in-match-range pos 8) 'minute)
12650 ((or (org-pos-in-match-range pos 4)
12651 (org-pos-in-match-range pos 5)) 'day)
12652 ((and (> pos (or (match-end 8) (match-end 5)))
12653 (< pos (match-end 0)))
12654 (- pos (or (match-end 8) (match-end 5))))
12655 (t 'day))))
12656 ans))
12658 (defun org-toggle-timestamp-type ()
12659 "Toggle the type (<active> or [inactive]) of a time stamp."
12660 (interactive)
12661 (when (org-at-timestamp-p t)
12662 (let ((beg (match-beginning 0)) (end (match-end 0))
12663 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12664 (save-excursion
12665 (goto-char beg)
12666 (while (re-search-forward "[][<>]" end t)
12667 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12668 t t)))
12669 (message "Timestamp is now %sactive"
12670 (if (equal (char-after beg) ?<) "" "in")))))
12672 (defun org-timestamp-change (n &optional what)
12673 "Change the date in the time stamp at point.
12674 The date will be changed by N times WHAT. WHAT can be `day', `month',
12675 `year', `minute', `second'. If WHAT is not given, the cursor position
12676 in the timestamp determines what will be changed."
12677 (let ((pos (point))
12678 with-hm inactive
12679 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12680 org-ts-what
12681 extra rem
12682 ts time time0)
12683 (if (not (org-at-timestamp-p t))
12684 (error "Not at a timestamp"))
12685 (if (and (not what) (eq org-ts-what 'bracket))
12686 (org-toggle-timestamp-type)
12687 (if (and (not what) (not (eq org-ts-what 'day))
12688 org-display-custom-times
12689 (get-text-property (point) 'display)
12690 (not (get-text-property (1- (point)) 'display)))
12691 (setq org-ts-what 'day))
12692 (setq org-ts-what (or what org-ts-what)
12693 inactive (= (char-after (match-beginning 0)) ?\[)
12694 ts (match-string 0))
12695 (replace-match "")
12696 (if (string-match
12697 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12699 (setq extra (match-string 1 ts)))
12700 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12701 (setq with-hm t))
12702 (setq time0 (org-parse-time-string ts))
12703 (when (and (eq org-ts-what 'minute)
12704 (eq current-prefix-arg nil))
12705 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12706 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12707 (setcar (cdr time0) (+ (nth 1 time0)
12708 (if (> n 0) (- rem) (- dm rem))))))
12709 (setq time
12710 (encode-time (or (car time0) 0)
12711 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12712 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12713 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12714 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12715 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12716 (nthcdr 6 time0)))
12717 (when (and (member org-ts-what '(hour minute))
12718 extra
12719 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
12720 (setq extra (org-modify-ts-extra
12721 extra
12722 (if (eq org-ts-what 'hour) 2 5)
12723 n dm)))
12724 (when (integerp org-ts-what)
12725 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12726 (if (eq what 'calendar)
12727 (let ((cal-date (org-get-date-from-calendar)))
12728 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12729 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12730 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12731 (setcar time0 (or (car time0) 0))
12732 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12733 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12734 (setq time (apply 'encode-time time0))))
12735 (setq org-last-changed-timestamp
12736 (org-insert-time-stamp time with-hm inactive nil nil extra))
12737 (org-clock-update-time-maybe)
12738 (goto-char pos)
12739 ;; Try to recenter the calendar window, if any
12740 (if (and org-calendar-follow-timestamp-change
12741 (get-buffer-window "*Calendar*" t)
12742 (memq org-ts-what '(day month year)))
12743 (org-recenter-calendar (time-to-days time))))))
12745 (defun org-modify-ts-extra (s pos n dm)
12746 "Change the different parts of the lead-time and repeat fields in timestamp."
12747 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12748 ng h m new rem)
12749 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12750 (cond
12751 ((or (org-pos-in-match-range pos 2)
12752 (org-pos-in-match-range pos 3))
12753 (setq m (string-to-number (match-string 3 s))
12754 h (string-to-number (match-string 2 s)))
12755 (if (org-pos-in-match-range pos 2)
12756 (setq h (+ h n))
12757 (setq n (* dm (org-no-warnings (signum n))))
12758 (when (not (= 0 (setq rem (% m dm))))
12759 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12760 (setq m (+ m n)))
12761 (if (< m 0) (setq m (+ m 60) h (1- h)))
12762 (if (> m 59) (setq m (- m 60) h (1+ h)))
12763 (setq h (min 24 (max 0 h)))
12764 (setq ng 1 new (format "-%02d:%02d" h m)))
12765 ((org-pos-in-match-range pos 6)
12766 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12767 ((org-pos-in-match-range pos 5)
12768 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12770 ((org-pos-in-match-range pos 9)
12771 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12772 ((org-pos-in-match-range pos 8)
12773 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12775 (when ng
12776 (setq s (concat
12777 (substring s 0 (match-beginning ng))
12779 (substring s (match-end ng))))))
12782 (defun org-recenter-calendar (date)
12783 "If the calendar is visible, recenter it to DATE."
12784 (let* ((win (selected-window))
12785 (cwin (get-buffer-window "*Calendar*" t))
12786 (calendar-move-hook nil))
12787 (when cwin
12788 (select-window cwin)
12789 (calendar-goto-date (if (listp date) date
12790 (calendar-gregorian-from-absolute date)))
12791 (select-window win))))
12793 (defun org-goto-calendar (&optional arg)
12794 "Go to the Emacs calendar at the current date.
12795 If there is a time stamp in the current line, go to that date.
12796 A prefix ARG can be used to force the current date."
12797 (interactive "P")
12798 (let ((tsr org-ts-regexp) diff
12799 (calendar-move-hook nil)
12800 (calendar-view-holidays-initially-flag nil)
12801 (view-calendar-holidays-initially nil)
12802 (calendar-view-diary-initially-flag nil)
12803 (view-diary-entries-initially nil))
12804 (if (or (org-at-timestamp-p)
12805 (save-excursion
12806 (beginning-of-line 1)
12807 (looking-at (concat ".*" tsr))))
12808 (let ((d1 (time-to-days (current-time)))
12809 (d2 (time-to-days
12810 (org-time-string-to-time (match-string 1)))))
12811 (setq diff (- d2 d1))))
12812 (calendar)
12813 (calendar-goto-today)
12814 (if (and diff (not arg)) (calendar-forward-day diff))))
12816 (defun org-get-date-from-calendar ()
12817 "Return a list (month day year) of date at point in calendar."
12818 (with-current-buffer "*Calendar*"
12819 (save-match-data
12820 (calendar-cursor-to-date))))
12822 (defun org-date-from-calendar ()
12823 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12824 If there is already a time stamp at the cursor position, update it."
12825 (interactive)
12826 (if (org-at-timestamp-p t)
12827 (org-timestamp-change 0 'calendar)
12828 (let ((cal-date (org-get-date-from-calendar)))
12829 (org-insert-time-stamp
12830 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12832 (defun org-minutes-to-hh:mm-string (m)
12833 "Compute H:MM from a number of minutes."
12834 (let ((h (/ m 60)))
12835 (setq m (- m (* 60 h)))
12836 (format org-time-clocksum-format h m)))
12838 (defun org-hh:mm-string-to-minutes (s)
12839 "Convert a string H:MM to a number of minutes."
12840 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12841 (+ (* (string-to-number (match-string 1 s)) 60)
12842 (string-to-number (match-string 2 s)))
12845 ;;;; Files
12847 (defun org-save-all-org-buffers ()
12848 "Save all Org-mode buffers without user confirmation."
12849 (interactive)
12850 (message "Saving all Org-mode buffers...")
12851 (save-some-buffers t 'org-mode-p)
12852 (when (featurep 'org-id) (org-id-locations-save))
12853 (message "Saving all Org-mode buffers... done"))
12855 (defun org-revert-all-org-buffers ()
12856 "Revert all Org-mode buffers.
12857 Prompt for confirmation when there are unsaved changes.
12858 Be sure you know what you are doing before letting this function
12859 overwrite your changes.
12861 This function is useful in a setup where one tracks org files
12862 with a version control system, to revert on one machine after pulling
12863 changes from another. I believe the procedure must be like this:
12865 1. M-x org-save-all-org-buffers
12866 2. Pull changes from the other machine, resolve conflicts
12867 3. M-x org-revert-all-org-buffers"
12868 (interactive)
12869 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
12870 (error "Abort"))
12871 (save-excursion
12872 (save-window-excursion
12873 (mapc
12874 (lambda (b)
12875 (when (and (with-current-buffer b (org-mode-p))
12876 (with-current-buffer b buffer-file-name))
12877 (switch-to-buffer b)
12878 (revert-buffer t 'no-confirm)))
12879 (buffer-list))
12880 (when (and (featurep 'org-id) org-id-track-globally)
12881 (org-id-locations-load)))))
12883 ;;;; Agenda files
12885 ;;;###autoload
12886 (defun org-iswitchb (&optional arg)
12887 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12888 With a prefix argument, restrict available to files.
12889 With two prefix arguments, restrict available buffers to agenda files.
12891 Due to some yet unresolved reason, the global function
12892 `iswitchb-mode' needs to be active for this function to work."
12893 (interactive "P")
12894 (require 'iswitchb)
12895 (let ((enabled iswitchb-mode) blist)
12896 (or enabled (iswitchb-mode 1))
12897 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12898 ((equal arg '(16)) (org-buffer-list 'agenda))
12899 (t (org-buffer-list))))
12900 (unwind-protect
12901 (let ((iswitchb-make-buflist-hook
12902 (lambda ()
12903 (setq iswitchb-temp-buflist
12904 (mapcar 'buffer-name blist)))))
12905 (switch-to-buffer
12906 (iswitchb-read-buffer
12907 "Switch-to: " nil t))
12908 (or enabled (iswitchb-mode -1))))))
12910 ;;;###autoload
12911 (defun org-ido-switchb (&optional arg)
12912 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12913 With a prefix argument, restrict available to files.
12914 With two prefix arguments, restrict available buffers to agenda files."
12915 (interactive "P")
12916 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12917 ((equal arg '(16)) (org-buffer-list 'agenda))
12918 (t (org-buffer-list)))))
12919 (switch-to-buffer
12920 (org-ido-completing-read "Org buffer: "
12921 (mapcar 'list (mapcar 'buffer-name blist))
12922 nil t))))
12924 (defun org-buffer-list (&optional predicate exclude-tmp)
12925 "Return a list of Org buffers.
12926 PREDICATE can be `export', `files' or `agenda'.
12928 export restrict the list to Export buffers.
12929 files restrict the list to buffers visiting Org files.
12930 agenda restrict the list to buffers visiting agenda files.
12932 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12933 (let* ((bfn nil)
12934 (agenda-files (and (eq predicate 'agenda)
12935 (mapcar 'file-truename (org-agenda-files t))))
12936 (filter
12937 (cond
12938 ((eq predicate 'files)
12939 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12940 ((eq predicate 'export)
12941 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12942 ((eq predicate 'agenda)
12943 (lambda (b)
12944 (with-current-buffer b
12945 (and (eq major-mode 'org-mode)
12946 (setq bfn (buffer-file-name b))
12947 (member (file-truename bfn) agenda-files)))))
12948 (t (lambda (b) (with-current-buffer b
12949 (or (eq major-mode 'org-mode)
12950 (string-match "\*Org .*Export"
12951 (buffer-name b)))))))))
12952 (delq nil
12953 (mapcar
12954 (lambda(b)
12955 (if (and (funcall filter b)
12956 (or (not exclude-tmp)
12957 (not (string-match "tmp" (buffer-name b)))))
12959 nil))
12960 (buffer-list)))))
12962 (defun org-agenda-files (&optional unrestricted archives)
12963 "Get the list of agenda files.
12964 Optional UNRESTRICTED means return the full list even if a restriction
12965 is currently in place.
12966 When ARCHIVES is t, include all archive files hat are really being
12967 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12968 `org-agenda-archives-mode' is t."
12969 (let ((files
12970 (cond
12971 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12972 ((stringp org-agenda-files) (org-read-agenda-file-list))
12973 ((listp org-agenda-files) org-agenda-files)
12974 (t (error "Invalid value of `org-agenda-files'")))))
12975 (setq files (apply 'append
12976 (mapcar (lambda (f)
12977 (if (file-directory-p f)
12978 (directory-files
12979 f t org-agenda-file-regexp)
12980 (list f)))
12981 files)))
12982 (when org-agenda-skip-unavailable-files
12983 (setq files (delq nil
12984 (mapcar (function
12985 (lambda (file)
12986 (and (file-readable-p file) file)))
12987 files))))
12988 (when (or (eq archives t)
12989 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12990 (setq files (org-add-archive-files files)))
12991 files))
12993 (defun org-edit-agenda-file-list ()
12994 "Edit the list of agenda files.
12995 Depending on setup, this either uses customize to edit the variable
12996 `org-agenda-files', or it visits the file that is holding the list. In the
12997 latter case, the buffer is set up in a way that saving it automatically kills
12998 the buffer and restores the previous window configuration."
12999 (interactive)
13000 (if (stringp org-agenda-files)
13001 (let ((cw (current-window-configuration)))
13002 (find-file org-agenda-files)
13003 (org-set-local 'org-window-configuration cw)
13004 (org-add-hook 'after-save-hook
13005 (lambda ()
13006 (set-window-configuration
13007 (prog1 org-window-configuration
13008 (kill-buffer (current-buffer))))
13009 (org-install-agenda-files-menu)
13010 (message "New agenda file list installed"))
13011 nil 'local)
13012 (message "%s" (substitute-command-keys
13013 "Edit list and finish with \\[save-buffer]")))
13014 (customize-variable 'org-agenda-files)))
13016 (defun org-store-new-agenda-file-list (list)
13017 "Set new value for the agenda file list and save it correctly."
13018 (if (stringp org-agenda-files)
13019 (let ((f org-agenda-files) b)
13020 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13021 (with-temp-file f
13022 (insert (mapconcat 'identity list "\n") "\n")))
13023 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13024 (setq org-agenda-files list)
13025 (customize-save-variable 'org-agenda-files org-agenda-files))))
13027 (defun org-read-agenda-file-list ()
13028 "Read the list of agenda files from a file."
13029 (when (file-directory-p org-agenda-files)
13030 (error "`org-agenda-files' cannot be a single directory"))
13031 (when (stringp org-agenda-files)
13032 (with-temp-buffer
13033 (insert-file-contents org-agenda-files)
13034 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13037 ;;;###autoload
13038 (defun org-cycle-agenda-files ()
13039 "Cycle through the files in `org-agenda-files'.
13040 If the current buffer visits an agenda file, find the next one in the list.
13041 If the current buffer does not, find the first agenda file."
13042 (interactive)
13043 (let* ((fs (org-agenda-files t))
13044 (files (append fs (list (car fs))))
13045 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13046 file)
13047 (unless files (error "No agenda files"))
13048 (catch 'exit
13049 (while (setq file (pop files))
13050 (if (equal (file-truename file) tcf)
13051 (when (car files)
13052 (find-file (car files))
13053 (throw 'exit t))))
13054 (find-file (car fs)))
13055 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13057 (defun org-agenda-file-to-front (&optional to-end)
13058 "Move/add the current file to the top of the agenda file list.
13059 If the file is not present in the list, it is added to the front. If it is
13060 present, it is moved there. With optional argument TO-END, add/move to the
13061 end of the list."
13062 (interactive "P")
13063 (let ((org-agenda-skip-unavailable-files nil)
13064 (file-alist (mapcar (lambda (x)
13065 (cons (file-truename x) x))
13066 (org-agenda-files t)))
13067 (ctf (file-truename buffer-file-name))
13068 x had)
13069 (setq x (assoc ctf file-alist) had x)
13071 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13072 (if to-end
13073 (setq file-alist (append (delq x file-alist) (list x)))
13074 (setq file-alist (cons x (delq x file-alist))))
13075 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13076 (org-install-agenda-files-menu)
13077 (message "File %s to %s of agenda file list"
13078 (if had "moved" "added") (if to-end "end" "front"))))
13080 (defun org-remove-file (&optional file)
13081 "Remove current file from the list of files in variable `org-agenda-files'.
13082 These are the files which are being checked for agenda entries.
13083 Optional argument FILE means, use this file instead of the current."
13084 (interactive)
13085 (let* ((org-agenda-skip-unavailable-files nil)
13086 (file (or file buffer-file-name))
13087 (true-file (file-truename file))
13088 (afile (abbreviate-file-name file))
13089 (files (delq nil (mapcar
13090 (lambda (x)
13091 (if (equal true-file
13092 (file-truename x))
13093 nil x))
13094 (org-agenda-files t)))))
13095 (if (not (= (length files) (length (org-agenda-files t))))
13096 (progn
13097 (org-store-new-agenda-file-list files)
13098 (org-install-agenda-files-menu)
13099 (message "Removed file: %s" afile))
13100 (message "File was not in list: %s (not removed)" afile))))
13102 (defun org-file-menu-entry (file)
13103 (vector file (list 'find-file file) t))
13105 (defun org-check-agenda-file (file)
13106 "Make sure FILE exists. If not, ask user what to do."
13107 (when (not (file-exists-p file))
13108 (message "non-existent file %s. [R]emove from list or [A]bort?"
13109 (abbreviate-file-name file))
13110 (let ((r (downcase (read-char-exclusive))))
13111 (cond
13112 ((equal r ?r)
13113 (org-remove-file file)
13114 (throw 'nextfile t))
13115 (t (error "Abort"))))))
13117 (defun org-get-agenda-file-buffer (file)
13118 "Get a buffer visiting FILE. If the buffer needs to be created, add
13119 it to the list of buffers which might be released later."
13120 (let ((buf (org-find-base-buffer-visiting file)))
13121 (if buf
13122 buf ; just return it
13123 ;; Make a new buffer and remember it
13124 (setq buf (find-file-noselect file))
13125 (if buf (push buf org-agenda-new-buffers))
13126 buf)))
13128 (defun org-release-buffers (blist)
13129 "Release all buffers in list, asking the user for confirmation when needed.
13130 When a buffer is unmodified, it is just killed. When modified, it is saved
13131 \(if the user agrees) and then killed."
13132 (let (buf file)
13133 (while (setq buf (pop blist))
13134 (setq file (buffer-file-name buf))
13135 (when (and (buffer-modified-p buf)
13136 file
13137 (y-or-n-p (format "Save file %s? " file)))
13138 (with-current-buffer buf (save-buffer)))
13139 (kill-buffer buf))))
13141 (defun org-prepare-agenda-buffers (files)
13142 "Create buffers for all agenda files, protect archived trees and comments."
13143 (interactive)
13144 (let ((pa '(:org-archived t))
13145 (pc '(:org-comment t))
13146 (pall '(:org-archived t :org-comment t))
13147 (inhibit-read-only t)
13148 (rea (concat ":" org-archive-tag ":"))
13149 bmp file re)
13150 (save-excursion
13151 (save-restriction
13152 (while (setq file (pop files))
13153 (if (bufferp file)
13154 (set-buffer file)
13155 (org-check-agenda-file file)
13156 (set-buffer (org-get-agenda-file-buffer file)))
13157 (widen)
13158 (setq bmp (buffer-modified-p))
13159 (org-refresh-category-properties)
13160 (setq org-todo-keywords-for-agenda
13161 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13162 (setq org-done-keywords-for-agenda
13163 (append org-done-keywords-for-agenda org-done-keywords))
13164 (setq org-todo-keyword-alist-for-agenda
13165 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13166 (setq org-tag-alist-for-agenda
13167 (append org-tag-alist-for-agenda org-tag-alist))
13169 (save-excursion
13170 (remove-text-properties (point-min) (point-max) pall)
13171 (when org-agenda-skip-archived-trees
13172 (goto-char (point-min))
13173 (while (re-search-forward rea nil t)
13174 (if (org-on-heading-p t)
13175 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13176 (goto-char (point-min))
13177 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13178 (while (re-search-forward re nil t)
13179 (add-text-properties
13180 (match-beginning 0) (org-end-of-subtree t) pc)))
13181 (set-buffer-modified-p bmp))))
13182 (setq org-todo-keyword-alist-for-agenda
13183 (org-uniquify org-todo-keyword-alist-for-agenda)
13184 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13186 ;;;; Embedded LaTeX
13188 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13189 "Keymap for the minor `org-cdlatex-mode'.")
13191 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13192 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13193 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13194 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13195 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13197 (defvar org-cdlatex-texmathp-advice-is-done nil
13198 "Flag remembering if we have applied the advice to texmathp already.")
13200 (define-minor-mode org-cdlatex-mode
13201 "Toggle the minor `org-cdlatex-mode'.
13202 This mode supports entering LaTeX environment and math in LaTeX fragments
13203 in Org-mode.
13204 \\{org-cdlatex-mode-map}"
13205 nil " OCDL" nil
13206 (when org-cdlatex-mode (require 'cdlatex))
13207 (unless org-cdlatex-texmathp-advice-is-done
13208 (setq org-cdlatex-texmathp-advice-is-done t)
13209 (defadvice texmathp (around org-math-always-on activate)
13210 "Always return t in org-mode buffers.
13211 This is because we want to insert math symbols without dollars even outside
13212 the LaTeX math segments. If Orgmode thinks that point is actually inside
13213 an embedded LaTeX fragment, let texmathp do its job.
13214 \\[org-cdlatex-mode-map]"
13215 (interactive)
13216 (let (p)
13217 (cond
13218 ((not (org-mode-p)) ad-do-it)
13219 ((eq this-command 'cdlatex-math-symbol)
13220 (setq ad-return-value t
13221 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13223 (let ((p (org-inside-LaTeX-fragment-p)))
13224 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13225 (setq ad-return-value t
13226 texmathp-why '("Org-mode embedded math" . 0))
13227 (if p ad-do-it)))))))))
13229 (defun turn-on-org-cdlatex ()
13230 "Unconditionally turn on `org-cdlatex-mode'."
13231 (org-cdlatex-mode 1))
13233 (defun org-inside-LaTeX-fragment-p ()
13234 "Test if point is inside a LaTeX fragment.
13235 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13236 sequence appearing also before point.
13237 Even though the matchers for math are configurable, this function assumes
13238 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13239 delimiters are skipped when they have been removed by customization.
13240 The return value is nil, or a cons cell with the delimiter and
13241 and the position of this delimiter.
13243 This function does a reasonably good job, but can locally be fooled by
13244 for example currency specifications. For example it will assume being in
13245 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13246 fragments that are properly closed, but during editing, we have to live
13247 with the uncertainty caused by missing closing delimiters. This function
13248 looks only before point, not after."
13249 (catch 'exit
13250 (let ((pos (point))
13251 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13252 (lim (progn
13253 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13254 (point)))
13255 dd-on str (start 0) m re)
13256 (goto-char pos)
13257 (when dodollar
13258 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13259 re (nth 1 (assoc "$" org-latex-regexps)))
13260 (while (string-match re str start)
13261 (cond
13262 ((= (match-end 0) (length str))
13263 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13264 ((= (match-end 0) (- (length str) 5))
13265 (throw 'exit nil))
13266 (t (setq start (match-end 0))))))
13267 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13268 (goto-char pos)
13269 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13270 (and (match-beginning 2) (throw 'exit nil))
13271 ;; count $$
13272 (while (re-search-backward "\\$\\$" lim t)
13273 (setq dd-on (not dd-on)))
13274 (goto-char pos)
13275 (if dd-on (cons "$$" m))))))
13278 (defun org-try-cdlatex-tab ()
13279 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13280 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13281 - inside a LaTeX fragment, or
13282 - after the first word in a line, where an abbreviation expansion could
13283 insert a LaTeX environment."
13284 (when org-cdlatex-mode
13285 (cond
13286 ((save-excursion
13287 (skip-chars-backward "a-zA-Z0-9*")
13288 (skip-chars-backward " \t")
13289 (bolp))
13290 (cdlatex-tab) t)
13291 ((org-inside-LaTeX-fragment-p)
13292 (cdlatex-tab) t)
13293 (t nil))))
13295 (defun org-cdlatex-underscore-caret (&optional arg)
13296 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13297 Revert to the normal definition outside of these fragments."
13298 (interactive "P")
13299 (if (org-inside-LaTeX-fragment-p)
13300 (call-interactively 'cdlatex-sub-superscript)
13301 (let (org-cdlatex-mode)
13302 (call-interactively (key-binding (vector last-input-event))))))
13304 (defun org-cdlatex-math-modify (&optional arg)
13305 "Execute `cdlatex-math-modify' in LaTeX fragments.
13306 Revert to the normal definition outside of these fragments."
13307 (interactive "P")
13308 (if (org-inside-LaTeX-fragment-p)
13309 (call-interactively 'cdlatex-math-modify)
13310 (let (org-cdlatex-mode)
13311 (call-interactively (key-binding (vector last-input-event))))))
13313 (defvar org-latex-fragment-image-overlays nil
13314 "List of overlays carrying the images of latex fragments.")
13315 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13317 (defun org-remove-latex-fragment-image-overlays ()
13318 "Remove all overlays with LaTeX fragment images in current buffer."
13319 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13320 (setq org-latex-fragment-image-overlays nil))
13322 (defun org-preview-latex-fragment (&optional subtree)
13323 "Preview the LaTeX fragment at point, or all locally or globally.
13324 If the cursor is in a LaTeX fragment, create the image and overlay
13325 it over the source code. If there is no fragment at point, display
13326 all fragments in the current text, from one headline to the next. With
13327 prefix SUBTREE, display all fragments in the current subtree. With a
13328 double prefix `C-u C-u', or when the cursor is before the first headline,
13329 display all fragments in the buffer.
13330 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13331 (interactive "P")
13332 (org-remove-latex-fragment-image-overlays)
13333 (save-excursion
13334 (save-restriction
13335 (let (beg end at msg)
13336 (cond
13337 ((or (equal subtree '(16))
13338 (not (save-excursion
13339 (re-search-backward (concat "^" outline-regexp) nil t))))
13340 (setq beg (point-min) end (point-max)
13341 msg "Creating images for buffer...%s"))
13342 ((equal subtree '(4))
13343 (org-back-to-heading)
13344 (setq beg (point) end (org-end-of-subtree t)
13345 msg "Creating images for subtree...%s"))
13347 (if (setq at (org-inside-LaTeX-fragment-p))
13348 (goto-char (max (point-min) (- (cdr at) 2)))
13349 (org-back-to-heading))
13350 (setq beg (point) end (progn (outline-next-heading) (point))
13351 msg (if at "Creating image...%s"
13352 "Creating images for entry...%s"))))
13353 (message msg "")
13354 (narrow-to-region beg end)
13355 (goto-char beg)
13356 (org-format-latex
13357 (concat "ltxpng/" (file-name-sans-extension
13358 (file-name-nondirectory
13359 buffer-file-name)))
13360 default-directory 'overlays msg at 'forbuffer)
13361 (message msg "done. Use `C-c C-c' to remove images.")))))
13363 (defvar org-latex-regexps
13364 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13365 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13366 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13367 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13368 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13369 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13370 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13371 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13372 "Regular expressions for matching embedded LaTeX.")
13374 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13375 "Replace LaTeX fragments with links to an image, and produce images."
13376 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13377 (let* ((prefixnodir (file-name-nondirectory prefix))
13378 (absprefix (expand-file-name prefix dir))
13379 (todir (file-name-directory absprefix))
13380 (opt org-format-latex-options)
13381 (matchers (plist-get opt :matchers))
13382 (re-list org-latex-regexps)
13383 (cnt 0) txt link beg end re e checkdir
13384 m n block linkfile movefile ov)
13385 ;; Check if there are old images files with this prefix, and remove them
13386 (when (file-directory-p todir)
13387 (mapc 'delete-file
13388 (directory-files
13389 todir 'full
13390 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13391 ;; Check the different regular expressions
13392 (while (setq e (pop re-list))
13393 (setq m (car e) re (nth 1 e) n (nth 2 e)
13394 block (if (nth 3 e) "\n\n" ""))
13395 (when (member m matchers)
13396 (goto-char (point-min))
13397 (while (re-search-forward re nil t)
13398 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13399 (not (get-text-property (match-beginning n)
13400 'org-protected)))
13401 (setq txt (match-string n)
13402 beg (match-beginning n) end (match-end n)
13403 cnt (1+ cnt)
13404 linkfile (format "%s_%04d.png" prefix cnt)
13405 movefile (format "%s_%04d.png" absprefix cnt)
13406 link (concat block "[[file:" linkfile "]]" block))
13407 (if msg (message msg cnt))
13408 (goto-char beg)
13409 (unless checkdir ; make sure the directory exists
13410 (setq checkdir t)
13411 (or (file-directory-p todir) (make-directory todir)))
13412 (org-create-formula-image
13413 txt movefile opt forbuffer)
13414 (if overlays
13415 (progn
13416 (setq ov (org-make-overlay beg end))
13417 (if (featurep 'xemacs)
13418 (progn
13419 (org-overlay-put ov 'invisible t)
13420 (org-overlay-put
13421 ov 'end-glyph
13422 (make-glyph (vector 'png :file movefile))))
13423 (org-overlay-put
13424 ov 'display
13425 (list 'image :type 'png :file movefile :ascent 'center)))
13426 (push ov org-latex-fragment-image-overlays)
13427 (goto-char end))
13428 (delete-region beg end)
13429 (insert link))))))))
13431 ;; This function borrows from Ganesh Swami's latex2png.el
13432 (defun org-create-formula-image (string tofile options buffer)
13433 (let* ((tmpdir (if (featurep 'xemacs)
13434 (temp-directory)
13435 temporary-file-directory))
13436 (texfilebase (make-temp-name
13437 (expand-file-name "orgtex" tmpdir)))
13438 (texfile (concat texfilebase ".tex"))
13439 (dvifile (concat texfilebase ".dvi"))
13440 (pngfile (concat texfilebase ".png"))
13441 (fnh (if (featurep 'xemacs)
13442 (font-height (get-face-font 'default))
13443 (face-attribute 'default :height nil)))
13444 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13445 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13446 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13447 "Black"))
13448 (bg (or (plist-get options (if buffer :background :html-background))
13449 "Transparent")))
13450 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13451 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13452 (with-temp-file texfile
13453 (insert org-format-latex-header
13454 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13455 (let ((dir default-directory))
13456 (condition-case nil
13457 (progn
13458 (cd tmpdir)
13459 (call-process "latex" nil nil nil texfile))
13460 (error nil))
13461 (cd dir))
13462 (if (not (file-exists-p dvifile))
13463 (progn (message "Failed to create dvi file from %s" texfile) nil)
13464 (condition-case nil
13465 (call-process "dvipng" nil nil nil
13466 "-E" "-fg" fg "-bg" bg
13467 "-D" dpi
13468 ;;"-x" scale "-y" scale
13469 "-T" "tight"
13470 "-o" pngfile
13471 dvifile)
13472 (error nil))
13473 (if (not (file-exists-p pngfile))
13474 (progn (message "Failed to create png file from %s" texfile) nil)
13475 ;; Use the requested file name and clean up
13476 (copy-file pngfile tofile 'replace)
13477 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13478 (delete-file (concat texfilebase e)))
13479 pngfile))))
13481 (defun org-dvipng-color (attr)
13482 "Return an rgb color specification for dvipng."
13483 (apply 'format "rgb %s %s %s"
13484 (mapcar 'org-normalize-color
13485 (color-values (face-attribute 'default attr nil)))))
13487 (defun org-normalize-color (value)
13488 "Return string to be used as color value for an RGB component."
13489 (format "%g" (/ value 65535.0)))
13491 ;;;; Key bindings
13493 ;; Make `C-c C-x' a prefix key
13494 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13496 ;; TAB key with modifiers
13497 (org-defkey org-mode-map "\C-i" 'org-cycle)
13498 (org-defkey org-mode-map [(tab)] 'org-cycle)
13499 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13500 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13501 (org-defkey org-mode-map "\M-\t" 'org-complete)
13502 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13503 ;; The following line is necessary under Suse GNU/Linux
13504 (unless (featurep 'xemacs)
13505 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13506 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13507 (define-key org-mode-map [backtab] 'org-shifttab)
13509 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13510 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13511 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13513 ;; Cursor keys with modifiers
13514 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13515 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13516 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13517 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13519 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13520 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13521 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13522 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13524 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13525 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13526 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13527 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13529 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13530 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13532 ;;; Extra keys for tty access.
13533 ;; We only set them when really needed because otherwise the
13534 ;; menus don't show the simple keys
13536 (when (or org-use-extra-keys
13537 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13538 (not window-system))
13539 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13540 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13541 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13542 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13543 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13544 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13545 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13546 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13547 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13548 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13549 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13550 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13551 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13552 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13553 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13554 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13555 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13556 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13557 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13558 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13559 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13560 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13562 ;; All the other keys
13564 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13565 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13566 (if (boundp 'narrow-map)
13567 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13568 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13569 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13570 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13571 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13572 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13573 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13574 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13575 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13576 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13577 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13578 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13579 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13580 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13581 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13582 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13583 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13584 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13585 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13586 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13587 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13588 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13589 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13590 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13591 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13592 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13593 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13594 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13595 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13596 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13597 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13598 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13599 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13600 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13601 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13602 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13603 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13604 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13605 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13606 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13607 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13608 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13609 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13610 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13611 (org-defkey org-mode-map "\C-c^" 'org-sort)
13612 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13613 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13614 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13615 (org-defkey org-mode-map "\C-m" 'org-return)
13616 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13617 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13618 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13619 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13620 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13621 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13622 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13623 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13624 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13625 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13626 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13627 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13628 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13629 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13630 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13631 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13632 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13634 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13635 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13636 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13637 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13639 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13640 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13641 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13642 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13643 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13644 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13645 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13646 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13647 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13648 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13649 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13650 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13651 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13653 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13654 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13655 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13656 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13658 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13660 (define-key org-mode-map "\C-c\C-xr" 'org-reload)
13662 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
13663 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
13665 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
13668 (when (featurep 'xemacs)
13669 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13672 (defvar org-self-insert-command-undo-counter 0)
13674 (defvar org-table-auto-blank-field) ; defined in org-table.el
13675 (defun org-self-insert-command (N)
13676 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13677 If the cursor is in a table looking at whitespace, the whitespace is
13678 overwritten, and the table is not marked as requiring realignment."
13679 (interactive "p")
13680 (if (and
13681 (org-table-p)
13682 (progn
13683 ;; check if we blank the field, and if that triggers align
13684 (and (featurep 'org-table) org-table-auto-blank-field
13685 (member last-command
13686 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13687 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13688 ;; got extra space, this field does not determine column width
13689 (let (org-table-may-need-update) (org-table-blank-field))
13690 ;; no extra space, this field may determine column width
13691 (org-table-blank-field)))
13693 (eq N 1)
13694 (looking-at "[^|\n]* |"))
13695 (let (org-table-may-need-update)
13696 (goto-char (1- (match-end 0)))
13697 (delete-backward-char 1)
13698 (goto-char (match-beginning 0))
13699 (self-insert-command N))
13700 (setq org-table-may-need-update t)
13701 (self-insert-command N)
13702 (org-fix-tags-on-the-fly)
13703 (if org-self-insert-cluster-for-undo
13704 (if (not (eq last-command 'org-self-insert-command))
13705 (setq org-self-insert-command-undo-counter 1)
13706 (if (>= org-self-insert-command-undo-counter 20)
13707 (setq org-self-insert-command-undo-counter 1)
13708 (and (> org-self-insert-command-undo-counter 0)
13709 buffer-undo-list
13710 (not (cadr buffer-undo-list)) ; remove nil entry
13711 (setcdr buffer-undo-list (cddr buffer-undo-list)))
13712 (setq org-self-insert-command-undo-counter
13713 (1+ org-self-insert-command-undo-counter)))))))
13715 (defun org-fix-tags-on-the-fly ()
13716 (when (and (equal (char-after (point-at-bol)) ?*)
13717 (org-on-heading-p))
13718 (org-align-tags-here org-tags-column)))
13720 (defun org-delete-backward-char (N)
13721 "Like `delete-backward-char', insert whitespace at field end in tables.
13722 When deleting backwards, in tables this function will insert whitespace in
13723 front of the next \"|\" separator, to keep the table aligned. The table will
13724 still be marked for re-alignment if the field did fill the entire column,
13725 because, in this case the deletion might narrow the column."
13726 (interactive "p")
13727 (if (and (org-table-p)
13728 (eq N 1)
13729 (string-match "|" (buffer-substring (point-at-bol) (point)))
13730 (looking-at ".*?|"))
13731 (let ((pos (point))
13732 (noalign (looking-at "[^|\n\r]* |"))
13733 (c org-table-may-need-update))
13734 (backward-delete-char N)
13735 (skip-chars-forward "^|")
13736 (insert " ")
13737 (goto-char (1- pos))
13738 ;; noalign: if there were two spaces at the end, this field
13739 ;; does not determine the width of the column.
13740 (if noalign (setq org-table-may-need-update c)))
13741 (backward-delete-char N)
13742 (org-fix-tags-on-the-fly)))
13744 (defun org-delete-char (N)
13745 "Like `delete-char', but insert whitespace at field end in tables.
13746 When deleting characters, in tables this function will insert whitespace in
13747 front of the next \"|\" separator, to keep the table aligned. The table will
13748 still be marked for re-alignment if the field did fill the entire column,
13749 because, in this case the deletion might narrow the column."
13750 (interactive "p")
13751 (if (and (org-table-p)
13752 (not (bolp))
13753 (not (= (char-after) ?|))
13754 (eq N 1))
13755 (if (looking-at ".*?|")
13756 (let ((pos (point))
13757 (noalign (looking-at "[^|\n\r]* |"))
13758 (c org-table-may-need-update))
13759 (replace-match (concat
13760 (substring (match-string 0) 1 -1)
13761 " |"))
13762 (goto-char pos)
13763 ;; noalign: if there were two spaces at the end, this field
13764 ;; does not determine the width of the column.
13765 (if noalign (setq org-table-may-need-update c)))
13766 (delete-char N))
13767 (delete-char N)
13768 (org-fix-tags-on-the-fly)))
13770 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13771 (put 'org-self-insert-command 'delete-selection t)
13772 (put 'orgtbl-self-insert-command 'delete-selection t)
13773 (put 'org-delete-char 'delete-selection 'supersede)
13774 (put 'org-delete-backward-char 'delete-selection 'supersede)
13775 (put 'org-yank 'delete-selection 'yank)
13777 ;; Make `flyspell-mode' delay after some commands
13778 (put 'org-self-insert-command 'flyspell-delayed t)
13779 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13780 (put 'org-delete-char 'flyspell-delayed t)
13781 (put 'org-delete-backward-char 'flyspell-delayed t)
13783 ;; Make pabbrev-mode expand after org-mode commands
13784 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13785 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13787 ;; How to do this: Measure non-white length of current string
13788 ;; If equal to column width, we should realign.
13790 (defun org-remap (map &rest commands)
13791 "In MAP, remap the functions given in COMMANDS.
13792 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13793 (let (new old)
13794 (while commands
13795 (setq old (pop commands) new (pop commands))
13796 (if (fboundp 'command-remapping)
13797 (org-defkey map (vector 'remap old) new)
13798 (substitute-key-definition old new map global-map)))))
13800 (when (eq org-enable-table-editor 'optimized)
13801 ;; If the user wants maximum table support, we need to hijack
13802 ;; some standard editing functions
13803 (org-remap org-mode-map
13804 'self-insert-command 'org-self-insert-command
13805 'delete-char 'org-delete-char
13806 'delete-backward-char 'org-delete-backward-char)
13807 (org-defkey org-mode-map "|" 'org-force-self-insert))
13809 (defvar org-ctrl-c-ctrl-c-hook nil
13810 "Hook for functions attaching themselves to `C-c C-c'.
13811 This can be used to add additional functionality to the C-c C-c key which
13812 executes context-dependent commands.
13813 Each function will be called with no arguments. The function must check
13814 if the context is appropriate for it to act. If yes, it should do its
13815 thing and then return a non-nil value. If the context is wrong,
13816 just do nothing.")
13818 (defvar org-metaleft-hook nil
13819 "Hook for functions attaching themselves to `M-left'.
13820 See `org-ctrl-c-ctrl-c-hook' for more information.")
13821 (defvar org-metaright-hook nil
13822 "Hook for functions attaching themselves to `M-right'.
13823 See `org-ctrl-c-ctrl-c-hook' for more information.")
13824 (defvar org-metaup-hook nil
13825 "Hook for functions attaching themselves to `M-up'.
13826 See `org-ctrl-c-ctrl-c-hook' for more information.")
13827 (defvar org-metadown-hook nil
13828 "Hook for functions attaching themselves to `M-down'.
13829 See `org-ctrl-c-ctrl-c-hook' for more information.")
13830 (defvar org-shiftmetaleft-hook nil
13831 "Hook for functions attaching themselves to `M-S-left'.
13832 See `org-ctrl-c-ctrl-c-hook' for more information.")
13833 (defvar org-shiftmetaright-hook nil
13834 "Hook for functions attaching themselves to `M-S-right'.
13835 See `org-ctrl-c-ctrl-c-hook' for more information.")
13836 (defvar org-shiftmetaup-hook nil
13837 "Hook for functions attaching themselves to `M-S-up'.
13838 See `org-ctrl-c-ctrl-c-hook' for more information.")
13839 (defvar org-shiftmetadown-hook nil
13840 "Hook for functions attaching themselves to `M-S-down'.
13841 See `org-ctrl-c-ctrl-c-hook' for more information.")
13842 (defvar org-metareturn-hook nil
13843 "Hook for functions attaching themselves to `M-RET'.
13844 See `org-ctrl-c-ctrl-c-hook' for more information.")
13846 (defun org-modifier-cursor-error ()
13847 "Throw an error, a modified cursor command was applied in wrong context."
13848 (error "This command is active in special context like tables, headlines or items"))
13850 (defun org-shiftselect-error ()
13851 "Throw an error because Shift-Cursor command was applied in wrong context."
13852 (if (and (boundp 'shift-select-mode) shift-select-mode)
13853 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13854 (error "This command works only in special context like headlines or timestamps.")))
13856 (defun org-call-for-shift-select (cmd)
13857 (let ((this-command-keys-shift-translated t))
13858 (call-interactively cmd)))
13860 (defun org-shifttab (&optional arg)
13861 "Global visibility cycling or move to previous table field.
13862 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13863 on context.
13864 See the individual commands for more information."
13865 (interactive "P")
13866 (cond
13867 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13868 ((integerp arg)
13869 (message "Content view to level: %d" arg)
13870 (org-content (prefix-numeric-value arg))
13871 (setq org-cycle-global-status 'overview))
13872 (t (call-interactively 'org-global-cycle))))
13874 (defun org-shiftmetaleft ()
13875 "Promote subtree or delete table column.
13876 Calls `org-promote-subtree', `org-outdent-item',
13877 or `org-table-delete-column', depending on context.
13878 See the individual commands for more information."
13879 (interactive)
13880 (cond
13881 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
13882 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13883 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13884 ((org-at-item-p) (call-interactively 'org-outdent-item))
13885 (t (org-modifier-cursor-error))))
13887 (defun org-shiftmetaright ()
13888 "Demote subtree or insert table column.
13889 Calls `org-demote-subtree', `org-indent-item',
13890 or `org-table-insert-column', depending on context.
13891 See the individual commands for more information."
13892 (interactive)
13893 (cond
13894 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
13895 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13896 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13897 ((org-at-item-p) (call-interactively 'org-indent-item))
13898 (t (org-modifier-cursor-error))))
13900 (defun org-shiftmetaup (&optional arg)
13901 "Move subtree up or kill table row.
13902 Calls `org-move-subtree-up' or `org-table-kill-row' or
13903 `org-move-item-up' depending on context. See the individual commands
13904 for more information."
13905 (interactive "P")
13906 (cond
13907 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
13908 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13909 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13910 ((org-at-item-p) (call-interactively 'org-move-item-up))
13911 (t (org-modifier-cursor-error))))
13913 (defun org-shiftmetadown (&optional arg)
13914 "Move subtree down or insert table row.
13915 Calls `org-move-subtree-down' or `org-table-insert-row' or
13916 `org-move-item-down', depending on context. See the individual
13917 commands for more information."
13918 (interactive "P")
13919 (cond
13920 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
13921 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13922 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13923 ((org-at-item-p) (call-interactively 'org-move-item-down))
13924 (t (org-modifier-cursor-error))))
13926 (defun org-metaleft (&optional arg)
13927 "Promote heading or move table column to left.
13928 Calls `org-do-promote' or `org-table-move-column', depending on context.
13929 With no specific context, calls the Emacs default `backward-word'.
13930 See the individual commands for more information."
13931 (interactive "P")
13932 (cond
13933 ((run-hook-with-args-until-success 'org-metaleft-hook))
13934 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13935 ((or (org-on-heading-p)
13936 (and (org-region-active-p)
13937 (save-excursion
13938 (goto-char (region-beginning))
13939 (org-on-heading-p))))
13940 (call-interactively 'org-do-promote))
13941 ((or (org-at-item-p)
13942 (and (org-region-active-p)
13943 (save-excursion
13944 (goto-char (region-beginning))
13945 (org-at-item-p))))
13946 (call-interactively 'org-outdent-item))
13947 (t (call-interactively 'backward-word))))
13949 (defun org-metaright (&optional arg)
13950 "Demote subtree or move table column to right.
13951 Calls `org-do-demote' or `org-table-move-column', depending on context.
13952 With no specific context, calls the Emacs default `forward-word'.
13953 See the individual commands for more information."
13954 (interactive "P")
13955 (cond
13956 ((run-hook-with-args-until-success 'org-metaright-hook))
13957 ((org-at-table-p) (call-interactively 'org-table-move-column))
13958 ((or (org-on-heading-p)
13959 (and (org-region-active-p)
13960 (save-excursion
13961 (goto-char (region-beginning))
13962 (org-on-heading-p))))
13963 (call-interactively 'org-do-demote))
13964 ((or (org-at-item-p)
13965 (and (org-region-active-p)
13966 (save-excursion
13967 (goto-char (region-beginning))
13968 (org-at-item-p))))
13969 (call-interactively 'org-indent-item))
13970 (t (call-interactively 'forward-word))))
13972 (defun org-metaup (&optional arg)
13973 "Move subtree up or move table row up.
13974 Calls `org-move-subtree-up' or `org-table-move-row' or
13975 `org-move-item-up', depending on context. See the individual commands
13976 for more information."
13977 (interactive "P")
13978 (cond
13979 ((run-hook-with-args-until-success 'org-metaup-hook))
13980 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13981 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13982 ((org-at-item-p) (call-interactively 'org-move-item-up))
13983 (t (transpose-lines 1) (beginning-of-line -1))))
13985 (defun org-metadown (&optional arg)
13986 "Move subtree down or move table row down.
13987 Calls `org-move-subtree-down' or `org-table-move-row' or
13988 `org-move-item-down', depending on context. See the individual
13989 commands for more information."
13990 (interactive "P")
13991 (cond
13992 ((run-hook-with-args-until-success 'org-metadown-hook))
13993 ((org-at-table-p) (call-interactively 'org-table-move-row))
13994 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13995 ((org-at-item-p) (call-interactively 'org-move-item-down))
13996 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13998 (defun org-shiftup (&optional arg)
13999 "Increase item in timestamp or increase priority of current headline.
14000 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14001 depending on context. See the individual commands for more information."
14002 (interactive "P")
14003 (cond
14004 ((and org-support-shift-select (org-region-active-p))
14005 (org-call-for-shift-select 'previous-line))
14006 ((org-at-timestamp-p t)
14007 (call-interactively (if org-edit-timestamp-down-means-later
14008 'org-timestamp-down 'org-timestamp-up)))
14009 ((and (not (eq org-support-shift-select 'always))
14010 (org-on-heading-p))
14011 (call-interactively 'org-priority-up))
14012 ((and (not org-support-shift-select) (org-at-item-p))
14013 (call-interactively 'org-previous-item))
14014 ((org-clocktable-try-shift 'up arg))
14015 (org-support-shift-select
14016 (org-call-for-shift-select 'previous-line))
14017 (t (org-shiftselect-error))))
14019 (defun org-shiftdown (&optional arg)
14020 "Decrease item in timestamp or decrease priority of current headline.
14021 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14022 depending on context. See the individual commands for more information."
14023 (interactive "P")
14024 (cond
14025 ((and org-support-shift-select (org-region-active-p))
14026 (org-call-for-shift-select 'next-line))
14027 ((org-at-timestamp-p t)
14028 (call-interactively (if org-edit-timestamp-down-means-later
14029 'org-timestamp-up 'org-timestamp-down)))
14030 ((and (not (eq org-support-shift-select 'always))
14031 (org-on-heading-p))
14032 (call-interactively 'org-priority-down))
14033 ((and (not org-support-shift-select) (org-at-item-p))
14034 (call-interactively 'org-next-item))
14035 ((org-clocktable-try-shift 'down arg))
14036 (org-support-shift-select
14037 (org-call-for-shift-select 'next-line))
14038 (t (org-shiftselect-error))))
14040 (defun org-shiftright (&optional arg)
14041 "Cycle the thing at point or in the current line, depending on context.
14042 Depending on context, this does one of the following:
14044 - switch a timestamp at point one day into the future
14045 - on a headline, switch to the next TODO keyword.
14046 - on an item, switch entire list to the next bullet type
14047 - on a property line, switch to the next allowed value
14048 - on a clocktable definition line, move time block into the future"
14049 (interactive "P")
14050 (cond
14051 ((and org-support-shift-select (org-region-active-p))
14052 (org-call-for-shift-select 'forward-char))
14053 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14054 ((and (not (eq org-support-shift-select 'always))
14055 (org-on-heading-p))
14056 (org-call-with-arg 'org-todo 'right))
14057 ((or (and org-support-shift-select
14058 (not (eq org-support-shift-select 'always))
14059 (org-at-item-bullet-p))
14060 (and (not org-support-shift-select) (org-at-item-p)))
14061 (org-call-with-arg 'org-cycle-list-bullet nil))
14062 ((and (not (eq org-support-shift-select 'always))
14063 (org-at-property-p))
14064 (call-interactively 'org-property-next-allowed-value))
14065 ((org-clocktable-try-shift 'right arg))
14066 (org-support-shift-select
14067 (org-call-for-shift-select 'forward-char))
14068 (t (org-shiftselect-error))))
14070 (defun org-shiftleft (&optional arg)
14071 "Cycle the thing at point or in the current line, depending on context.
14072 Depending on context, this does one of the following:
14074 - switch a timestamp at point one day into the past
14075 - on a headline, switch to the previous TODO keyword.
14076 - on an item, switch entire list to the previous bullet type
14077 - on a property line, switch to the previous allowed value
14078 - on a clocktable definition line, move time block into the past"
14079 (interactive "P")
14080 (cond
14081 ((and org-support-shift-select (org-region-active-p))
14082 (org-call-for-shift-select 'backward-char))
14083 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14084 ((and (not (eq org-support-shift-select 'always))
14085 (org-on-heading-p))
14086 (org-call-with-arg 'org-todo 'left))
14087 ((or (and org-support-shift-select
14088 (not (eq org-support-shift-select 'always))
14089 (org-at-item-bullet-p))
14090 (and (not org-support-shift-select) (org-at-item-p)))
14091 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14092 ((and (not (eq org-support-shift-select 'always))
14093 (org-at-property-p))
14094 (call-interactively 'org-property-previous-allowed-value))
14095 ((org-clocktable-try-shift 'left arg))
14096 (org-support-shift-select
14097 (org-call-for-shift-select 'backward-char))
14098 (t (org-shiftselect-error))))
14100 (defun org-shiftcontrolright ()
14101 "Switch to next TODO set."
14102 (interactive)
14103 (cond
14104 ((and org-support-shift-select (org-region-active-p))
14105 (org-call-for-shift-select 'forward-word))
14106 ((and (not (eq org-support-shift-select 'always))
14107 (org-on-heading-p))
14108 (org-call-with-arg 'org-todo 'nextset))
14109 (org-support-shift-select
14110 (org-call-for-shift-select 'forward-word))
14111 (t (org-shiftselect-error))))
14113 (defun org-shiftcontrolleft ()
14114 "Switch to previous TODO set."
14115 (interactive)
14116 (cond
14117 ((and org-support-shift-select (org-region-active-p))
14118 (org-call-for-shift-select 'backward-word))
14119 ((and (not (eq org-support-shift-select 'always))
14120 (org-on-heading-p))
14121 (org-call-with-arg 'org-todo 'previousset))
14122 (org-support-shift-select
14123 (org-call-for-shift-select 'backward-word))
14124 (t (org-shiftselect-error))))
14126 (defun org-ctrl-c-ret ()
14127 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14128 (interactive)
14129 (cond
14130 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14131 (t (call-interactively 'org-insert-heading))))
14133 (defun org-copy-special ()
14134 "Copy region in table or copy current subtree.
14135 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14136 See the individual commands for more information."
14137 (interactive)
14138 (call-interactively
14139 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14141 (defun org-cut-special ()
14142 "Cut region in table or cut current subtree.
14143 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14144 See the individual commands for more information."
14145 (interactive)
14146 (call-interactively
14147 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14149 (defun org-paste-special (arg)
14150 "Paste rectangular region into table, or past subtree relative to level.
14151 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14152 See the individual commands for more information."
14153 (interactive "P")
14154 (if (org-at-table-p)
14155 (org-table-paste-rectangle)
14156 (org-paste-subtree arg)))
14158 (defun org-edit-special ()
14159 "Call a special editor for the stuff at point.
14160 When at a table, call the formula editor with `org-table-edit-formulas'.
14161 When at the first line of an src example, call `org-edit-src-code'.
14162 When in an #+include line, visit the include file. Otherwise call
14163 `ffap' to visit the file at point."
14164 (interactive)
14165 (cond
14166 ((org-at-table-p)
14167 (call-interactively 'org-table-edit-formulas))
14168 ((save-excursion
14169 (beginning-of-line 1)
14170 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14171 (find-file (org-trim (match-string 1))))
14172 ((org-edit-src-code))
14173 ((org-edit-fixed-width-region))
14174 (t (call-interactively 'ffap))))
14177 (defun org-ctrl-c-ctrl-c (&optional arg)
14178 "Set tags in headline, or update according to changed information at point.
14180 This command does many different things, depending on context:
14182 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14183 this is what we do.
14185 - If the cursor is in a headline, prompt for tags and insert them
14186 into the current line, aligned to `org-tags-column'. When called
14187 with prefix arg, realign all tags in the current buffer.
14189 - If the cursor is in one of the special #+KEYWORD lines, this
14190 triggers scanning the buffer for these lines and updating the
14191 information.
14193 - If the cursor is inside a table, realign the table. This command
14194 works even if the automatic table editor has been turned off.
14196 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14197 the entire table.
14199 - If the cursor is at a footnote reference or definition, jump to
14200 the corresponding definition or references, respectively.
14202 - If the cursor is a the beginning of a dynamic block, update it.
14204 - If the cursor is inside a table created by the table.el package,
14205 activate that table.
14207 - If the current buffer is a remember buffer, close note and file
14208 it. A prefix argument of 1 files to the default location
14209 without further interaction. A prefix argument of 2 files to
14210 the currently clocking task.
14212 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14213 links in this buffer.
14215 - If the cursor is on a numbered item in a plain list, renumber the
14216 ordered list.
14218 - If the cursor is on a checkbox, toggle it."
14219 (interactive "P")
14220 (let ((org-enable-table-editor t))
14221 (cond
14222 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14223 org-occur-highlights
14224 org-latex-fragment-image-overlays)
14225 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14226 (org-remove-occur-highlights)
14227 (org-remove-latex-fragment-image-overlays)
14228 (message "Temporary highlights/overlays removed from current buffer"))
14229 ((and (local-variable-p 'org-finish-function (current-buffer))
14230 (fboundp org-finish-function))
14231 (funcall org-finish-function))
14232 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14233 ((org-at-property-p)
14234 (call-interactively 'org-property-action))
14235 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14236 ((org-on-heading-p) (call-interactively 'org-set-tags))
14237 ((org-at-table.el-p)
14238 (require 'table)
14239 (beginning-of-line 1)
14240 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14241 (call-interactively 'table-recognize-table))
14242 ((org-at-table-p)
14243 (org-table-maybe-eval-formula)
14244 (if arg
14245 (call-interactively 'org-table-recalculate)
14246 (org-table-maybe-recalculate-line))
14247 (call-interactively 'org-table-align))
14248 ((or (org-footnote-at-reference-p)
14249 (org-footnote-at-definition-p))
14250 (call-interactively 'org-footnote-action))
14251 ((org-at-item-checkbox-p)
14252 (call-interactively 'org-toggle-checkbox))
14253 ((org-at-item-p)
14254 (if arg
14255 (call-interactively 'org-toggle-checkbox)
14256 (call-interactively 'org-maybe-renumber-ordered-list)))
14257 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14258 ;; Dynamic block
14259 (beginning-of-line 1)
14260 (save-excursion (org-update-dblock)))
14261 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14262 (cond
14263 ((equal (match-string 1) "TBLFM")
14264 ;; Recalculate the table before this line
14265 (save-excursion
14266 (beginning-of-line 1)
14267 (skip-chars-backward " \r\n\t")
14268 (if (org-at-table-p)
14269 (org-call-with-arg 'org-table-recalculate t))))
14271 ; (org-set-regexps-and-options)
14272 ; (org-restart-font-lock)
14273 (let ((org-inhibit-startup t)) (org-mode-restart))
14274 (message "Local setup has been refreshed"))))
14275 (t (error "C-c C-c can do nothing useful at this location.")))))
14277 (defun org-mode-restart ()
14278 "Restart Org-mode, to scan again for special lines.
14279 Also updates the keyword regular expressions."
14280 (interactive)
14281 (org-mode)
14282 (message "Org-mode restarted"))
14284 (defun org-kill-note-or-show-branches ()
14285 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14286 (interactive)
14287 (if (not org-finish-function)
14288 (call-interactively 'show-branches)
14289 (let ((org-note-abort t))
14290 (funcall org-finish-function))))
14292 (defun org-return (&optional indent)
14293 "Goto next table row or insert a newline.
14294 Calls `org-table-next-row' or `newline', depending on context.
14295 See the individual commands for more information."
14296 (interactive)
14297 (cond
14298 ((bobp) (if indent (newline-and-indent) (newline)))
14299 ((org-at-table-p)
14300 (org-table-justify-field-maybe)
14301 (call-interactively 'org-table-next-row))
14302 ((and org-return-follows-link
14303 (eq (get-text-property (point) 'face) 'org-link))
14304 (call-interactively 'org-open-at-point))
14305 ((and (org-at-heading-p)
14306 (looking-at
14307 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14308 (org-show-entry)
14309 (end-of-line 1)
14310 (newline))
14311 (t (if indent (newline-and-indent) (newline)))))
14313 (defun org-return-indent ()
14314 "Goto next table row or insert a newline and indent.
14315 Calls `org-table-next-row' or `newline-and-indent', depending on
14316 context. See the individual commands for more information."
14317 (interactive)
14318 (org-return t))
14320 (defun org-ctrl-c-star ()
14321 "Compute table, or change heading status of lines.
14322 Calls `org-table-recalculate' or `org-toggle-heading',
14323 depending on context."
14324 (interactive)
14325 (cond
14326 ((org-at-table-p)
14327 (call-interactively 'org-table-recalculate))
14329 ;; Convert all lines in region to list items
14330 (call-interactively 'org-toggle-heading))))
14332 (defun org-ctrl-c-minus ()
14333 "Insert separator line in table or modify bullet status of line.
14334 Also turns a plain line or a region of lines into list items.
14335 Calls `org-table-insert-hline', `org-toggle-item', or
14336 `org-cycle-list-bullet', depending on context."
14337 (interactive)
14338 (cond
14339 ((org-at-table-p)
14340 (call-interactively 'org-table-insert-hline))
14341 ((org-region-active-p)
14342 (call-interactively 'org-toggle-item))
14343 ((org-in-item-p)
14344 (call-interactively 'org-cycle-list-bullet))
14346 (call-interactively 'org-toggle-item))))
14348 (defun org-toggle-item ()
14349 "Convert headings or normal lines to items, items to normal lines.
14350 If there is no active region, only the current line is considered.
14352 If the first line in the region is a headline, convert all headlines to items.
14354 If the first line in the region is an item, convert all items to normal lines.
14356 If the first line is normal text, add an item bullet to each line."
14357 (interactive)
14358 (let (l2 l beg end)
14359 (if (org-region-active-p)
14360 (setq beg (region-beginning) end (region-end))
14361 (setq beg (point-at-bol)
14362 end (min (1+ (point-at-eol)) (point-max))))
14363 (save-excursion
14364 (goto-char end)
14365 (setq l2 (org-current-line))
14366 (goto-char beg)
14367 (beginning-of-line 1)
14368 (setq l (1- (org-current-line)))
14369 (if (org-at-item-p)
14370 ;; We already have items, de-itemize
14371 (while (< (setq l (1+ l)) l2)
14372 (when (org-at-item-p)
14373 (goto-char (match-beginning 2))
14374 (delete-region (match-beginning 2) (match-end 2))
14375 (and (looking-at "[ \t]+") (replace-match "")))
14376 (beginning-of-line 2))
14377 (if (org-on-heading-p)
14378 ;; Headings, convert to items
14379 (while (< (setq l (1+ l)) l2)
14380 (if (looking-at org-outline-regexp)
14381 (replace-match "- " t t))
14382 (beginning-of-line 2))
14383 ;; normal lines, turn them into items
14384 (while (< (setq l (1+ l)) l2)
14385 (unless (org-at-item-p)
14386 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14387 (replace-match "\\1- \\2")))
14388 (beginning-of-line 2)))))))
14390 (defun org-toggle-heading (&optional nstars)
14391 "Convert headings to normal text, or items or text to headings.
14392 If there is no active region, only the current line is considered.
14394 If the first line is a heading, remove the stars from all headlines
14395 in the region.
14397 If the first line is a plain list item, turn all plain list items into
14398 headings.
14400 If the first line is a normal line, turn each and every line in the region
14401 into a heading.
14403 When converting a line into a heading, the number of stars is chosen
14404 such that the lines become children of the current entry. However, when
14405 a prefix argument is given, its value determines the number of stars to add."
14406 (interactive "P")
14407 (let (l2 l itemp beg end)
14408 (if (org-region-active-p)
14409 (setq beg (region-beginning) end (region-end))
14410 (setq beg (point-at-bol)
14411 end (min (1+ (point-at-eol)) (point-max))))
14412 (save-excursion
14413 (goto-char end)
14414 (setq l2 (org-current-line))
14415 (goto-char beg)
14416 (beginning-of-line 1)
14417 (setq l (1- (org-current-line)))
14418 (if (org-on-heading-p)
14419 ;; We already have headlines, de-star them
14420 (while (< (setq l (1+ l)) l2)
14421 (when (org-on-heading-p t)
14422 (and (looking-at outline-regexp) (replace-match "")))
14423 (beginning-of-line 2))
14424 (setq itemp (org-at-item-p))
14425 (let* ((stars
14426 (if nstars
14427 (make-string (prefix-numeric-value current-prefix-arg)
14429 (save-excursion
14430 (re-search-backward org-complex-heading-regexp nil t)
14431 (or (match-string 1) ""))))
14432 (add-stars (cond (nstars "")
14433 ((equal stars "") "*")
14434 (org-odd-levels-only "**")
14435 (t "*")))
14436 (rpl (concat stars add-stars " ")))
14437 (while (< (setq l (1+ l)) l2)
14438 (if itemp
14439 (and (org-at-item-p) (replace-match rpl t t))
14440 (unless (org-on-heading-p)
14441 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14442 (replace-match (concat rpl (match-string 2))))))
14443 (beginning-of-line 2)))))))
14445 (defun org-meta-return (&optional arg)
14446 "Insert a new heading or wrap a region in a table.
14447 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14448 See the individual commands for more information."
14449 (interactive "P")
14450 (cond
14451 ((run-hook-with-args-until-success 'org-metareturn-hook))
14452 ((org-at-table-p)
14453 (call-interactively 'org-table-wrap-region))
14454 (t (call-interactively 'org-insert-heading))))
14456 ;;; Menu entries
14458 ;; Define the Org-mode menus
14459 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14460 '("Tbl"
14461 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14462 ["Next Field" org-cycle (org-at-table-p)]
14463 ["Previous Field" org-shifttab (org-at-table-p)]
14464 ["Next Row" org-return (org-at-table-p)]
14465 "--"
14466 ["Blank Field" org-table-blank-field (org-at-table-p)]
14467 ["Edit Field" org-table-edit-field (org-at-table-p)]
14468 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14469 "--"
14470 ("Column"
14471 ["Move Column Left" org-metaleft (org-at-table-p)]
14472 ["Move Column Right" org-metaright (org-at-table-p)]
14473 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14474 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14475 ("Row"
14476 ["Move Row Up" org-metaup (org-at-table-p)]
14477 ["Move Row Down" org-metadown (org-at-table-p)]
14478 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14479 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14480 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14481 "--"
14482 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14483 ("Rectangle"
14484 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14485 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14486 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14487 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14488 "--"
14489 ("Calculate"
14490 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14491 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14492 ["Edit Formulas" org-edit-special (org-at-table-p)]
14493 "--"
14494 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14495 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14496 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14497 "--"
14498 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14499 "--"
14500 ["Sum Column/Rectangle" org-table-sum
14501 (or (org-at-table-p) (org-region-active-p))]
14502 ["Which Column?" org-table-current-column (org-at-table-p)])
14503 ["Debug Formulas"
14504 org-table-toggle-formula-debugger
14505 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14506 ["Show Col/Row Numbers"
14507 org-table-toggle-coordinate-overlays
14508 :style toggle
14509 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14510 "--"
14511 ["Create" org-table-create (and (not (org-at-table-p))
14512 org-enable-table-editor)]
14513 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14514 ["Import from File" org-table-import (not (org-at-table-p))]
14515 ["Export to File" org-table-export (org-at-table-p)]
14516 "--"
14517 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14519 (easy-menu-define org-org-menu org-mode-map "Org menu"
14520 '("Org"
14521 ("Show/Hide"
14522 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14523 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14524 ["Sparse Tree..." org-sparse-tree t]
14525 ["Reveal Context" org-reveal t]
14526 ["Show All" show-all t]
14527 "--"
14528 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14529 "--"
14530 ["New Heading" org-insert-heading t]
14531 ("Navigate Headings"
14532 ["Up" outline-up-heading t]
14533 ["Next" outline-next-visible-heading t]
14534 ["Previous" outline-previous-visible-heading t]
14535 ["Next Same Level" outline-forward-same-level t]
14536 ["Previous Same Level" outline-backward-same-level t]
14537 "--"
14538 ["Jump" org-goto t])
14539 ("Edit Structure"
14540 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14541 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14542 "--"
14543 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14544 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14545 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14546 "--"
14547 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14548 "--"
14549 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14550 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14551 ["Demote Heading" org-metaright (not (org-at-table-p))]
14552 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14553 "--"
14554 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14555 "--"
14556 ["Convert to odd levels" org-convert-to-odd-levels t]
14557 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14558 ("Editing"
14559 ["Emphasis..." org-emphasize t]
14560 ["Edit Source Example" org-edit-special t]
14561 "--"
14562 ["Footnote new/jump" org-footnote-action t]
14563 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14564 ("Archive"
14565 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14566 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14567 ; :active t :keys "C-u C-c C-x C-a"]
14568 ["Sparse trees open ARCHIVE trees"
14569 (setq org-sparse-tree-open-archived-trees
14570 (not org-sparse-tree-open-archived-trees))
14571 :style toggle :selected org-sparse-tree-open-archived-trees]
14572 ["Cycling opens ARCHIVE trees"
14573 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14574 :style toggle :selected org-cycle-open-archived-trees]
14575 "--"
14576 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14577 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14578 ; ["Check and Move Children" (org-archive-subtree '(4))
14579 ; :active t :keys "C-u C-c C-x C-s"]
14581 "--"
14582 ("Hyperlinks"
14583 ["Store Link (Global)" org-store-link t]
14584 ["Insert Link" org-insert-link t]
14585 ["Follow Link" org-open-at-point t]
14586 "--"
14587 ["Next link" org-next-link t]
14588 ["Previous link" org-previous-link t]
14589 "--"
14590 ["Descriptive Links"
14591 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14592 :style radio
14593 :selected (member '(org-link) buffer-invisibility-spec)]
14594 ["Literal Links"
14595 (progn
14596 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14597 :style radio
14598 :selected (not (member '(org-link) buffer-invisibility-spec))])
14599 "--"
14600 ("TODO Lists"
14601 ["TODO/DONE/-" org-todo t]
14602 ("Select keyword"
14603 ["Next keyword" org-shiftright (org-on-heading-p)]
14604 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14605 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14606 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14607 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14608 ["Show TODO Tree" org-show-todo-tree t]
14609 ["Global TODO list" org-todo-list t]
14610 "--"
14611 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14612 :selected org-enforce-todo-dependencies :style toggle :active t]
14613 "Settings for tree at point"
14614 ["Do Children sequentially" org-toggle-ordered-property :style radio
14615 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14616 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14617 ["Do Children parallel" org-toggle-ordered-property :style radio
14618 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14619 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14620 "--"
14621 ["Set Priority" org-priority t]
14622 ["Priority Up" org-shiftup t]
14623 ["Priority Down" org-shiftdown t]
14624 "--"
14625 ["Get news from all feeds" org-feed-update-all t]
14626 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
14627 ["Customize feeds" (customize-variable 'org-feed-alist) t])
14628 ("TAGS and Properties"
14629 ["Set Tags" org-set-tags-command t]
14630 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14631 "--"
14632 ["Set property" org-set-property t]
14633 ["Column view of properties" org-columns t]
14634 ["Insert Column View DBlock" org-insert-columns-dblock t])
14635 ("Dates and Scheduling"
14636 ["Timestamp" org-time-stamp t]
14637 ["Timestamp (inactive)" org-time-stamp-inactive t]
14638 ("Change Date"
14639 ["1 Day Later" org-shiftright t]
14640 ["1 Day Earlier" org-shiftleft t]
14641 ["1 ... Later" org-shiftup t]
14642 ["1 ... Earlier" org-shiftdown t])
14643 ["Compute Time Range" org-evaluate-time-range t]
14644 ["Schedule Item" org-schedule t]
14645 ["Deadline" org-deadline t]
14646 "--"
14647 ["Custom time format" org-toggle-time-stamp-overlays
14648 :style radio :selected org-display-custom-times]
14649 "--"
14650 ["Goto Calendar" org-goto-calendar t]
14651 ["Date from Calendar" org-date-from-calendar t]
14652 "--"
14653 ["Start/Restart Timer" org-timer-start t]
14654 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14655 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14656 ["Insert Timer String" org-timer t]
14657 ["Insert Timer Item" org-timer-item t])
14658 ("Logging work"
14659 ["Clock in" org-clock-in t]
14660 ["Clock out" org-clock-out t]
14661 ["Clock cancel" org-clock-cancel t]
14662 ["Goto running clock" org-clock-goto t]
14663 ["Display times" org-clock-display t]
14664 ["Create clock table" org-clock-report t]
14665 "--"
14666 ["Record DONE time"
14667 (progn (setq org-log-done (not org-log-done))
14668 (message "Switching to %s will %s record a timestamp"
14669 (car org-done-keywords)
14670 (if org-log-done "automatically" "not")))
14671 :style toggle :selected org-log-done])
14672 "--"
14673 ["Agenda Command..." org-agenda t]
14674 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14675 ("File List for Agenda")
14676 ("Special views current file"
14677 ["TODO Tree" org-show-todo-tree t]
14678 ["Check Deadlines" org-check-deadlines t]
14679 ["Timeline" org-timeline t]
14680 ["Tags/Property tree" org-match-sparse-tree t])
14681 "--"
14682 ["Export/Publish..." org-export t]
14683 ("LaTeX"
14684 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14685 :selected org-cdlatex-mode]
14686 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14687 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14688 ["Modify math symbol" org-cdlatex-math-modify
14689 (org-inside-LaTeX-fragment-p)]
14690 ["Insert citation" org-reftex-citation t]
14691 "--"
14692 ["Export LaTeX fragments as images"
14693 (if (featurep 'org-exp)
14694 (setq org-export-with-LaTeX-fragments
14695 (not org-export-with-LaTeX-fragments))
14696 (require 'org-exp))
14697 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14698 org-export-with-LaTeX-fragments)])
14699 "--"
14700 ("Documentation"
14701 ["Show Version" org-version t]
14702 ["Info Documentation" org-info t])
14703 ("Customize"
14704 ["Browse Org Group" org-customize t]
14705 "--"
14706 ["Expand This Menu" org-create-customize-menu
14707 (fboundp 'customize-menu-create)])
14708 "--"
14709 ("Refresh/Reload"
14710 ["Refresh setup current buffer" org-mode-restart t]
14711 ["Reload Org (after update)" org-reload t]
14712 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
14715 (defun org-info (&optional node)
14716 "Read documentation for Org-mode in the info system.
14717 With optional NODE, go directly to that node."
14718 (interactive)
14719 (info (format "(org)%s" (or node ""))))
14721 (defun org-install-agenda-files-menu ()
14722 (let ((bl (buffer-list)))
14723 (save-excursion
14724 (while bl
14725 (set-buffer (pop bl))
14726 (if (org-mode-p) (setq bl nil)))
14727 (when (org-mode-p)
14728 (easy-menu-change
14729 '("Org") "File List for Agenda"
14730 (append
14731 (list
14732 ["Edit File List" (org-edit-agenda-file-list) t]
14733 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14734 ["Remove Current File from List" org-remove-file t]
14735 ["Cycle through agenda files" org-cycle-agenda-files t]
14736 ["Occur in all agenda files" org-occur-in-agenda-files t]
14737 "--")
14738 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14740 ;;;; Documentation
14742 ;;;###autoload
14743 (defun org-require-autoloaded-modules ()
14744 (interactive)
14745 (mapc 'require
14746 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
14747 org-docbook org-exp org-html org-icalendar
14748 org-id org-latex
14749 org-publish org-remember org-table
14750 org-timer org-xoxo)))
14752 ;;;###autoload
14753 (defun org-reload (&optional uncompiled)
14754 "Reload all org lisp files.
14755 With prefix arg UNCOMPILED, load the uncompiled versions."
14756 (interactive "P")
14757 (require 'find-func)
14758 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
14759 (dir-org (file-name-directory (org-find-library-name "org")))
14760 (dir-org-contrib (ignore-errors
14761 (file-name-directory
14762 (org-find-library-name "org-contribdir"))))
14763 (files
14764 (append (directory-files dir-org t file-re)
14765 (and dir-org-contrib
14766 (directory-files dir-org-contrib t file-re))))
14767 (remove-re (concat (if (featurep 'xemacs)
14768 "org-colview" "org-colview-xemacs")
14769 "\\'")))
14770 (setq files (mapcar 'file-name-sans-extension files))
14771 (setq files (mapcar
14772 (lambda (x) (if (string-match remove-re x) nil x))
14773 files))
14774 (setq files (delq nil files))
14775 (mapc
14776 (lambda (f)
14777 (when (featurep (intern (file-name-nondirectory f)))
14778 (if (and (not uncompiled)
14779 (file-exists-p (concat f ".elc")))
14780 (load (concat f ".elc") nil nil t)
14781 (load (concat f ".el") nil nil t))))
14782 files))
14783 (org-version))
14785 ;;;###autoload
14786 (defun org-customize ()
14787 "Call the customize function with org as argument."
14788 (interactive)
14789 (org-load-modules-maybe)
14790 (org-require-autoloaded-modules)
14791 (customize-browse 'org))
14793 (defun org-create-customize-menu ()
14794 "Create a full customization menu for Org-mode, insert it into the menu."
14795 (interactive)
14796 (org-load-modules-maybe)
14797 (org-require-autoloaded-modules)
14798 (if (fboundp 'customize-menu-create)
14799 (progn
14800 (easy-menu-change
14801 '("Org") "Customize"
14802 `(["Browse Org group" org-customize t]
14803 "--"
14804 ,(customize-menu-create 'org)
14805 ["Set" Custom-set t]
14806 ["Save" Custom-save t]
14807 ["Reset to Current" Custom-reset-current t]
14808 ["Reset to Saved" Custom-reset-saved t]
14809 ["Reset to Standard Settings" Custom-reset-standard t]))
14810 (message "\"Org\"-menu now contains full customization menu"))
14811 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14813 ;;;; Miscellaneous stuff
14815 ;;; Generally useful functions
14817 (defun org-find-text-property-in-string (prop s)
14818 "Return the first non-nil value of property PROP in string S."
14819 (or (get-text-property 0 prop s)
14820 (get-text-property (or (next-single-property-change 0 prop s) 0)
14821 prop s)))
14823 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14824 "Display the given MESSAGE as a warning."
14825 (if (fboundp 'display-warning)
14826 (display-warning 'org message
14827 (if (featurep 'xemacs)
14828 'warning
14829 :warning))
14830 (let ((buf (get-buffer-create "*Org warnings*")))
14831 (with-current-buffer buf
14832 (goto-char (point-max))
14833 (insert "Warning (Org): " message)
14834 (unless (bolp)
14835 (newline)))
14836 (display-buffer buf)
14837 (sit-for 0))))
14839 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14840 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14841 (if (and marker (marker-buffer marker)
14842 (buffer-live-p (marker-buffer marker)))
14843 (progn
14844 (switch-to-buffer (marker-buffer marker))
14845 (if (or (> marker (point-max)) (< marker (point-min)))
14846 (widen))
14847 (goto-char marker)
14848 (org-show-context 'org-goto))
14849 (if bookmark
14850 (bookmark-jump bookmark)
14851 (error "Cannot find location"))))
14853 (defun org-quote-csv-field (s)
14854 "Quote field for inclusion in CSV material."
14855 (if (string-match "[\",]" s)
14856 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14859 (defun org-plist-delete (plist property)
14860 "Delete PROPERTY from PLIST.
14861 This is in contrast to merely setting it to 0."
14862 (let (p)
14863 (while plist
14864 (if (not (eq property (car plist)))
14865 (setq p (plist-put p (car plist) (nth 1 plist))))
14866 (setq plist (cddr plist)))
14869 (defun org-force-self-insert (N)
14870 "Needed to enforce self-insert under remapping."
14871 (interactive "p")
14872 (self-insert-command N))
14874 (defun org-string-width (s)
14875 "Compute width of string, ignoring invisible characters.
14876 This ignores character with invisibility property `org-link', and also
14877 characters with property `org-cwidth', because these will become invisible
14878 upon the next fontification round."
14879 (let (b l)
14880 (when (or (eq t buffer-invisibility-spec)
14881 (assq 'org-link buffer-invisibility-spec))
14882 (while (setq b (text-property-any 0 (length s)
14883 'invisible 'org-link s))
14884 (setq s (concat (substring s 0 b)
14885 (substring s (or (next-single-property-change
14886 b 'invisible s) (length s)))))))
14887 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14888 (setq s (concat (substring s 0 b)
14889 (substring s (or (next-single-property-change
14890 b 'org-cwidth s) (length s))))))
14891 (setq l (string-width s) b -1)
14892 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14893 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14896 (defun org-get-indentation (&optional line)
14897 "Get the indentation of the current line, interpreting tabs.
14898 When LINE is given, assume it represents a line and compute its indentation."
14899 (if line
14900 (if (string-match "^ *" (org-remove-tabs line))
14901 (match-end 0))
14902 (save-excursion
14903 (beginning-of-line 1)
14904 (skip-chars-forward " \t")
14905 (current-column))))
14907 (defun org-remove-tabs (s &optional width)
14908 "Replace tabulators in S with spaces.
14909 Assumes that s is a single line, starting in column 0."
14910 (setq width (or width tab-width))
14911 (while (string-match "\t" s)
14912 (setq s (replace-match
14913 (make-string
14914 (- (* width (/ (+ (match-beginning 0) width) width))
14915 (match-beginning 0)) ?\ )
14916 t t s)))
14919 (defun org-fix-indentation (line ind)
14920 "Fix indentation in LINE.
14921 IND is a cons cell with target and minimum indentation.
14922 If the current indentation in LINE is smaller than the minimum,
14923 leave it alone. If it is larger than ind, set it to the target."
14924 (let* ((l (org-remove-tabs line))
14925 (i (org-get-indentation l))
14926 (i1 (car ind)) (i2 (cdr ind)))
14927 (if (>= i i2) (setq l (substring line i2)))
14928 (if (> i1 0)
14929 (concat (make-string i1 ?\ ) l)
14930 l)))
14932 (defun org-base-buffer (buffer)
14933 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14934 (if (not buffer)
14935 buffer
14936 (or (buffer-base-buffer buffer)
14937 buffer)))
14939 (defun org-trim (s)
14940 "Remove whitespace at beginning and end of string."
14941 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14942 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14945 (defun org-wrap (string &optional width lines)
14946 "Wrap string to either a number of lines, or a width in characters.
14947 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14948 that costs. If there is a word longer than WIDTH, the text is actually
14949 wrapped to the length of that word.
14950 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14951 many lines, whatever width that takes.
14952 The return value is a list of lines, without newlines at the end."
14953 (let* ((words (org-split-string string "[ \t\n]+"))
14954 (maxword (apply 'max (mapcar 'org-string-width words)))
14955 w ll)
14956 (cond (width
14957 (org-do-wrap words (max maxword width)))
14958 (lines
14959 (setq w maxword)
14960 (setq ll (org-do-wrap words maxword))
14961 (if (<= (length ll) lines)
14963 (setq ll words)
14964 (while (> (length ll) lines)
14965 (setq w (1+ w))
14966 (setq ll (org-do-wrap words w)))
14967 ll))
14968 (t (error "Cannot wrap this")))))
14970 (defun org-do-wrap (words width)
14971 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14972 (let (lines line)
14973 (while words
14974 (setq line (pop words))
14975 (while (and words (< (+ (length line) (length (car words))) width))
14976 (setq line (concat line " " (pop words))))
14977 (setq lines (push line lines)))
14978 (nreverse lines)))
14980 (defun org-split-string (string &optional separators)
14981 "Splits STRING into substrings at SEPARATORS.
14982 No empty strings are returned if there are matches at the beginning
14983 and end of string."
14984 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14985 (start 0)
14986 notfirst
14987 (list nil))
14988 (while (and (string-match rexp string
14989 (if (and notfirst
14990 (= start (match-beginning 0))
14991 (< start (length string)))
14992 (1+ start) start))
14993 (< (match-beginning 0) (length string)))
14994 (setq notfirst t)
14995 (or (eq (match-beginning 0) 0)
14996 (and (eq (match-beginning 0) (match-end 0))
14997 (eq (match-beginning 0) start))
14998 (setq list
14999 (cons (substring string start (match-beginning 0))
15000 list)))
15001 (setq start (match-end 0)))
15002 (or (eq start (length string))
15003 (setq list
15004 (cons (substring string start)
15005 list)))
15006 (nreverse list)))
15008 (defun org-uuidgen-p (s)
15009 "Is S an ID created by UUIDGEN?"
15010 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15012 (defun org-context ()
15013 "Return a list of contexts of the current cursor position.
15014 If several contexts apply, all are returned.
15015 Each context entry is a list with a symbol naming the context, and
15016 two positions indicating start and end of the context. Possible
15017 contexts are:
15019 :headline anywhere in a headline
15020 :headline-stars on the leading stars in a headline
15021 :todo-keyword on a TODO keyword (including DONE) in a headline
15022 :tags on the TAGS in a headline
15023 :priority on the priority cookie in a headline
15024 :item on the first line of a plain list item
15025 :item-bullet on the bullet/number of a plain list item
15026 :checkbox on the checkbox in a plain list item
15027 :table in an org-mode table
15028 :table-special on a special filed in a table
15029 :table-table in a table.el table
15030 :link on a hyperlink
15031 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15032 :target on a <<target>>
15033 :radio-target on a <<<radio-target>>>
15034 :latex-fragment on a LaTeX fragment
15035 :latex-preview on a LaTeX fragment with overlayed preview image
15037 This function expects the position to be visible because it uses font-lock
15038 faces as a help to recognize the following contexts: :table-special, :link,
15039 and :keyword."
15040 (let* ((f (get-text-property (point) 'face))
15041 (faces (if (listp f) f (list f)))
15042 (p (point)) clist o)
15043 ;; First the large context
15044 (cond
15045 ((org-on-heading-p t)
15046 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15047 (when (progn
15048 (beginning-of-line 1)
15049 (looking-at org-todo-line-tags-regexp))
15050 (push (org-point-in-group p 1 :headline-stars) clist)
15051 (push (org-point-in-group p 2 :todo-keyword) clist)
15052 (push (org-point-in-group p 4 :tags) clist))
15053 (goto-char p)
15054 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15055 (if (looking-at "\\[#[A-Z0-9]\\]")
15056 (push (org-point-in-group p 0 :priority) clist)))
15058 ((org-at-item-p)
15059 (push (org-point-in-group p 2 :item-bullet) clist)
15060 (push (list :item (point-at-bol)
15061 (save-excursion (org-end-of-item) (point)))
15062 clist)
15063 (and (org-at-item-checkbox-p)
15064 (push (org-point-in-group p 0 :checkbox) clist)))
15066 ((org-at-table-p)
15067 (push (list :table (org-table-begin) (org-table-end)) clist)
15068 (if (memq 'org-formula faces)
15069 (push (list :table-special
15070 (previous-single-property-change p 'face)
15071 (next-single-property-change p 'face)) clist)))
15072 ((org-at-table-p 'any)
15073 (push (list :table-table) clist)))
15074 (goto-char p)
15076 ;; Now the small context
15077 (cond
15078 ((org-at-timestamp-p)
15079 (push (org-point-in-group p 0 :timestamp) clist))
15080 ((memq 'org-link faces)
15081 (push (list :link
15082 (previous-single-property-change p 'face)
15083 (next-single-property-change p 'face)) clist))
15084 ((memq 'org-special-keyword faces)
15085 (push (list :keyword
15086 (previous-single-property-change p 'face)
15087 (next-single-property-change p 'face)) clist))
15088 ((org-on-target-p)
15089 (push (org-point-in-group p 0 :target) clist)
15090 (goto-char (1- (match-beginning 0)))
15091 (if (looking-at org-radio-target-regexp)
15092 (push (org-point-in-group p 0 :radio-target) clist))
15093 (goto-char p))
15094 ((setq o (car (delq nil
15095 (mapcar
15096 (lambda (x)
15097 (if (memq x org-latex-fragment-image-overlays) x))
15098 (org-overlays-at (point))))))
15099 (push (list :latex-fragment
15100 (org-overlay-start o) (org-overlay-end o)) clist)
15101 (push (list :latex-preview
15102 (org-overlay-start o) (org-overlay-end o)) clist))
15103 ((org-inside-LaTeX-fragment-p)
15104 ;; FIXME: positions wrong.
15105 (push (list :latex-fragment (point) (point)) clist)))
15107 (setq clist (nreverse (delq nil clist)))
15108 clist))
15110 ;; FIXME: Compare with at-regexp-p Do we need both?
15111 (defun org-in-regexp (re &optional nlines visually)
15112 "Check if point is inside a match of regexp.
15113 Normally only the current line is checked, but you can include NLINES extra
15114 lines both before and after point into the search.
15115 If VISUALLY is set, require that the cursor is not after the match but
15116 really on, so that the block visually is on the match."
15117 (catch 'exit
15118 (let ((pos (point))
15119 (eol (point-at-eol (+ 1 (or nlines 0))))
15120 (inc (if visually 1 0)))
15121 (save-excursion
15122 (beginning-of-line (- 1 (or nlines 0)))
15123 (while (re-search-forward re eol t)
15124 (if (and (<= (match-beginning 0) pos)
15125 (>= (+ inc (match-end 0)) pos))
15126 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15128 (defun org-at-regexp-p (regexp)
15129 "Is point inside a match of REGEXP in the current line?"
15130 (catch 'exit
15131 (save-excursion
15132 (let ((pos (point)) (end (point-at-eol)))
15133 (beginning-of-line 1)
15134 (while (re-search-forward regexp end t)
15135 (if (and (<= (match-beginning 0) pos)
15136 (>= (match-end 0) pos))
15137 (throw 'exit t)))
15138 nil))))
15140 (defun org-occur-in-agenda-files (regexp &optional nlines)
15141 "Call `multi-occur' with buffers for all agenda files."
15142 (interactive "sOrg-files matching: \np")
15143 (let* ((files (org-agenda-files))
15144 (tnames (mapcar 'file-truename files))
15145 (extra org-agenda-text-search-extra-files)
15147 (when (eq (car extra) 'agenda-archives)
15148 (setq extra (cdr extra))
15149 (setq files (org-add-archive-files files)))
15150 (while (setq f (pop extra))
15151 (unless (member (file-truename f) tnames)
15152 (add-to-list 'files f 'append)
15153 (add-to-list 'tnames (file-truename f) 'append)))
15154 (multi-occur
15155 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15156 regexp)))
15158 (if (boundp 'occur-mode-find-occurrence-hook)
15159 ;; Emacs 23
15160 (add-hook 'occur-mode-find-occurrence-hook
15161 (lambda ()
15162 (when (org-mode-p)
15163 (org-reveal))))
15164 ;; Emacs 22
15165 (defadvice occur-mode-goto-occurrence
15166 (after org-occur-reveal activate)
15167 (and (org-mode-p) (org-reveal)))
15168 (defadvice occur-mode-goto-occurrence-other-window
15169 (after org-occur-reveal activate)
15170 (and (org-mode-p) (org-reveal)))
15171 (defadvice occur-mode-display-occurrence
15172 (after org-occur-reveal activate)
15173 (when (org-mode-p)
15174 (let ((pos (occur-mode-find-occurrence)))
15175 (with-current-buffer (marker-buffer pos)
15176 (save-excursion
15177 (goto-char pos)
15178 (org-reveal)))))))
15180 (defun org-uniquify (list)
15181 "Remove duplicate elements from LIST."
15182 (let (res)
15183 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15184 res))
15186 (defun org-delete-all (elts list)
15187 "Remove all elements in ELTS from LIST."
15188 (while elts
15189 (setq list (delete (pop elts) list)))
15190 list)
15192 (defun org-back-over-empty-lines ()
15193 "Move backwards over whitespace, to the beginning of the first empty line.
15194 Returns the number of empty lines passed."
15195 (let ((pos (point)))
15196 (skip-chars-backward " \t\n\r")
15197 (beginning-of-line 2)
15198 (goto-char (min (point) pos))
15199 (count-lines (point) pos)))
15201 (defun org-skip-whitespace ()
15202 (skip-chars-forward " \t\n\r"))
15204 (defun org-point-in-group (point group &optional context)
15205 "Check if POINT is in match-group GROUP.
15206 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15207 match. If the match group does ot exist or point is not inside it,
15208 return nil."
15209 (and (match-beginning group)
15210 (>= point (match-beginning group))
15211 (<= point (match-end group))
15212 (if context
15213 (list context (match-beginning group) (match-end group))
15214 t)))
15216 (defun org-switch-to-buffer-other-window (&rest args)
15217 "Switch to buffer in a second window on the current frame.
15218 In particular, do not allow pop-up frames."
15219 (let (pop-up-frames special-display-buffer-names special-display-regexps
15220 special-display-function)
15221 (apply 'switch-to-buffer-other-window args)))
15223 (defun org-combine-plists (&rest plists)
15224 "Create a single property list from all plists in PLISTS.
15225 The process starts by copying the first list, and then setting properties
15226 from the other lists. Settings in the last list are the most significant
15227 ones and overrule settings in the other lists."
15228 (let ((rtn (copy-sequence (pop plists)))
15229 p v ls)
15230 (while plists
15231 (setq ls (pop plists))
15232 (while ls
15233 (setq p (pop ls) v (pop ls))
15234 (setq rtn (plist-put rtn p v))))
15235 rtn))
15237 (defun org-move-line-down (arg)
15238 "Move the current line down. 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 (+ 1 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-move-line-up (arg)
15251 "Move the current line up. With prefix argument, move it past ARG lines."
15252 (interactive "p")
15253 (let ((col (current-column))
15254 beg end pos)
15255 (beginning-of-line 1) (setq beg (point))
15256 (beginning-of-line 2) (setq end (point))
15257 (beginning-of-line (- arg))
15258 (setq pos (move-marker (make-marker) (point)))
15259 (insert (delete-and-extract-region beg end))
15260 (goto-char pos)
15261 (org-move-to-column col)))
15263 (defun org-replace-escapes (string table)
15264 "Replace %-escapes in STRING with values in TABLE.
15265 TABLE is an association list with keys like \"%a\" and string values.
15266 The sequences in STRING may contain normal field width and padding information,
15267 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15268 so values can contain further %-escapes if they are define later in TABLE."
15269 (let ((case-fold-search nil)
15270 e re rpl)
15271 (while (setq e (pop table))
15272 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15273 (while (string-match re string)
15274 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15275 (cdr e)))
15276 (setq string (replace-match rpl t t string))))
15277 string))
15280 (defun org-sublist (list start end)
15281 "Return a section of LIST, from START to END.
15282 Counting starts at 1."
15283 (let (rtn (c start))
15284 (setq list (nthcdr (1- start) list))
15285 (while (and list (<= c end))
15286 (push (pop list) rtn)
15287 (setq c (1+ c)))
15288 (nreverse rtn)))
15290 (defun org-find-base-buffer-visiting (file)
15291 "Like `find-buffer-visiting' but alway return the base buffer and
15292 not an indirect buffer."
15293 (let ((buf (find-buffer-visiting file)))
15294 (if buf
15295 (or (buffer-base-buffer buf) buf)
15296 nil)))
15298 (defun org-image-file-name-regexp (&optional extensions)
15299 "Return regexp matching the file names of images.
15300 If EXTENSIONS is given, only match these."
15301 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15302 (image-file-name-regexp)
15303 (let ((image-file-name-extensions
15304 (or extensions
15305 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15306 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15307 (concat "\\."
15308 (regexp-opt (nconc (mapcar 'upcase
15309 image-file-name-extensions)
15310 image-file-name-extensions)
15312 "\\'"))))
15314 (defun org-file-image-p (file &optional extensions)
15315 "Return non-nil if FILE is an image."
15316 (save-match-data
15317 (string-match (org-image-file-name-regexp extensions) file)))
15319 (defun org-get-cursor-date ()
15320 "Return the date at cursor in as a time.
15321 This works in the calendar and in the agenda, anywhere else it just
15322 returns the current time."
15323 (let (date day defd)
15324 (cond
15325 ((eq major-mode 'calendar-mode)
15326 (setq date (calendar-cursor-to-date)
15327 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15328 ((eq major-mode 'org-agenda-mode)
15329 (setq day (get-text-property (point) 'day))
15330 (if day
15331 (setq date (calendar-gregorian-from-absolute day)
15332 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15333 (nth 2 date))))))
15334 (or defd (current-time))))
15336 (defvar org-agenda-action-marker (make-marker)
15337 "Marker pointing to the entry for the next agenda action.")
15339 (defun org-mark-entry-for-agenda-action ()
15340 "Mark the current entry as target of an agenda action.
15341 Agenda actions are actions executed from the agenda with the key `k',
15342 which make use of the date at the cursor."
15343 (interactive)
15344 (move-marker org-agenda-action-marker
15345 (save-excursion (org-back-to-heading t) (point))
15346 (current-buffer))
15347 (message
15348 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15350 ;;; Paragraph filling stuff.
15351 ;; We want this to be just right, so use the full arsenal.
15353 (defun org-indent-line-function ()
15354 "Indent line like previous, but further if previous was headline or item."
15355 (interactive)
15356 (let* ((pos (point))
15357 (itemp (org-at-item-p))
15358 (org-drawer-regexp (or org-drawer-regexp "\000"))
15359 column bpos bcol tpos tcol bullet btype bullet-type)
15360 ;; Find the previous relevant line
15361 (beginning-of-line 1)
15362 (cond
15363 ((looking-at "#") (setq column 0))
15364 ((looking-at "\\*+ ") (setq column 0))
15365 ((and (looking-at "[ \t]*:END:")
15366 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15367 (save-excursion
15368 (goto-char (1- (match-beginning 1)))
15369 (setq column (current-column))))
15371 (beginning-of-line 0)
15372 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15373 (not (looking-at "[ \t]*:END:"))
15374 (not (looking-at org-drawer-regexp)))
15375 (beginning-of-line 0))
15376 (cond
15377 ((looking-at "\\*+[ \t]+")
15378 (if (not org-adapt-indentation)
15379 (setq column 0)
15380 (goto-char (match-end 0))
15381 (setq column (current-column))))
15382 ((looking-at org-drawer-regexp)
15383 (goto-char (1- (match-beginning 1)))
15384 (setq column (current-column)))
15385 ((looking-at "\\([ \t]*\\):END:")
15386 (goto-char (match-end 1))
15387 (setq column (current-column)))
15388 ((org-in-item-p)
15389 (org-beginning-of-item)
15390 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15391 (setq bpos (match-beginning 1) tpos (match-end 0)
15392 bcol (progn (goto-char bpos) (current-column))
15393 tcol (progn (goto-char tpos) (current-column))
15394 bullet (match-string 1)
15395 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15396 (if (> tcol (+ bcol org-description-max-indent))
15397 (setq tcol (+ bcol 5)))
15398 (if (not itemp)
15399 (setq column tcol)
15400 (goto-char pos)
15401 (beginning-of-line 1)
15402 (if (looking-at "\\S-")
15403 (progn
15404 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15405 (setq bullet (match-string 1)
15406 btype (if (string-match "[0-9]" bullet) "n" bullet))
15407 (setq column (if (equal btype bullet-type) bcol tcol)))
15408 (setq column (org-get-indentation)))))
15409 (t (setq column (org-get-indentation))))))
15410 (goto-char pos)
15411 (if (<= (current-column) (current-indentation))
15412 (org-indent-line-to column)
15413 (save-excursion (org-indent-line-to column)))
15414 (setq column (current-column))
15415 (beginning-of-line 1)
15416 (if (looking-at
15417 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15418 (replace-match (concat "\\1" (format org-property-format
15419 (match-string 2) (match-string 3)))
15420 t nil))
15421 (org-move-to-column column)))
15423 (defun org-set-autofill-regexps ()
15424 (interactive)
15425 ;; In the paragraph separator we include headlines, because filling
15426 ;; text in a line directly attached to a headline would otherwise
15427 ;; fill the headline as well.
15428 (org-set-local 'comment-start-skip "^#+[ \t]*")
15429 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15430 ;; The paragraph starter includes hand-formatted lists.
15431 (org-set-local 'paragraph-start
15432 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15433 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15434 ;; But only if the user has not turned off tables or fixed-width regions
15435 (org-set-local
15436 'auto-fill-inhibit-regexp
15437 (concat "\\*+ \\|#\\+"
15438 "\\|[ \t]*" org-keyword-time-regexp
15439 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15440 (concat
15441 "\\|[ \t]*["
15442 (if org-enable-table-editor "|" "")
15443 (if org-enable-fixed-width-editor ":" "")
15444 "]"))))
15445 ;; We use our own fill-paragraph function, to make sure that tables
15446 ;; and fixed-width regions are not wrapped. That function will pass
15447 ;; through to `fill-paragraph' when appropriate.
15448 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15449 ; Adaptive filling: To get full control, first make sure that
15450 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15451 (org-set-local 'adaptive-fill-regexp "\000")
15452 (org-set-local 'adaptive-fill-function
15453 'org-adaptive-fill-function)
15454 (org-set-local
15455 'align-mode-rules-list
15456 '((org-in-buffer-settings
15457 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15458 (modes . '(org-mode))))))
15460 (defun org-fill-paragraph (&optional justify)
15461 "Re-align a table, pass through to fill-paragraph if no table."
15462 (let ((table-p (org-at-table-p))
15463 (table.el-p (org-at-table.el-p)))
15464 (cond ((and (equal (char-after (point-at-bol)) ?*)
15465 (save-excursion (goto-char (point-at-bol))
15466 (looking-at outline-regexp)))
15467 t) ; skip headlines
15468 (table.el-p t) ; skip table.el tables
15469 (table-p (org-table-align) t) ; align org-mode tables
15470 (t nil)))) ; call paragraph-fill
15472 ;; For reference, this is the default value of adaptive-fill-regexp
15473 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15475 (defun org-adaptive-fill-function ()
15476 "Return a fill prefix for org-mode files.
15477 In particular, this makes sure hanging paragraphs for hand-formatted lists
15478 work correctly."
15479 (cond ((looking-at "#[ \t]+")
15480 (match-string 0))
15481 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15482 (save-excursion
15483 (if (> (match-end 1) (+ (match-beginning 1)
15484 org-description-max-indent))
15485 (goto-char (+ (match-beginning 1) 5))
15486 (goto-char (match-end 0)))
15487 (make-string (current-column) ?\ )))
15488 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15489 (save-excursion
15490 (goto-char (match-end 0))
15491 (make-string (current-column) ?\ )))
15492 (t nil)))
15494 ;;; Other stuff.
15496 (defun org-toggle-fixed-width-section (arg)
15497 "Toggle the fixed-width export.
15498 If there is no active region, the QUOTE keyword at the current headline is
15499 inserted or removed. When present, it causes the text between this headline
15500 and the next to be exported as fixed-width text, and unmodified.
15501 If there is an active region, this command adds or removes a colon as the
15502 first character of this line. If the first character of a line is a colon,
15503 this line is also exported in fixed-width font."
15504 (interactive "P")
15505 (let* ((cc 0)
15506 (regionp (org-region-active-p))
15507 (beg (if regionp (region-beginning) (point)))
15508 (end (if regionp (region-end)))
15509 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15510 (case-fold-search nil)
15511 (re "[ \t]*\\(: \\)")
15512 off)
15513 (if regionp
15514 (save-excursion
15515 (goto-char beg)
15516 (setq cc (current-column))
15517 (beginning-of-line 1)
15518 (setq off (looking-at re))
15519 (while (> nlines 0)
15520 (setq nlines (1- nlines))
15521 (beginning-of-line 1)
15522 (cond
15523 (arg
15524 (org-move-to-column cc t)
15525 (insert ": \n")
15526 (forward-line -1))
15527 ((and off (looking-at re))
15528 (replace-match "" t t nil 1))
15529 ((not off) (org-move-to-column cc t) (insert ": ")))
15530 (forward-line 1)))
15531 (save-excursion
15532 (org-back-to-heading)
15533 (if (looking-at (concat outline-regexp
15534 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15535 (replace-match "" t t nil 1)
15536 (if (looking-at outline-regexp)
15537 (progn
15538 (goto-char (match-end 0))
15539 (insert org-quote-string " "))))))))
15541 (defun org-reftex-citation ()
15542 "Use reftex-citation to insert a citation into the buffer.
15543 This looks for a line like
15545 #+BIBLIOGRAPHY: foo plain option:-d
15547 and derives from it that foo.bib is the bbliography file relevant
15548 for this document. It then installs the necessary environment for RefTeX
15549 to work in this buffer and calls `reftex-citation' to insert a citation
15550 into the buffer.
15552 Export of such citations to both LaTeX and HTML is handled by the contributed
15553 package org-exp-bibtex by Taru Karttunen."
15554 (interactive)
15555 (let ((reftex-docstruct-symbol 'rds)
15556 (reftex-cite-format "\\cite{%l}")
15557 rds bib)
15558 (save-excursion
15559 (save-restriction
15560 (widen)
15561 (let ((case-fold-search t)
15562 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
15563 (if (not (save-excursion
15564 (or (re-search-forward re nil t)
15565 (re-search-backward re nil t))))
15566 (error "No bibliography defined in file")
15567 (setq bib (concat (match-string 1) ".bib")
15568 rds (list (list 'bib bib)))))))
15569 (call-interactively 'reftex-citation)))
15571 ;;;; Functions extending outline functionality
15573 (defun org-beginning-of-line (&optional arg)
15574 "Go to the beginning of the current line. If that is invisible, continue
15575 to a visible line beginning. This makes the function of C-a more intuitive.
15576 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15577 first attempt, and only move to after the tags when the cursor is already
15578 beyond the end of the headline."
15579 (interactive "P")
15580 (let ((pos (point))
15581 (special (if (consp org-special-ctrl-a/e)
15582 (car org-special-ctrl-a/e)
15583 org-special-ctrl-a/e))
15584 refpos)
15585 (beginning-of-line 1)
15586 (if (and arg (fboundp 'move-beginning-of-line))
15587 (call-interactively 'move-beginning-of-line)
15588 (if (bobp)
15590 (backward-char 1)
15591 (if (org-invisible-p)
15592 (while (and (not (bobp)) (org-invisible-p))
15593 (backward-char 1)
15594 (beginning-of-line 1))
15595 (forward-char 1))))
15596 (when special
15597 (cond
15598 ((and (looking-at org-complex-heading-regexp)
15599 (= (char-after (match-end 1)) ?\ ))
15600 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15601 (point-at-eol)))
15602 (goto-char
15603 (if (eq special t)
15604 (cond ((> pos refpos) refpos)
15605 ((= pos (point)) refpos)
15606 (t (point)))
15607 (cond ((> pos (point)) (point))
15608 ((not (eq last-command this-command)) (point))
15609 (t refpos)))))
15610 ((org-at-item-p)
15611 (goto-char
15612 (if (eq special t)
15613 (cond ((> pos (match-end 4)) (match-end 4))
15614 ((= pos (point)) (match-end 4))
15615 (t (point)))
15616 (cond ((> pos (point)) (point))
15617 ((not (eq last-command this-command)) (point))
15618 (t (match-end 4))))))))
15619 (org-no-warnings
15620 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15622 (defun org-end-of-line (&optional arg)
15623 "Go to the end of the line.
15624 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15625 first attempt, and only move to after the tags when the cursor is already
15626 beyond the end of the headline."
15627 (interactive "P")
15628 (let ((special (if (consp org-special-ctrl-a/e)
15629 (cdr org-special-ctrl-a/e)
15630 org-special-ctrl-a/e)))
15631 (if (or (not special)
15632 (not (org-on-heading-p))
15633 arg)
15634 (call-interactively (if (fboundp 'move-end-of-line)
15635 'move-end-of-line
15636 'end-of-line))
15637 (let ((pos (point)))
15638 (beginning-of-line 1)
15639 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15640 (if (eq special t)
15641 (if (or (< pos (match-beginning 1))
15642 (= pos (match-end 0)))
15643 (goto-char (match-beginning 1))
15644 (goto-char (match-end 0)))
15645 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15646 (goto-char (match-end 0))
15647 (goto-char (match-beginning 1))))
15648 (call-interactively (if (fboundp 'move-end-of-line)
15649 'move-end-of-line
15650 'end-of-line)))))
15651 (org-no-warnings
15652 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15654 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15655 (define-key org-mode-map "\C-e" 'org-end-of-line)
15657 (defun org-backward-sentence (&optional arg)
15658 "Go to beginning of sentence, or beginning of table field.
15659 This will call `backward-sentence' or `org-table-beginning-of-field',
15660 depending on context."
15661 (interactive "P")
15662 (cond
15663 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
15664 (t (call-interactively 'backward-sentence))))
15666 (defun org-forward-sentence (&optional arg)
15667 "Go to end of sentence, or end of table field.
15668 This will call `forward-sentence' or `org-table-end-of-field',
15669 depending on context."
15670 (interactive "P")
15671 (cond
15672 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
15673 (t (call-interactively 'forward-sentence))))
15675 (define-key org-mode-map "\M-a" 'org-backward-sentence)
15676 (define-key org-mode-map "\M-e" 'org-forward-sentence)
15678 (defun org-kill-line (&optional arg)
15679 "Kill line, to tags or end of line."
15680 (interactive "P")
15681 (cond
15682 ((or (not org-special-ctrl-k)
15683 (bolp)
15684 (not (org-on-heading-p)))
15685 (call-interactively 'kill-line))
15686 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15687 (kill-region (point) (match-beginning 1))
15688 (org-set-tags nil t))
15689 (t (kill-region (point) (point-at-eol)))))
15691 (define-key org-mode-map "\C-k" 'org-kill-line)
15693 (defun org-yank (&optional arg)
15694 "Yank. If the kill is a subtree, treat it specially.
15695 This command will look at the current kill and check if is a single
15696 subtree, or a series of subtrees[1]. If it passes the test, and if the
15697 cursor is at the beginning of a line or after the stars of a currently
15698 empty headline, then the yank is handled specially. How exactly depends
15699 on the value of the following variables, both set by default.
15701 org-yank-folded-subtrees
15702 When set, the subtree(s) will be folded after insertion, but only
15703 if doing so would now swallow text after the yanked text.
15705 org-yank-adjusted-subtrees
15706 When set, the subtree will be promoted or demoted in order to
15707 fit into the local outline tree structure, which means that the level
15708 will be adjusted so that it becomes the smaller one of the two
15709 *visible* surrounding headings.
15711 Any prefix to this command will cause `yank' to be called directly with
15712 no special treatment. In particular, a simple `C-u' prefix will just
15713 plainly yank the text as it is.
15715 \[1] Basically, the test checks if the first non-white line is a heading
15716 and if there are no other headings with fewer stars."
15717 (interactive "P")
15718 (setq this-command 'yank)
15719 (if arg
15720 (call-interactively 'yank)
15721 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15722 (and (org-kill-is-subtree-p)
15723 (or (bolp)
15724 (and (looking-at "[ \t]*$")
15725 (string-match
15726 "\\`\\*+\\'"
15727 (buffer-substring (point-at-bol) (point)))))))
15728 swallowp)
15729 (cond
15730 ((and subtreep org-yank-folded-subtrees)
15731 (let ((beg (point))
15732 end)
15733 (if (and subtreep org-yank-adjusted-subtrees)
15734 (org-paste-subtree nil nil 'for-yank)
15735 (call-interactively 'yank))
15736 (setq end (point))
15737 (goto-char beg)
15738 (when (and (bolp) subtreep
15739 (not (setq swallowp
15740 (org-yank-folding-would-swallow-text beg end))))
15741 (or (looking-at outline-regexp)
15742 (re-search-forward (concat "^" outline-regexp) end t))
15743 (while (and (< (point) end) (looking-at outline-regexp))
15744 (hide-subtree)
15745 (org-cycle-show-empty-lines 'folded)
15746 (condition-case nil
15747 (outline-forward-same-level 1)
15748 (error (goto-char end)))))
15749 (when swallowp
15750 (message
15751 "Yanked text not folded because that would swallow text"))
15752 (goto-char end)
15753 (skip-chars-forward " \t\n\r")
15754 (beginning-of-line 1)
15755 (push-mark beg 'nomsg)))
15756 ((and subtreep org-yank-adjusted-subtrees)
15757 (let ((beg (point-at-bol)))
15758 (org-paste-subtree nil nil 'for-yank)
15759 (push-mark beg 'nomsg)))
15761 (call-interactively 'yank))))))
15763 (defun org-yank-folding-would-swallow-text (beg end)
15764 "Would hide-subtree at BEG swallow any text after END?"
15765 (let (level)
15766 (save-excursion
15767 (goto-char beg)
15768 (when (or (looking-at outline-regexp)
15769 (re-search-forward (concat "^" outline-regexp) end t))
15770 (setq level (org-outline-level)))
15771 (goto-char end)
15772 (skip-chars-forward " \t\r\n\v\f")
15773 (if (or (eobp)
15774 (and (bolp) (looking-at org-outline-regexp)
15775 (<= (org-outline-level) level)))
15776 nil ; Nothing would be swallowed
15777 t)))) ; something would swallow
15779 (define-key org-mode-map "\C-y" 'org-yank)
15781 (defun org-invisible-p ()
15782 "Check if point is at a character currently not visible."
15783 ;; Early versions of noutline don't have `outline-invisible-p'.
15784 (if (fboundp 'outline-invisible-p)
15785 (outline-invisible-p)
15786 (get-char-property (point) 'invisible)))
15788 (defun org-invisible-p2 ()
15789 "Check if point is at a character currently not visible."
15790 (save-excursion
15791 (if (and (eolp) (not (bobp))) (backward-char 1))
15792 ;; Early versions of noutline don't have `outline-invisible-p'.
15793 (if (fboundp 'outline-invisible-p)
15794 (outline-invisible-p)
15795 (get-char-property (point) 'invisible))))
15797 (defun org-back-to-heading (&optional invisible-ok)
15798 "Call `outline-back-to-heading', but provide a better error message."
15799 (condition-case nil
15800 (outline-back-to-heading invisible-ok)
15801 (error (error "Before first headline at position %d in buffer %s"
15802 (point) (current-buffer)))))
15804 (defun org-before-first-heading-p ()
15805 "Before first heading?"
15806 (save-excursion
15807 (null (re-search-backward "^\\*+ " nil t))))
15809 (defalias 'org-on-heading-p 'outline-on-heading-p)
15810 (defalias 'org-at-heading-p 'outline-on-heading-p)
15811 (defun org-at-heading-or-item-p ()
15812 (or (org-on-heading-p) (org-at-item-p)))
15814 (defun org-on-target-p ()
15815 (or (org-in-regexp org-radio-target-regexp)
15816 (org-in-regexp org-target-regexp)))
15818 (defun org-up-heading-all (arg)
15819 "Move to the heading line of which the present line is a subheading.
15820 This function considers both visible and invisible heading lines.
15821 With argument, move up ARG levels."
15822 (if (fboundp 'outline-up-heading-all)
15823 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15824 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15826 (defun org-up-heading-safe ()
15827 "Move to the heading line of which the present line is a subheading.
15828 This version will not throw an error. It will return the level of the
15829 headline found, or nil if no higher level is found.
15831 Also, this function will be a lot faster than `outline-up-heading',
15832 because it relies on stars being the outline starters. This can really
15833 make a significant difference in outlines with very many siblings."
15834 (let (start-level re)
15835 (org-back-to-heading t)
15836 (setq start-level (funcall outline-level))
15837 (if (equal start-level 1)
15839 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
15840 (if (re-search-backward re nil t)
15841 (funcall outline-level)))))
15843 (defun org-first-sibling-p ()
15844 "Is this heading the first child of its parents?"
15845 (interactive)
15846 (let ((re (concat "^" outline-regexp))
15847 level l)
15848 (unless (org-at-heading-p t)
15849 (error "Not at a heading"))
15850 (setq level (funcall outline-level))
15851 (save-excursion
15852 (if (not (re-search-backward re nil t))
15854 (setq l (funcall outline-level))
15855 (< l level)))))
15857 (defun org-goto-sibling (&optional previous)
15858 "Goto the next sibling, even if it is invisible.
15859 When PREVIOUS is set, go to the previous sibling instead. Returns t
15860 when a sibling was found. When none is found, return nil and don't
15861 move point."
15862 (let ((fun (if previous 're-search-backward 're-search-forward))
15863 (pos (point))
15864 (re (concat "^" outline-regexp))
15865 level l)
15866 (when (condition-case nil (org-back-to-heading t) (error nil))
15867 (setq level (funcall outline-level))
15868 (catch 'exit
15869 (or previous (forward-char 1))
15870 (while (funcall fun re nil t)
15871 (setq l (funcall outline-level))
15872 (when (< l level) (goto-char pos) (throw 'exit nil))
15873 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15874 (goto-char pos)
15875 nil))))
15877 (defun org-show-siblings ()
15878 "Show all siblings of the current headline."
15879 (save-excursion
15880 (while (org-goto-sibling) (org-flag-heading nil)))
15881 (save-excursion
15882 (while (org-goto-sibling 'previous)
15883 (org-flag-heading nil))))
15885 (defun org-show-hidden-entry ()
15886 "Show an entry where even the heading is hidden."
15887 (save-excursion
15888 (org-show-entry)))
15890 (defun org-flag-heading (flag &optional entry)
15891 "Flag the current heading. FLAG non-nil means make invisible.
15892 When ENTRY is non-nil, show the entire entry."
15893 (save-excursion
15894 (org-back-to-heading t)
15895 ;; Check if we should show the entire entry
15896 (if entry
15897 (progn
15898 (org-show-entry)
15899 (save-excursion
15900 (and (outline-next-heading)
15901 (org-flag-heading nil))))
15902 (outline-flag-region (max (point-min) (1- (point)))
15903 (save-excursion (outline-end-of-heading) (point))
15904 flag))))
15906 (defun org-forward-same-level (arg)
15907 "Move forward to the ARG'th subheading at same level as this one.
15908 Stop at the first and last subheadings of a superior heading.
15909 This is like outline-forward-same-level, but invisible headings are ok."
15910 (interactive "p")
15911 (org-back-to-heading t)
15912 (while (> arg 0)
15913 (let ((point-to-move-to (save-excursion
15914 (org-get-next-sibling))))
15915 (if point-to-move-to
15916 (progn
15917 (goto-char point-to-move-to)
15918 (setq arg (1- arg)))
15919 (progn
15920 (setq arg 0)
15921 (error "No following same-level heading"))))))
15923 (defun org-get-next-sibling ()
15924 "Move to next heading of the same level, and return point.
15925 If there is no such heading, return nil.
15926 This is like outline-next-sibling, but invisible headings are ok."
15927 (let ((level (funcall outline-level)))
15928 (outline-next-heading)
15929 (while (and (not (eobp)) (> (funcall outline-level) level))
15930 (outline-next-heading))
15931 (if (or (eobp) (< (funcall outline-level) level))
15933 (point))))
15935 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15936 ;; This is an exact copy of the original function, but it uses
15937 ;; `org-back-to-heading', to make it work also in invisible
15938 ;; trees. And is uses an invisible-OK argument.
15939 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15940 (org-back-to-heading invisible-OK)
15941 (let ((first t)
15942 (level (funcall outline-level)))
15943 (while (and (not (eobp))
15944 (or first (> (funcall outline-level) level)))
15945 (setq first nil)
15946 (outline-next-heading))
15947 (unless to-heading
15948 (if (memq (preceding-char) '(?\n ?\^M))
15949 (progn
15950 ;; Go to end of line before heading
15951 (forward-char -1)
15952 (if (memq (preceding-char) '(?\n ?\^M))
15953 ;; leave blank line before heading
15954 (forward-char -1))))))
15955 (point))
15957 (defun org-show-subtree ()
15958 "Show everything after this heading at deeper levels."
15959 (outline-flag-region
15960 (point)
15961 (save-excursion
15962 (outline-end-of-subtree) (outline-next-heading) (point))
15963 nil))
15965 (defun org-show-entry ()
15966 "Show the body directly following this heading.
15967 Show the heading too, if it is currently invisible."
15968 (interactive)
15969 (save-excursion
15970 (condition-case nil
15971 (progn
15972 (org-back-to-heading t)
15973 (outline-flag-region
15974 (max (point-min) (1- (point)))
15975 (save-excursion
15976 (if (re-search-forward
15977 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
15978 (match-beginning 1)
15979 (point-max)))
15980 nil))
15981 (error nil))))
15983 (defun org-make-options-regexp (kwds &optional extra)
15984 "Make a regular expression for keyword lines."
15985 (concat
15987 "#?[ \t]*\\+\\("
15988 (mapconcat 'regexp-quote kwds "\\|")
15989 (if extra (concat "\\|" extra))
15990 "\\):[ \t]*"
15991 "\\(.+\\)"))
15993 ;; Make isearch reveal the necessary context
15994 (defun org-isearch-end ()
15995 "Reveal context after isearch exits."
15996 (when isearch-success ; only if search was successful
15997 (if (featurep 'xemacs)
15998 ;; Under XEmacs, the hook is run in the correct place,
15999 ;; we directly show the context.
16000 (org-show-context 'isearch)
16001 ;; In Emacs the hook runs *before* restoring the overlays.
16002 ;; So we have to use a one-time post-command-hook to do this.
16003 ;; (Emacs 22 has a special variable, see function `org-mode')
16004 (unless (and (boundp 'isearch-mode-end-hook-quit)
16005 isearch-mode-end-hook-quit)
16006 ;; Only when the isearch was not quitted.
16007 (org-add-hook 'post-command-hook 'org-isearch-post-command
16008 'append 'local)))))
16010 (defun org-isearch-post-command ()
16011 "Remove self from hook, and show context."
16012 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16013 (org-show-context 'isearch))
16016 ;;;; Integration with and fixes for other packages
16018 ;;; Imenu support
16020 (defvar org-imenu-markers nil
16021 "All markers currently used by Imenu.")
16022 (make-variable-buffer-local 'org-imenu-markers)
16024 (defun org-imenu-new-marker (&optional pos)
16025 "Return a new marker for use by Imenu, and remember the marker."
16026 (let ((m (make-marker)))
16027 (move-marker m (or pos (point)))
16028 (push m org-imenu-markers)
16031 (defun org-imenu-get-tree ()
16032 "Produce the index for Imenu."
16033 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16034 (setq org-imenu-markers nil)
16035 (let* ((n org-imenu-depth)
16036 (re (concat "^" outline-regexp))
16037 (subs (make-vector (1+ n) nil))
16038 (last-level 0)
16039 m level head)
16040 (save-excursion
16041 (save-restriction
16042 (widen)
16043 (goto-char (point-max))
16044 (while (re-search-backward re nil t)
16045 (setq level (org-reduced-level (funcall outline-level)))
16046 (when (<= level n)
16047 (looking-at org-complex-heading-regexp)
16048 (setq head (org-link-display-format
16049 (org-match-string-no-properties 4))
16050 m (org-imenu-new-marker))
16051 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16052 (if (>= level last-level)
16053 (push (cons head m) (aref subs level))
16054 (push (cons head (aref subs (1+ level))) (aref subs level))
16055 (loop for i from (1+ level) to n do (aset subs i nil)))
16056 (setq last-level level)))))
16057 (aref subs 1)))
16059 (eval-after-load "imenu"
16060 '(progn
16061 (add-hook 'imenu-after-jump-hook
16062 (lambda ()
16063 (if (eq major-mode 'org-mode)
16064 (org-show-context 'org-goto))))))
16066 (defun org-link-display-format (link)
16067 "Replace a link with either the description, or the link target
16068 if no description is present"
16069 (save-match-data
16070 (if (string-match org-bracket-link-analytic-regexp link)
16071 (replace-match (or (match-string 5 link)
16072 (concat (match-string 1 link)
16073 (match-string 3 link)))
16074 nil nil link)
16075 link)))
16077 ;; Speedbar support
16079 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16080 "Overlay marking the agenda restriction line in speedbar.")
16081 (org-overlay-put org-speedbar-restriction-lock-overlay
16082 'face 'org-agenda-restriction-lock)
16083 (org-overlay-put org-speedbar-restriction-lock-overlay
16084 'help-echo "Agendas are currently limited to this item.")
16085 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16087 (defun org-speedbar-set-agenda-restriction ()
16088 "Restrict future agenda commands to the location at point in speedbar.
16089 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16090 (interactive)
16091 (require 'org-agenda)
16092 (let (p m tp np dir txt)
16093 (cond
16094 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16095 'org-imenu t))
16096 (setq m (get-text-property p 'org-imenu-marker))
16097 (save-excursion
16098 (save-restriction
16099 (set-buffer (marker-buffer m))
16100 (goto-char m)
16101 (org-agenda-set-restriction-lock 'subtree))))
16102 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16103 'speedbar-function 'speedbar-find-file))
16104 (setq tp (previous-single-property-change
16105 (1+ p) 'speedbar-function)
16106 np (next-single-property-change
16107 tp 'speedbar-function)
16108 dir (speedbar-line-directory)
16109 txt (buffer-substring-no-properties (or tp (point-min))
16110 (or np (point-max))))
16111 (save-excursion
16112 (save-restriction
16113 (set-buffer (find-file-noselect
16114 (let ((default-directory dir))
16115 (expand-file-name txt))))
16116 (unless (org-mode-p)
16117 (error "Cannot restrict to non-Org-mode file"))
16118 (org-agenda-set-restriction-lock 'file))))
16119 (t (error "Don't know how to restrict Org-mode's agenda")))
16120 (org-move-overlay org-speedbar-restriction-lock-overlay
16121 (point-at-bol) (point-at-eol))
16122 (setq current-prefix-arg nil)
16123 (org-agenda-maybe-redo)))
16125 (eval-after-load "speedbar"
16126 '(progn
16127 (speedbar-add-supported-extension ".org")
16128 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16129 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16130 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16131 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16132 (add-hook 'speedbar-visiting-tag-hook
16133 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16136 ;;; Fixes and Hacks for problems with other packages
16138 ;; Make flyspell not check words in links, to not mess up our keymap
16139 (defun org-mode-flyspell-verify ()
16140 "Don't let flyspell put overlays at active buttons."
16141 (not (get-text-property (point) 'keymap)))
16143 ;; Make `bookmark-jump' show the jump location if it was hidden.
16144 (eval-after-load "bookmark"
16145 '(if (boundp 'bookmark-after-jump-hook)
16146 ;; We can use the hook
16147 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16148 ;; Hook not available, use advice
16149 (defadvice bookmark-jump (after org-make-visible activate)
16150 "Make the position visible."
16151 (org-bookmark-jump-unhide))))
16153 ;; Make sure saveplace show the location if it was hidden
16154 (eval-after-load "saveplace"
16155 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16156 "Make the position visible."
16157 (org-bookmark-jump-unhide)))
16159 (defun org-bookmark-jump-unhide ()
16160 "Unhide the current position, to show the bookmark location."
16161 (and (org-mode-p)
16162 (or (org-invisible-p)
16163 (save-excursion (goto-char (max (point-min) (1- (point))))
16164 (org-invisible-p)))
16165 (org-show-context 'bookmark-jump)))
16167 ;; Make session.el ignore our circular variable
16168 (eval-after-load "session"
16169 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16171 ;;;; Experimental code
16173 (defun org-closed-in-range ()
16174 "Sparse tree of items closed in a certain time range.
16175 Still experimental, may disappear in the future."
16176 (interactive)
16177 ;; Get the time interval from the user.
16178 (let* ((time1 (time-to-seconds
16179 (org-read-date nil 'to-time nil "Starting date: ")))
16180 (time2 (time-to-seconds
16181 (org-read-date nil 'to-time nil "End date:")))
16182 ;; callback function
16183 (callback (lambda ()
16184 (let ((time
16185 (time-to-seconds
16186 (apply 'encode-time
16187 (org-parse-time-string
16188 (match-string 1))))))
16189 ;; check if time in interval
16190 (and (>= time time1) (<= time time2))))))
16191 ;; make tree, check each match with the callback
16192 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16194 ;;;; Finish up
16196 (provide 'org)
16198 (run-hooks 'org-load-hook)
16200 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16202 ;;; org.el ends here