Moving subtrees: Speedup when many siblings exist.
[org-mode/org-tableheadings.git] / lisp / org.el
blob80ff0c2248a531c0c2da83adcd689cf11a4c1921
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.28trans
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-src)
92 (require 'org-footnote)
94 ;;;; Customization variables
96 ;;; Version
98 (defconst org-version "6.28trans"
99 "The version number of the file org.el.")
101 (defun org-version (&optional here)
102 "Show the org-mode version in the echo area.
103 With prefix arg HERE, insert it at point."
104 (interactive "P")
105 (let ((version (format "Org-mode version %s" org-version)))
106 (message version)
107 (if here
108 (insert version))))
110 ;;; Compatibility constants
112 ;;; The custom variables
114 (defgroup org nil
115 "Outline-based notes management and organizer."
116 :tag "Org"
117 :group 'outlines
118 :group 'hypermedia
119 :group 'calendar)
121 (defcustom org-load-hook nil
122 "Hook that is run after org.el has been loaded."
123 :group 'org
124 :type 'hook)
126 (defvar org-modules) ; defined below
127 (defvar org-modules-loaded nil
128 "Have the modules been loaded already?")
130 (defun org-load-modules-maybe (&optional force)
131 "Load all extensions listed in `org-modules'."
132 (when (or force (not org-modules-loaded))
133 (mapc (lambda (ext)
134 (condition-case nil (require ext)
135 (error (message "Problems while trying to load feature `%s'" ext))))
136 org-modules)
137 (setq org-modules-loaded t)))
139 (defun org-set-modules (var value)
140 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
141 (set var value)
142 (when (featurep 'org)
143 (org-load-modules-maybe 'force)))
145 (when (org-bound-and-true-p org-modules)
146 (let ((a (member 'org-infojs org-modules)))
147 (and a (setcar a 'org-jsinfo))))
149 (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)
150 "Modules that should always be loaded together with org.el.
151 If a description starts with <C>, the file is not part of Emacs
152 and loading it will require that you have downloaded and properly installed
153 the org-mode distribution.
155 You can also use this system to load external packages (i.e. neither Org
156 core modules, not modules from the CONTRIB directory). Just add symbols
157 to the end of the list. If the package is called org-xyz.el, then you need
158 to add the symbol `xyz', and the package must have a call to
160 (provide 'org-xyz)"
161 :group 'org
162 :set 'org-set-modules
163 :type
164 '(set :greedy t
165 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
166 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
167 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
168 (const :tag " id: Global IDs for identifying entries" org-id)
169 (const :tag " info: Links to Info nodes" org-info)
170 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
171 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
172 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
173 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
174 (const :tag " mew Links to Mew folders/messages" org-mew)
175 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
176 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
177 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
178 (const :tag " vm: Links to VM folders/messages" org-vm)
179 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
180 (const :tag " w3m: Special cut/paste from w3m to Org." org-w3m)
181 (const :tag " mouse: Additional mouse support" org-mouse)
183 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
184 (const :tag "C annotation-helper: Call Remember directly from Browser (OBSOLETE, use org-protocol)" org-annotation-helper)
185 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
186 (const :tag "C browser-url: Store link, directly from Browser (OBSOLETE, use org-protocol)" org-browser-url)
187 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
188 (const :tag "C collector: Collect properties into tables" org-collector)
189 (const :tag "C depend: TODO dependencies for Org-mode (PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
190 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
191 (const :tag "C eval: Include command output as text" org-eval)
192 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
193 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
194 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
195 (const :tag "C interactive-query: Interactive modification of tags query (PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
196 (const :tag "C jira Add a jira:ticket protocol to Org" org-jira)
197 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
198 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
199 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
200 (const :tag "C mtags: Support for muse-like tags" org-mtags)
201 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
202 (const :tag "C R: Computation using the R language" org-R)
203 (const :tag "C registry: A registry for Org links" org-registry)
204 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
205 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
206 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
207 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
208 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
209 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
211 (defcustom org-support-shift-select nil
212 "Non-nil means, make shift-cursor commands select text when possible.
214 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
215 selecting a region, or enlarge thusly regions started in this way.
216 In Org-mode, in special contexts, these same keys are used for other
217 purposes, important enough to compete with shift selection. Org tries
218 to balance these needs by supporting `shift-select-mode' outside these
219 special contexts, under control of this variable.
221 The default of this variable is nil, to avoid confusing behavior. Shifted
222 cursor keys will then execute Org commands in the following contexts:
223 - on a headline, changing TODO state (left/right) and priority (up/down)
224 - on a time stamp, changing the time
225 - in a plain list item, changing the bullet type
226 - in a property definition line, switching between allowed values
227 - in the BEGIN line of a clock table (changing the time block).
228 Outside these contexts, the commands will throw an error.
230 When this variable is t and the cursor is not in a special context,
231 Org-mode will support shift-selection for making and enlarging regions.
232 To make this more effective, the bullet cycling will no longer happen
233 anywhere in an item line, but only if the cursor is exactly on the bullet.
235 If you set this variable to the symbol `always', then the keys
236 will not be special in headlines, property lines, and item lines, to make
237 shift selection work there as well. If this is what you want, you can
238 use the following alternative commands: `C-c C-t' and `C-c ,' to
239 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
240 TODO sets, `C-c -' to cycle item bullet types, and properties can be
241 edited by hand or in column view.
243 However, when the cursor is on a timestamp, shift-cursor commands
244 will still edit the time stamp - this is just too good to give up.
246 XEmacs user should have this variable set to nil, because shift-select-mode
247 is Emacs 23 only."
248 :group 'org
249 :type '(choice
250 (const :tag "Never" nil)
251 (const :tag "When outside special context" t)
252 (const :tag "Everywhere except timestamps" always)))
254 (defgroup org-startup nil
255 "Options concerning startup of Org-mode."
256 :tag "Org Startup"
257 :group 'org)
259 (defcustom org-startup-folded t
260 "Non-nil means, entering Org-mode will switch to OVERVIEW.
261 This can also be configured on a per-file basis by adding one of
262 the following lines anywhere in the buffer:
264 #+STARTUP: fold
265 #+STARTUP: nofold
266 #+STARTUP: content"
267 :group 'org-startup
268 :type '(choice
269 (const :tag "nofold: show all" nil)
270 (const :tag "fold: overview" t)
271 (const :tag "content: all headlines" content)))
273 (defcustom org-startup-truncated t
274 "Non-nil means, entering Org-mode will set `truncate-lines'.
275 This is useful since some lines containing links can be very long and
276 uninteresting. Also tables look terrible when wrapped."
277 :group 'org-startup
278 :type 'boolean)
280 (defcustom org-startup-align-all-tables nil
281 "Non-nil means, align all tables when visiting a file.
282 This is useful when the column width in tables is forced with <N> cookies
283 in table fields. Such tables will look correct only after the first re-align.
284 This can also be configured on a per-file basis by adding one of
285 the following lines anywhere in the buffer:
286 #+STARTUP: align
287 #+STARTUP: noalign"
288 :group 'org-startup
289 :type 'boolean)
291 (defcustom org-insert-mode-line-in-empty-file nil
292 "Non-nil means insert the first line setting Org-mode in empty files.
293 When the function `org-mode' is called interactively in an empty file, this
294 normally means that the file name does not automatically trigger Org-mode.
295 To ensure that the file will always be in Org-mode in the future, a
296 line enforcing Org-mode will be inserted into the buffer, if this option
297 has been set."
298 :group 'org-startup
299 :type 'boolean)
301 (defcustom org-replace-disputed-keys nil
302 "Non-nil means use alternative key bindings for some keys.
303 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
304 These keys are also used by other packages like shift-selection-mode'
305 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
306 If you want to use Org-mode together with one of these other modes,
307 or more generally if you would like to move some Org-mode commands to
308 other keys, set this variable and configure the keys with the variable
309 `org-disputed-keys'.
311 This option is only relevant at load-time of Org-mode, and must be set
312 *before* org.el is loaded. Changing it requires a restart of Emacs to
313 become effective."
314 :group 'org-startup
315 :type 'boolean)
317 (defcustom org-use-extra-keys nil
318 "Non-nil means use extra key sequence definitions for certain
319 commands. This happens automatically if you run XEmacs or if
320 window-system is nil. This variable lets you do the same
321 manually. You must set it before loading org.
323 Example: on Carbon Emacs 22 running graphically, with an external
324 keyboard on a Powerbook, the default way of setting M-left might
325 not work for either Alt or ESC. Setting this variable will make
326 it work for ESC."
327 :group 'org-startup
328 :type 'boolean)
330 (if (fboundp 'defvaralias)
331 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
333 (defcustom org-disputed-keys
334 '(([(shift up)] . [(meta p)])
335 ([(shift down)] . [(meta n)])
336 ([(shift left)] . [(meta -)])
337 ([(shift right)] . [(meta +)])
338 ([(control shift right)] . [(meta shift +)])
339 ([(control shift left)] . [(meta shift -)]))
340 "Keys for which Org-mode and other modes compete.
341 This is an alist, cars are the default keys, second element specifies
342 the alternative to use when `org-replace-disputed-keys' is t.
344 Keys can be specified in any syntax supported by `define-key'.
345 The value of this option takes effect only at Org-mode's startup,
346 therefore you'll have to restart Emacs to apply it after changing."
347 :group 'org-startup
348 :type 'alist)
350 (defun org-key (key)
351 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
352 Or return the original if not disputed."
353 (if org-replace-disputed-keys
354 (let* ((nkey (key-description key))
355 (x (org-find-if (lambda (x)
356 (equal (key-description (car x)) nkey))
357 org-disputed-keys)))
358 (if x (cdr x) key))
359 key))
361 (defun org-find-if (predicate seq)
362 (catch 'exit
363 (while seq
364 (if (funcall predicate (car seq))
365 (throw 'exit (car seq))
366 (pop seq)))))
368 (defun org-defkey (keymap key def)
369 "Define a key, possibly translated, as returned by `org-key'."
370 (define-key keymap (org-key key) def))
372 (defcustom org-ellipsis nil
373 "The ellipsis to use in the Org-mode outline.
374 When nil, just use the standard three dots. When a string, use that instead,
375 When a face, use the standard 3 dots, but with the specified face.
376 The change affects only Org-mode (which will then use its own display table).
377 Changing this requires executing `M-x org-mode' in a buffer to become
378 effective."
379 :group 'org-startup
380 :type '(choice (const :tag "Default" nil)
381 (face :tag "Face" :value org-warning)
382 (string :tag "String" :value "...#")))
384 (defvar org-display-table nil
385 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
387 (defgroup org-keywords nil
388 "Keywords in Org-mode."
389 :tag "Org Keywords"
390 :group 'org)
392 (defcustom org-deadline-string "DEADLINE:"
393 "String to mark deadline entries.
394 A deadline is this string, followed by a time stamp. Should be a word,
395 terminated by a colon. You can insert a schedule keyword and
396 a timestamp with \\[org-deadline].
397 Changes become only effective after restarting Emacs."
398 :group 'org-keywords
399 :type 'string)
401 (defcustom org-scheduled-string "SCHEDULED:"
402 "String to mark scheduled TODO entries.
403 A schedule is this string, followed by a time stamp. Should be a word,
404 terminated by a colon. You can insert a schedule keyword and
405 a timestamp with \\[org-schedule].
406 Changes become only effective after restarting Emacs."
407 :group 'org-keywords
408 :type 'string)
410 (defcustom org-closed-string "CLOSED:"
411 "String used as the prefix for timestamps logging closing a TODO entry."
412 :group 'org-keywords
413 :type 'string)
415 (defcustom org-clock-string "CLOCK:"
416 "String used as prefix for timestamps clocking work hours on an item."
417 :group 'org-keywords
418 :type 'string)
420 (defcustom org-comment-string "COMMENT"
421 "Entries starting with this keyword will never be exported.
422 An entry can be toggled between COMMENT and normal with
423 \\[org-toggle-comment].
424 Changes become only effective after restarting Emacs."
425 :group 'org-keywords
426 :type 'string)
428 (defcustom org-quote-string "QUOTE"
429 "Entries starting with this keyword will be exported in fixed-width font.
430 Quoting applies only to the text in the entry following the headline, and does
431 not extend beyond the next headline, even if that is lower level.
432 An entry can be toggled between QUOTE and normal with
433 \\[org-toggle-fixed-width-section]."
434 :group 'org-keywords
435 :type 'string)
437 (defconst org-repeat-re
438 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
439 "Regular expression for specifying repeated events.
440 After a match, group 1 contains the repeat expression.")
442 (defgroup org-structure nil
443 "Options concerning the general structure of Org-mode files."
444 :tag "Org Structure"
445 :group 'org)
447 (defgroup org-reveal-location nil
448 "Options about how to make context of a location visible."
449 :tag "Org Reveal Location"
450 :group 'org-structure)
452 (defconst org-context-choice
453 '(choice
454 (const :tag "Always" t)
455 (const :tag "Never" nil)
456 (repeat :greedy t :tag "Individual contexts"
457 (cons
458 (choice :tag "Context"
459 (const agenda)
460 (const org-goto)
461 (const occur-tree)
462 (const tags-tree)
463 (const link-search)
464 (const mark-goto)
465 (const bookmark-jump)
466 (const isearch)
467 (const default))
468 (boolean))))
469 "Contexts for the reveal options.")
471 (defcustom org-show-hierarchy-above '((default . t))
472 "Non-nil means, show full hierarchy when revealing a location.
473 Org-mode often shows locations in an org-mode file which might have
474 been invisible before. When this is set, the hierarchy of headings
475 above the exposed location is shown.
476 Turning this off for example for sparse trees makes them very compact.
477 Instead of t, this can also be an alist specifying this option for different
478 contexts. Valid contexts are
479 agenda when exposing an entry from the agenda
480 org-goto when using the command `org-goto' on key C-c C-j
481 occur-tree when using the command `org-occur' on key C-c /
482 tags-tree when constructing a sparse tree based on tags matches
483 link-search when exposing search matches associated with a link
484 mark-goto when exposing the jump goal of a mark
485 bookmark-jump when exposing a bookmark location
486 isearch when exiting from an incremental search
487 default default for all contexts not set explicitly"
488 :group 'org-reveal-location
489 :type org-context-choice)
491 (defcustom org-show-following-heading '((default . nil))
492 "Non-nil means, show following heading when revealing a location.
493 Org-mode often shows locations in an org-mode file which might have
494 been invisible before. When this is set, the heading following the
495 match is shown.
496 Turning this off for example for sparse trees makes them very compact,
497 but makes it harder to edit the location of the match. In such a case,
498 use the command \\[org-reveal] to show more context.
499 Instead of t, this can also be an alist specifying this option for different
500 contexts. See `org-show-hierarchy-above' for valid contexts."
501 :group 'org-reveal-location
502 :type org-context-choice)
504 (defcustom org-show-siblings '((default . nil) (isearch t))
505 "Non-nil means, show all sibling heading when revealing a location.
506 Org-mode often shows locations in an org-mode file which might have
507 been invisible before. When this is set, the sibling of the current entry
508 heading are all made visible. If `org-show-hierarchy-above' is t,
509 the same happens on each level of the hierarchy above the current entry.
511 By default this is on for the isearch context, off for all other contexts.
512 Turning this off for example for sparse trees makes them very compact,
513 but makes it harder to edit the location of the match. In such a case,
514 use the command \\[org-reveal] to show more context.
515 Instead of t, this can also be an alist specifying this option for different
516 contexts. See `org-show-hierarchy-above' for valid contexts."
517 :group 'org-reveal-location
518 :type org-context-choice)
520 (defcustom org-show-entry-below '((default . nil))
521 "Non-nil means, show the entry below a headline when revealing a location.
522 Org-mode often shows locations in an org-mode file which might have
523 been invisible before. When this is set, the text below the headline that is
524 exposed is also shown.
526 By default this is off for all contexts.
527 Instead of t, this can also be an alist specifying this option for different
528 contexts. See `org-show-hierarchy-above' for valid contexts."
529 :group 'org-reveal-location
530 :type org-context-choice)
532 (defcustom org-indirect-buffer-display 'other-window
533 "How should indirect tree buffers be displayed?
534 This applies to indirect buffers created with the commands
535 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
536 Valid values are:
537 current-window Display in the current window
538 other-window Just display in another window.
539 dedicated-frame Create one new frame, and re-use it each time.
540 new-frame Make a new frame each time. Note that in this case
541 previously-made indirect buffers are kept, and you need to
542 kill these buffers yourself."
543 :group 'org-structure
544 :group 'org-agenda-windows
545 :type '(choice
546 (const :tag "In current window" current-window)
547 (const :tag "In current frame, other window" other-window)
548 (const :tag "Each time a new frame" new-frame)
549 (const :tag "One dedicated frame" dedicated-frame)))
551 (defgroup org-cycle nil
552 "Options concerning visibility cycling in Org-mode."
553 :tag "Org Cycle"
554 :group 'org-structure)
556 (defcustom org-cycle-max-level nil
557 "Maximum level which should still be subject to visibility cycling.
558 Levels higher than this will, for cycling, be treated as text, not a headline.
559 When `org-odd-levels-only' is set, a value of N in this variable actually
560 means 2N-1 stars as the limiting headline.
561 When nil, cycle all levels.
562 Note that the limiting level of cycling is also influenced by
563 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
564 `org-inlinetask-min-level' is, cycling will be limited to levels one less
565 than its value."
566 :group 'org-cycle
567 :type '(choice
568 (const :tag "No limit" nil)
569 (integer :tag "Maximum level")))
571 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
572 "Names of drawers. Drawers are not opened by cycling on the headline above.
573 Drawers only open with a TAB on the drawer line itself. A drawer looks like
574 this:
575 :DRAWERNAME:
576 .....
577 :END:
578 The drawer \"PROPERTIES\" is special for capturing properties through
579 the property API.
581 Drawers can be defined on the per-file basis with a line like:
583 #+DRAWERS: HIDDEN STATE PROPERTIES"
584 :group 'org-structure
585 :group 'org-cycle
586 :type '(repeat (string :tag "Drawer Name")))
588 (defcustom org-hide-block-startup nil
589 "Non-nil means, , entering Org-mode will fold all blocks.
590 This can also be set in on a per-file basis with
592 #+STARTUP: hideblocks
593 #+STARTUP: showblocks"
594 :group 'org-startup
595 :group 'org-cycle
596 :type 'boolean)
598 (defcustom org-cycle-global-at-bob nil
599 "Cycle globally if cursor is at beginning of buffer and not at a headline.
600 This makes it possible to do global cycling without having to use S-TAB or
601 C-u TAB. For this special case to work, the first line of the buffer
602 must not be a headline - it may be empty or some other text. When used in
603 this way, `org-cycle-hook' is disables temporarily, to make sure the
604 cursor stays at the beginning of the buffer.
605 When this option is nil, don't do anything special at the beginning
606 of the buffer."
607 :group 'org-cycle
608 :type 'boolean)
610 (defcustom org-cycle-emulate-tab t
611 "Where should `org-cycle' emulate TAB.
612 nil Never
613 white Only in completely white lines
614 whitestart Only at the beginning of lines, before the first non-white char
615 t Everywhere except in headlines
616 exc-hl-bol Everywhere except at the start of a headline
617 If TAB is used in a place where it does not emulate TAB, the current subtree
618 visibility is cycled."
619 :group 'org-cycle
620 :type '(choice (const :tag "Never" nil)
621 (const :tag "Only in completely white lines" white)
622 (const :tag "Before first char in a line" whitestart)
623 (const :tag "Everywhere except in headlines" t)
624 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
627 (defcustom org-cycle-separator-lines 2
628 "Number of empty lines needed to keep an empty line between collapsed trees.
629 If you leave an empty line between the end of a subtree and the following
630 headline, this empty line is hidden when the subtree is folded.
631 Org-mode will leave (exactly) one empty line visible if the number of
632 empty lines is equal or larger to the number given in this variable.
633 So the default 2 means, at least 2 empty lines after the end of a subtree
634 are needed to produce free space between a collapsed subtree and the
635 following headline.
637 Special case: when 0, never leave empty lines in collapsed view."
638 :group 'org-cycle
639 :type 'integer)
640 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
642 (defcustom org-pre-cycle-hook nil
643 "Hook that is run before visibility cycling is happening.
644 The function(s) in this hook must accept a single argument which indicates
645 the new state that will be set right after running this hook. The
646 argument is a symbol. Before a global state change, it can have the values
647 `overview', `content', or `all'. Before a local state change, it can have
648 the values `folded', `children', or `subtree'."
649 :group 'org-cycle
650 :type 'hook)
652 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
653 org-cycle-hide-drawers
654 org-cycle-show-empty-lines
655 org-optimize-window-after-visibility-change)
656 "Hook that is run after `org-cycle' has changed the buffer visibility.
657 The function(s) in this hook must accept a single argument which indicates
658 the new state that was set by the most recent `org-cycle' command. The
659 argument is a symbol. After a global state change, it can have the values
660 `overview', `content', or `all'. After a local state change, it can have
661 the values `folded', `children', or `subtree'."
662 :group 'org-cycle
663 :type 'hook)
665 (defgroup org-edit-structure nil
666 "Options concerning structure editing in Org-mode."
667 :tag "Org Edit Structure"
668 :group 'org-structure)
670 (defcustom org-odd-levels-only nil
671 "Non-nil means, skip even levels and only use odd levels for the outline.
672 This has the effect that two stars are being added/taken away in
673 promotion/demotion commands. It also influences how levels are
674 handled by the exporters.
675 Changing it requires restart of `font-lock-mode' to become effective
676 for fontification also in regions already fontified.
677 You may also set this on a per-file basis by adding one of the following
678 lines to the buffer:
680 #+STARTUP: odd
681 #+STARTUP: oddeven"
682 :group 'org-edit-structure
683 :group 'org-font-lock
684 :type 'boolean)
686 (defcustom org-adapt-indentation t
687 "Non-nil means, adapt indentation to outline node level.
689 When this variable is set, Org assumes that you write outlines by
690 indenting text in each node to align with the headline (after the stars).
691 The following issues are influenced by this variable:
693 - When this is set and the *entire* text in an entry is indented, the
694 indentation is increased by one space in a demotion command, and
695 decreased by one in a promotion command. If any line in the entry
696 body starts at column 0, indentation is not changed at all.
698 - Property drawers and planning information is inserted indented when
699 this variable s set. When nil, they will not be indented.
701 - TAB indents a line relative to context. The lines below a headline
702 will be indented when this variable is set.
704 Note that this is all about true indentation, by adding and removing
705 spaces. See also `org-indent.el' which does level-dependent indentation
706 in a virtual way, i.e. only for display in Emacs."
707 :group 'org-edit-structure
708 :type 'boolean)
710 (defcustom org-special-ctrl-a/e nil
711 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
713 When t, `C-a' will bring back the cursor to the beginning of the
714 headline text, i.e. after the stars and after a possible TODO keyword.
715 In an item, this will be the position after the bullet.
716 When the cursor is already at that position, another `C-a' will bring
717 it to the beginning of the line.
719 `C-e' will jump to the end of the headline, ignoring the presence of tags
720 in the headline. A second `C-e' will then jump to the true end of the
721 line, after any tags.
723 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
724 and only a directly following, identical keypress will bring the cursor
725 to the special positions.
727 This may also be a cons cell where the behavior for `C-a' and `C-e' is
728 set separately."
729 :group 'org-edit-structure
730 :type '(choice
731 (const :tag "off" nil)
732 (const :tag "after stars/bullet and before tags first" t)
733 (const :tag "true line boundary first" reversed)
734 (cons :tag "Set C-a and C-e separately"
735 (choice :tag "Special C-a"
736 (const :tag "off" nil)
737 (const :tag "after stars/bullet first" t)
738 (const :tag "before stars/bullet first" reversed))
739 (choice :tag "Special C-e"
740 (const :tag "off" nil)
741 (const :tag "before tags first" t)
742 (const :tag "after tags first" reversed)))))
743 (if (fboundp 'defvaralias)
744 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
746 (defcustom org-special-ctrl-k nil
747 "Non-nil means `C-k' will behave specially in headlines.
748 When nil, `C-k' will call the default `kill-line' command.
749 When t, the following will happen while the cursor is in the headline:
751 - When the cursor is at the beginning of a headline, kill the entire
752 line and possible the folded subtree below the line.
753 - When in the middle of the headline text, kill the headline up to the tags.
754 - When after the headline text, kill the tags."
755 :group 'org-edit-structure
756 :type 'boolean)
758 (defcustom org-yank-folded-subtrees t
759 "Non-nil means, when yanking subtrees, fold them.
760 If the kill is a single subtree, or a sequence of subtrees, i.e. if
761 it starts with a heading and all other headings in it are either children
762 or siblings, then fold all the subtrees. However, do this only if no
763 text after the yank would be swallowed into a folded tree by this action."
764 :group 'org-edit-structure
765 :type 'boolean)
767 (defcustom org-yank-adjusted-subtrees nil
768 "Non-nil means, when yanking subtrees, adjust the level.
769 With this setting, `org-paste-subtree' is used to insert the subtree, see
770 this function for details."
771 :group 'org-edit-structure
772 :type 'boolean)
774 (defcustom org-M-RET-may-split-line '((default . t))
775 "Non-nil means, M-RET will split the line at the cursor position.
776 When nil, it will go to the end of the line before making a
777 new line.
778 You may also set this option in a different way for different
779 contexts. Valid contexts are:
781 headline when creating a new headline
782 item when creating a new item
783 table in a table field
784 default the value to be used for all contexts not explicitly
785 customized"
786 :group 'org-structure
787 :group 'org-table
788 :type '(choice
789 (const :tag "Always" t)
790 (const :tag "Never" nil)
791 (repeat :greedy t :tag "Individual contexts"
792 (cons
793 (choice :tag "Context"
794 (const headline)
795 (const item)
796 (const table)
797 (const default))
798 (boolean)))))
801 (defcustom org-insert-heading-respect-content nil
802 "Non-nil means, insert new headings after the current subtree.
803 When nil, the new heading is created directly after the current line.
804 The commands \\[org-insert-heading-respect-content] and
805 \\[org-insert-todo-heading-respect-content] turn this variable on
806 for the duration of the command."
807 :group 'org-structure
808 :type 'boolean)
810 (defcustom org-blank-before-new-entry '((heading . auto)
811 (plain-list-item . auto))
812 "Should `org-insert-heading' leave a blank line before new heading/item?
813 The value is an alist, with `heading' and `plain-list-item' as car,
814 and a boolean flag as cdr. For plain lists, if the variable
815 `org-empty-line-terminates-plain-lists' is set, the setting here
816 is ignored and no empty line is inserted, to keep the list in tact."
817 :group 'org-edit-structure
818 :type '(list
819 (cons (const heading)
820 (choice (const :tag "Never" nil)
821 (const :tag "Always" t)
822 (const :tag "Auto" auto)))
823 (cons (const plain-list-item)
824 (choice (const :tag "Never" nil)
825 (const :tag "Always" t)
826 (const :tag "Auto" auto)))))
828 (defcustom org-insert-heading-hook nil
829 "Hook being run after inserting a new heading."
830 :group 'org-edit-structure
831 :type 'hook)
833 (defcustom org-enable-fixed-width-editor t
834 "Non-nil means, lines starting with \":\" are treated as fixed-width.
835 This currently only means, they are never auto-wrapped.
836 When nil, such lines will be treated like ordinary lines.
837 See also the QUOTE keyword."
838 :group 'org-edit-structure
839 :type 'boolean)
842 (defcustom org-goto-auto-isearch t
843 "Non-nil means, typing characters in org-goto starts incremental search."
844 :group 'org-edit-structure
845 :type 'boolean)
847 (defgroup org-sparse-trees nil
848 "Options concerning sparse trees in Org-mode."
849 :tag "Org Sparse Trees"
850 :group 'org-structure)
852 (defcustom org-highlight-sparse-tree-matches t
853 "Non-nil means, highlight all matches that define a sparse tree.
854 The highlights will automatically disappear the next time the buffer is
855 changed by an edit command."
856 :group 'org-sparse-trees
857 :type 'boolean)
859 (defcustom org-remove-highlights-with-change t
860 "Non-nil means, any change to the buffer will remove temporary highlights.
861 Such highlights are created by `org-occur' and `org-clock-display'.
862 When nil, `C-c C-c needs to be used to get rid of the highlights.
863 The highlights created by `org-preview-latex-fragment' always need
864 `C-c C-c' to be removed."
865 :group 'org-sparse-trees
866 :group 'org-time
867 :type 'boolean)
870 (defcustom org-occur-hook '(org-first-headline-recenter)
871 "Hook that is run after `org-occur' has constructed a sparse tree.
872 This can be used to recenter the window to show as much of the structure
873 as possible."
874 :group 'org-sparse-trees
875 :type 'hook)
877 (defgroup org-imenu-and-speedbar nil
878 "Options concerning imenu and speedbar in Org-mode."
879 :tag "Org Imenu and Speedbar"
880 :group 'org-structure)
882 (defcustom org-imenu-depth 2
883 "The maximum level for Imenu access to Org-mode headlines.
884 This also applied for speedbar access."
885 :group 'org-imenu-and-speedbar
886 :type 'integer)
888 (defgroup org-table nil
889 "Options concerning tables in Org-mode."
890 :tag "Org Table"
891 :group 'org)
893 (defcustom org-enable-table-editor 'optimized
894 "Non-nil means, lines starting with \"|\" are handled by the table editor.
895 When nil, such lines will be treated like ordinary lines.
897 When equal to the symbol `optimized', the table editor will be optimized to
898 do the following:
899 - Automatic overwrite mode in front of whitespace in table fields.
900 This makes the structure of the table stay in tact as long as the edited
901 field does not exceed the column width.
902 - Minimize the number of realigns. Normally, the table is aligned each time
903 TAB or RET are pressed to move to another field. With optimization this
904 happens only if changes to a field might have changed the column width.
905 Optimization requires replacing the functions `self-insert-command',
906 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
907 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
908 very good at guessing when a re-align will be necessary, but you can always
909 force one with \\[org-ctrl-c-ctrl-c].
911 If you would like to use the optimized version in Org-mode, but the
912 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
914 This variable can be used to turn on and off the table editor during a session,
915 but in order to toggle optimization, a restart is required.
917 See also the variable `org-table-auto-blank-field'."
918 :group 'org-table
919 :type '(choice
920 (const :tag "off" nil)
921 (const :tag "on" t)
922 (const :tag "on, optimized" optimized)))
924 (defcustom org-self-insert-cluster-for-undo t
925 "Non-nil means cluster self-insert commands for undo when possible.
926 If this is set, then, like in the Emacs command loop, 20 consequtive
927 characters will be undone together.
928 This is configurable, because there is some impact on typing performance."
929 :group 'org-table
930 :type 'boolean)
932 (defcustom org-table-tab-recognizes-table.el t
933 "Non-nil means, TAB will automatically notice a table.el table.
934 When it sees such a table, it moves point into it and - if necessary -
935 calls `table-recognize-table'."
936 :group 'org-table-editing
937 :type 'boolean)
939 (defgroup org-link nil
940 "Options concerning links in Org-mode."
941 :tag "Org Link"
942 :group 'org)
944 (defvar org-link-abbrev-alist-local nil
945 "Buffer-local version of `org-link-abbrev-alist', which see.
946 The value of this is taken from the #+LINK lines.")
947 (make-variable-buffer-local 'org-link-abbrev-alist-local)
949 (defcustom org-link-abbrev-alist nil
950 "Alist of link abbreviations.
951 The car of each element is a string, to be replaced at the start of a link.
952 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
953 links in Org-mode buffers can have an optional tag after a double colon, e.g.
955 [[linkkey:tag][description]]
957 The 'linkkey' must be a word word, starting with a letter, followed
958 by letters, numbers, '-' or '_'.
960 If REPLACE is a string, the tag will simply be appended to create the link.
961 If the string contains \"%s\", the tag will be inserted there. Alternatively,
962 the placeholder \"%h\" will cause a url-encoded version of the tag to
963 be inserted at that point (see the function `url-hexify-string').
965 REPLACE may also be a function that will be called with the tag as the
966 only argument to create the link, which should be returned as a string.
968 See the manual for examples."
969 :group 'org-link
970 :type '(repeat
971 (cons
972 (string :tag "Protocol")
973 (choice
974 (string :tag "Format")
975 (function)))))
977 (defcustom org-descriptive-links t
978 "Non-nil means, hide link part and only show description of bracket links.
979 Bracket links are like [[link][description]]. This variable sets the initial
980 state in new org-mode buffers. The setting can then be toggled on a
981 per-buffer basis from the Org->Hyperlinks menu."
982 :group 'org-link
983 :type 'boolean)
985 (defcustom org-link-file-path-type 'adaptive
986 "How the path name in file links should be stored.
987 Valid values are:
989 relative Relative to the current directory, i.e. the directory of the file
990 into which the link is being inserted.
991 absolute Absolute path, if possible with ~ for home directory.
992 noabbrev Absolute path, no abbreviation of home directory.
993 adaptive Use relative path for files in the current directory and sub-
994 directories of it. For other files, use an absolute path."
995 :group 'org-link
996 :type '(choice
997 (const relative)
998 (const absolute)
999 (const noabbrev)
1000 (const adaptive)))
1002 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1003 "Types of links that should be activated in Org-mode files.
1004 This is a list of symbols, each leading to the activation of a certain link
1005 type. In principle, it does not hurt to turn on most link types - there may
1006 be a small gain when turning off unused link types. The types are:
1008 bracket The recommended [[link][description]] or [[link]] links with hiding.
1009 angular Links in angular brackets that may contain whitespace like
1010 <bbdb:Carsten Dominik>.
1011 plain Plain links in normal text, no whitespace, like http://google.com.
1012 radio Text that is matched by a radio target, see manual for details.
1013 tag Tag settings in a headline (link to tag search).
1014 date Time stamps (link to calendar).
1015 footnote Footnote labels.
1017 Changing this variable requires a restart of Emacs to become effective."
1018 :group 'org-link
1019 :type '(set :greedy t
1020 (const :tag "Double bracket links (new style)" bracket)
1021 (const :tag "Angular bracket links (old style)" angular)
1022 (const :tag "Plain text links" plain)
1023 (const :tag "Radio target matches" radio)
1024 (const :tag "Tags" tag)
1025 (const :tag "Timestamps" date)
1026 (const :tag "Footnotes" footnote)))
1028 (defcustom org-make-link-description-function nil
1029 "Function to use to generate link descriptions from links. If
1030 nil the link location will be used. This function must take two
1031 parameters; the first is the link and the second the description
1032 org-insert-link has generated, and should return the description
1033 to use."
1034 :group 'org-link
1035 :type 'function)
1037 (defgroup org-link-store nil
1038 "Options concerning storing links in Org-mode."
1039 :tag "Org Store Link"
1040 :group 'org-link)
1042 (defcustom org-email-link-description-format "Email %c: %.30s"
1043 "Format of the description part of a link to an email or usenet message.
1044 The following %-escapes will be replaced by corresponding information:
1046 %F full \"From\" field
1047 %f name, taken from \"From\" field, address if no name
1048 %T full \"To\" field
1049 %t first name in \"To\" field, address if no name
1050 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1051 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1052 %s subject
1053 %m message-id.
1055 You may use normal field width specification between the % and the letter.
1056 This is for example useful to limit the length of the subject.
1058 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1059 :group 'org-link-store
1060 :type 'string)
1062 (defcustom org-from-is-user-regexp
1063 (let (r1 r2)
1064 (when (and user-mail-address (not (string= user-mail-address "")))
1065 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1066 (when (and user-full-name (not (string= user-full-name "")))
1067 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1068 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1069 "Regexp matched against the \"From:\" header of an email or usenet message.
1070 It should match if the message is from the user him/herself."
1071 :group 'org-link-store
1072 :type 'regexp)
1074 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1075 "Non-nil means, storing a link to an Org file will use entry IDs.
1077 Note that before this variable is even considered, org-id must be loaded,
1078 so please customize `org-modules' and turn it on.
1080 The variable can have the following values:
1082 t Create an ID if needed to make a link to the current entry.
1084 create-if-interactive
1085 If `org-store-link' is called directly (interactively, as a user
1086 command), do create an ID to support the link. But when doing the
1087 job for remember, only use the ID if it already exists. The
1088 purpose of this setting is to avoid proliferation of unwanted
1089 IDs, just because you happen to be in an Org file when you
1090 call `org-remember' that automatically and preemptively
1091 creates a link. If you do want to get an ID link in a remember
1092 template to an entry not having an ID, create it first by
1093 explicitly creating a link to it, using `C-c C-l' first.
1095 create-if-interactive-and-no-custom-id
1096 Like create-if-interactive, but do not create an ID if there is
1097 a CUSTOM_ID property defined in the entry. This is the default.
1099 use-existing
1100 Use existing ID, do not create one.
1102 nil Never use an ID to make a link, instead link using a text search for
1103 the headline text."
1104 :group 'org-link-store
1105 :type '(choice
1106 (const :tag "Create ID to make link" t)
1107 (const :tag "Create if storing link interactively"
1108 create-if-interactive)
1109 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1110 create-if-interactive-and-no-custom-id)
1111 (const :tag "Only use existing" use-existing)
1112 (const :tag "Do not use ID to create link" nil)))
1114 (defcustom org-context-in-file-links t
1115 "Non-nil means, file links from `org-store-link' contain context.
1116 A search string will be added to the file name with :: as separator and
1117 used to find the context when the link is activated by the command
1118 `org-open-at-point'.
1119 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1120 negates this setting for the duration of the command."
1121 :group 'org-link-store
1122 :type 'boolean)
1124 (defcustom org-keep-stored-link-after-insertion nil
1125 "Non-nil means, keep link in list for entire session.
1127 The command `org-store-link' adds a link pointing to the current
1128 location to an internal list. These links accumulate during a session.
1129 The command `org-insert-link' can be used to insert links into any
1130 Org-mode file (offering completion for all stored links). When this
1131 option is nil, every link which has been inserted once using \\[org-insert-link]
1132 will be removed from the list, to make completing the unused links
1133 more efficient."
1134 :group 'org-link-store
1135 :type 'boolean)
1137 (defgroup org-link-follow nil
1138 "Options concerning following links in Org-mode."
1139 :tag "Org Follow Link"
1140 :group 'org-link)
1142 (defcustom org-link-translation-function nil
1143 "Function to translate links with different syntax to Org syntax.
1144 This can be used to translate links created for example by the Planner
1145 or emacs-wiki packages to Org syntax.
1146 The function must accept two parameters, a TYPE containing the link
1147 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1148 which is everything after the link protocol. It should return a cons
1149 with possibly modified values of type and path.
1150 Org contains a function for this, so if you set this variable to
1151 `org-translate-link-from-planner', you should be able follow many
1152 links created by planner."
1153 :group 'org-link-follow
1154 :type 'function)
1156 (defcustom org-follow-link-hook nil
1157 "Hook that is run after a link has been followed."
1158 :group 'org-link-follow
1159 :type 'hook)
1161 (defcustom org-tab-follows-link nil
1162 "Non-nil means, on links TAB will follow the link.
1163 Needs to be set before org.el is loaded.
1164 This really should not be used, it does not make sense, and the
1165 implementation is bad."
1166 :group 'org-link-follow
1167 :type 'boolean)
1169 (defcustom org-return-follows-link nil
1170 "Non-nil means, on links RET will follow the link.
1171 Needs to be set before org.el is loaded."
1172 :group 'org-link-follow
1173 :type 'boolean)
1175 (defcustom org-mouse-1-follows-link
1176 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1177 "Non-nil means, mouse-1 on a link will follow the link.
1178 A longer mouse click will still set point. Does not work on XEmacs.
1179 Needs to be set before org.el is loaded."
1180 :group 'org-link-follow
1181 :type 'boolean)
1183 (defcustom org-mark-ring-length 4
1184 "Number of different positions to be recorded in the ring
1185 Changing this requires a restart of Emacs to work correctly."
1186 :group 'org-link-follow
1187 :type 'integer)
1189 (defcustom org-link-frame-setup
1190 '((vm . vm-visit-folder-other-frame)
1191 (gnus . gnus-other-frame)
1192 (file . find-file-other-window))
1193 "Setup the frame configuration for following links.
1194 When following a link with Emacs, it may often be useful to display
1195 this link in another window or frame. This variable can be used to
1196 set this up for the different types of links.
1197 For VM, use any of
1198 `vm-visit-folder'
1199 `vm-visit-folder-other-frame'
1200 For Gnus, use any of
1201 `gnus'
1202 `gnus-other-frame'
1203 `org-gnus-no-new-news'
1204 For FILE, use any of
1205 `find-file'
1206 `find-file-other-window'
1207 `find-file-other-frame'
1208 For the calendar, use the variable `calendar-setup'.
1209 For BBDB, it is currently only possible to display the matches in
1210 another window."
1211 :group 'org-link-follow
1212 :type '(list
1213 (cons (const vm)
1214 (choice
1215 (const vm-visit-folder)
1216 (const vm-visit-folder-other-window)
1217 (const vm-visit-folder-other-frame)))
1218 (cons (const gnus)
1219 (choice
1220 (const gnus)
1221 (const gnus-other-frame)
1222 (const org-gnus-no-new-news)))
1223 (cons (const file)
1224 (choice
1225 (const find-file)
1226 (const find-file-other-window)
1227 (const find-file-other-frame)))))
1229 (defcustom org-display-internal-link-with-indirect-buffer nil
1230 "Non-nil means, use indirect buffer to display infile links.
1231 Activating internal links (from one location in a file to another location
1232 in the same file) normally just jumps to the location. When the link is
1233 activated with a C-u prefix (or with mouse-3), the link is displayed in
1234 another window. When this option is set, the other window actually displays
1235 an indirect buffer clone of the current buffer, to avoid any visibility
1236 changes to the current buffer."
1237 :group 'org-link-follow
1238 :type 'boolean)
1240 (defcustom org-open-non-existing-files nil
1241 "Non-nil means, `org-open-file' will open non-existing files.
1242 When nil, an error will be generated.
1243 This variable applies only to external applications because they
1244 might choke on non-existing files. If the link is to a file that
1245 will be openend in Emacs, the variable is ignored."
1246 :group 'org-link-follow
1247 :type 'boolean)
1249 (defcustom org-open-directory-means-index-dot-org nil
1250 "Non-nil means, a link to a directory really means to index.org.
1251 When nil, following a directory link will run dired or open a finder/explorer
1252 window on that directory."
1253 :group 'org-link-follow
1254 :type 'boolean)
1256 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1257 "Function and arguments to call for following mailto links.
1258 This is a list with the first element being a lisp function, and the
1259 remaining elements being arguments to the function. In string arguments,
1260 %a will be replaced by the address, and %s will be replaced by the subject
1261 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1262 :group 'org-link-follow
1263 :type '(choice
1264 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1265 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1266 (const :tag "message-mail" (message-mail "%a" "%s"))
1267 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1269 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1270 "Non-nil means, ask for confirmation before executing shell links.
1271 Shell links can be dangerous: just think about a link
1273 [[shell:rm -rf ~/*][Google Search]]
1275 This link would show up in your Org-mode document as \"Google Search\",
1276 but really it would remove your entire home directory.
1277 Therefore we advise against setting this variable to nil.
1278 Just change it to `y-or-n-p' if you want to confirm with a
1279 single keystroke rather than having to type \"yes\"."
1280 :group 'org-link-follow
1281 :type '(choice
1282 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1283 (const :tag "with y-or-n (faster)" y-or-n-p)
1284 (const :tag "no confirmation (dangerous)" nil)))
1286 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1287 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1288 Elisp links can be dangerous: just think about a link
1290 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1292 This link would show up in your Org-mode document as \"Google Search\",
1293 but really it would remove your entire home directory.
1294 Therefore we advise against setting this variable to nil.
1295 Just change it to `y-or-n-p' if you want to confirm with a
1296 single keystroke rather than having to type \"yes\"."
1297 :group 'org-link-follow
1298 :type '(choice
1299 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1300 (const :tag "with y-or-n (faster)" y-or-n-p)
1301 (const :tag "no confirmation (dangerous)" nil)))
1303 (defconst org-file-apps-defaults-gnu
1304 '((remote . emacs)
1305 (system . mailcap)
1306 (t . mailcap))
1307 "Default file applications on a UNIX or GNU/Linux system.
1308 See `org-file-apps'.")
1310 (defconst org-file-apps-defaults-macosx
1311 '((remote . emacs)
1312 (t . "open %s")
1313 (system . "open %s")
1314 ("ps.gz" . "gv %s")
1315 ("eps.gz" . "gv %s")
1316 ("dvi" . "xdvi %s")
1317 ("fig" . "xfig %s"))
1318 "Default file applications on a MacOS X system.
1319 The system \"open\" is known as a default, but we use X11 applications
1320 for some files for which the OS does not have a good default.
1321 See `org-file-apps'.")
1323 (defconst org-file-apps-defaults-windowsnt
1324 (list
1325 '(remote . emacs)
1326 (cons t
1327 (list (if (featurep 'xemacs)
1328 'mswindows-shell-execute
1329 'w32-shell-execute)
1330 "open" 'file))
1331 (cons 'system
1332 (list (if (featurep 'xemacs)
1333 'mswindows-shell-execute
1334 'w32-shell-execute)
1335 "open" 'file)))
1336 "Default file applications on a Windows NT system.
1337 The system \"open\" is used for most files.
1338 See `org-file-apps'.")
1340 (defcustom org-file-apps
1342 (auto-mode . emacs)
1343 ("\\.x?html?\\'" . default)
1344 ("\\.pdf\\'" . default)
1346 "External applications for opening `file:path' items in a document.
1347 Org-mode uses system defaults for different file types, but
1348 you can use this variable to set the application for a given file
1349 extension. The entries in this list are cons cells where the car identifies
1350 files and the cdr the corresponding command. Possible values for the
1351 file identifier are
1352 \"regex\" Regular expression matched against the file name. For backward
1353 compatibility, this can also be a string with only alphanumeric
1354 characters, which is then interpreted as an extension.
1355 `directory' Matches a directory
1356 `remote' Matches a remote file, accessible through tramp or efs.
1357 Remote files most likely should be visited through Emacs
1358 because external applications cannot handle such paths.
1359 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1360 so all files Emacs knows how to handle. Using this with
1361 command `emacs' will open most files in Emacs. Beware that this
1362 will also open html files inside Emacs, unless you add
1363 (\"html\" . default) to the list as well.
1364 t Default for files not matched by any of the other options.
1365 `system' The system command to open files, like `open' on Windows
1366 and Mac OS X, and mailcap under GNU/Linux. This is the command
1367 that will be selected if you call `C-c C-o' with a double
1368 `C-u C-u' prefix.
1370 Possible values for the command are:
1371 `emacs' The file will be visited by the current Emacs process.
1372 `default' Use the default application for this file type, which is the
1373 association for t in the list, most likely in the system-specific
1374 part.
1375 This can be used to overrule an unwanted setting in the
1376 system-specific variable.
1377 `system' Use the system command for opening files, like \"open\".
1378 This command is specified by the entry whose car is `system'.
1379 Most likely, the system-specific version of this variable
1380 does define this command, but you can overrule/replace it
1381 here.
1382 string A command to be executed by a shell; %s will be replaced
1383 by the path to the file.
1384 sexp A Lisp form which will be evaluated. The file path will
1385 be available in the Lisp variable `file'.
1386 For more examples, see the system specific constants
1387 `org-file-apps-defaults-macosx'
1388 `org-file-apps-defaults-windowsnt'
1389 `org-file-apps-defaults-gnu'."
1390 :group 'org-link-follow
1391 :type '(repeat
1392 (cons (choice :value ""
1393 (string :tag "Extension")
1394 (const :tag "System command to open files" system)
1395 (const :tag "Default for unrecognized files" t)
1396 (const :tag "Remote file" remote)
1397 (const :tag "Links to a directory" directory)
1398 (const :tag "Any files that have Emacs modes"
1399 auto-mode))
1400 (choice :value ""
1401 (const :tag "Visit with Emacs" emacs)
1402 (const :tag "Use default" default)
1403 (const :tag "Use the system command" system)
1404 (string :tag "Command")
1405 (sexp :tag "Lisp form")))))
1407 (defgroup org-refile nil
1408 "Options concerning refiling entries in Org-mode."
1409 :tag "Org Refile"
1410 :group 'org)
1412 (defcustom org-directory "~/org"
1413 "Directory with org files.
1414 This is just a default location to look for Org files. There is no need
1415 at all to put your files into this directory. It is only used in the
1416 following situations:
1418 1. When a remember template specifies a target file that is not an
1419 absolute path. The path will then be interpreted relative to
1420 `org-directory'
1421 2. When a remember note is filed away in an interactive way (when exiting the
1422 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1423 with `org-directory' as the default path."
1424 :group 'org-refile
1425 :group 'org-remember
1426 :type 'directory)
1428 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1429 "Default target for storing notes.
1430 Used by the hooks for remember.el. This can be a string, or nil to mean
1431 the value of `remember-data-file'.
1432 You can set this on a per-template basis with the variable
1433 `org-remember-templates'."
1434 :group 'org-refile
1435 :group 'org-remember
1436 :type '(choice
1437 (const :tag "Default from remember-data-file" nil)
1438 file))
1440 (defcustom org-goto-interface 'outline
1441 "The default interface to be used for `org-goto'.
1442 Allowed values are:
1443 outline The interface shows an outline of the relevant file
1444 and the correct heading is found by moving through
1445 the outline or by searching with incremental search.
1446 outline-path-completion Headlines in the current buffer are offered via
1447 completion. This is the interface also used by
1448 the refile command."
1449 :group 'org-refile
1450 :type '(choice
1451 (const :tag "Outline" outline)
1452 (const :tag "Outline-path-completion" outline-path-completion)))
1454 (defcustom org-goto-max-level 5
1455 "Maximum level to be considered when running org-goto with refile interface."
1456 :group 'org-refile
1457 :type 'integer)
1459 (defcustom org-reverse-note-order nil
1460 "Non-nil means, store new notes at the beginning of a file or entry.
1461 When nil, new notes will be filed to the end of a file or entry.
1462 This can also be a list with cons cells of regular expressions that
1463 are matched against file names, and values."
1464 :group 'org-remember
1465 :group 'org-refile
1466 :type '(choice
1467 (const :tag "Reverse always" t)
1468 (const :tag "Reverse never" nil)
1469 (repeat :tag "By file name regexp"
1470 (cons regexp boolean))))
1472 (defcustom org-refile-targets nil
1473 "Targets for refiling entries with \\[org-refile].
1474 This is list of cons cells. Each cell contains:
1475 - a specification of the files to be considered, either a list of files,
1476 or a symbol whose function or variable value will be used to retrieve
1477 a file name or a list of file names. If you use `org-agenda-files' for
1478 that, all agenda files will be scanned for targets. Nil means, consider
1479 headings in the current buffer.
1480 - A specification of how to find candidate refile targets. This may be
1481 any of:
1482 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1483 This tag has to be present in all target headlines, inheritance will
1484 not be considered.
1485 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1486 todo keyword.
1487 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1488 headlines that are refiling targets.
1489 - a cons cell (:level . N). Any headline of level N is considered a target.
1490 Note that, when `org-odd-levels-only' is set, level corresponds to
1491 order in hierarchy, not to the number of stars.
1492 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1493 Note that, when `org-odd-levels-only' is set, level corresponds to
1494 order in hierarchy, not to the number of stars.
1496 You can set the variable `org-refile-target-verify-function' to a function
1497 to verify each headline found by the simple critery above.
1499 When this variable is nil, all top-level headlines in the current buffer
1500 are used, equivalent to the value `((nil . (:level . 1))'."
1501 :group 'org-refile
1502 :type '(repeat
1503 (cons
1504 (choice :value org-agenda-files
1505 (const :tag "All agenda files" org-agenda-files)
1506 (const :tag "Current buffer" nil)
1507 (function) (variable) (file))
1508 (choice :tag "Identify target headline by"
1509 (cons :tag "Specific tag" (const :value :tag) (string))
1510 (cons :tag "TODO keyword" (const :value :todo) (string))
1511 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1512 (cons :tag "Level number" (const :value :level) (integer))
1513 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1515 (defcustom org-refile-target-verify-function nil
1516 "Function to verify if the headline at point should be a refile target.
1517 The function will be called without arguments, with point at the
1518 beginning of the headline. It should return t and leave point
1519 where it is if the headline is a valid target for refiling.
1521 If the target should not be selected, the function must return nil.
1522 In addition to this, it may move point to a place from where the search
1523 should be continued. For example, the function may decide that the entire
1524 subtree of the current entry should be excluded and move point to the end
1525 of the subtree."
1526 :group 'org-refile
1527 :type 'function)
1529 (defcustom org-refile-use-outline-path nil
1530 "Non-nil means, provide refile targets as paths.
1531 So a level 3 headline will be available as level1/level2/level3.
1533 When the value is `file', also include the file name (without directory)
1534 into the path. In this case, you can also stop the completion after
1535 the file name, to get entries inserted as top level in the file.
1537 When `full-file-path', include the full file path."
1538 :group 'org-refile
1539 :type '(choice
1540 (const :tag "Not" nil)
1541 (const :tag "Yes" t)
1542 (const :tag "Start with file name" file)
1543 (const :tag "Start with full file path" full-file-path)))
1545 (defcustom org-outline-path-complete-in-steps t
1546 "Non-nil means, complete the outline path in hierarchical steps.
1547 When Org-mode uses the refile interface to select an outline path
1548 \(see variable `org-refile-use-outline-path'), the completion of
1549 the path can be done is a single go, or if can be done in steps down
1550 the headline hierarchy. Going in steps is probably the best if you
1551 do not use a special completion package like `ido' or `icicles'.
1552 However, when using these packages, going in one step can be very
1553 fast, while still showing the whole path to the entry."
1554 :group 'org-refile
1555 :type 'boolean)
1557 (defcustom org-refile-allow-creating-parent-nodes nil
1558 "Non-nil means, allow to create new nodes as refile targets.
1559 New nodes are then created by adding \"/new node name\" to the completion
1560 of an existing node. When the value of this variable is `confirm',
1561 new node creation must be confirmed by the user (recommended)
1562 When nil, the completion must match an existing entry.
1564 Note that, if the new heading is not seen by the criteria
1565 listed in `org-refile-targets', multiple instances of the same
1566 heading would be created by trying again to file under the new
1567 heading."
1568 :group 'org-refile
1569 :type '(choice
1570 (const :tag "Never" nil)
1571 (const :tag "Always" t)
1572 (const :tag "Prompt for confirmation" confirm)))
1574 (defgroup org-todo nil
1575 "Options concerning TODO items in Org-mode."
1576 :tag "Org TODO"
1577 :group 'org)
1579 (defgroup org-progress nil
1580 "Options concerning Progress logging in Org-mode."
1581 :tag "Org Progress"
1582 :group 'org-time)
1584 (defvar org-todo-interpretation-widgets
1586 (:tag "Sequence (cycling hits every state)" sequence)
1587 (:tag "Type (cycling directly to DONE)" type))
1588 "The available interpretation symbols for customizing
1589 `org-todo-keywords'.
1590 Interested libraries should add to this list.")
1592 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1593 "List of TODO entry keyword sequences and their interpretation.
1594 \\<org-mode-map>This is a list of sequences.
1596 Each sequence starts with a symbol, either `sequence' or `type',
1597 indicating if the keywords should be interpreted as a sequence of
1598 action steps, or as different types of TODO items. The first
1599 keywords are states requiring action - these states will select a headline
1600 for inclusion into the global TODO list Org-mode produces. If one of
1601 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1602 signify that no further action is necessary. If \"|\" is not found,
1603 the last keyword is treated as the only DONE state of the sequence.
1605 The command \\[org-todo] cycles an entry through these states, and one
1606 additional state where no keyword is present. For details about this
1607 cycling, see the manual.
1609 TODO keywords and interpretation can also be set on a per-file basis with
1610 the special #+SEQ_TODO and #+TYP_TODO lines.
1612 Each keyword can optionally specify a character for fast state selection
1613 \(in combination with the variable `org-use-fast-todo-selection')
1614 and specifiers for state change logging, using the same syntax
1615 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1616 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1617 indicates to record a time stamp each time this state is selected.
1619 Each keyword may also specify if a timestamp or a note should be
1620 recorded when entering or leaving the state, by adding additional
1621 characters in the parenthesis after the keyword. This looks like this:
1622 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1623 record only the time of the state change. With X and Y being either
1624 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1625 Y when leaving the state if and only if the *target* state does not
1626 define X. You may omit any of the fast-selection key or X or /Y,
1627 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1629 For backward compatibility, this variable may also be just a list
1630 of keywords - in this case the interpretation (sequence or type) will be
1631 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1632 :group 'org-todo
1633 :group 'org-keywords
1634 :type '(choice
1635 (repeat :tag "Old syntax, just keywords"
1636 (string :tag "Keyword"))
1637 (repeat :tag "New syntax"
1638 (cons
1639 (choice
1640 :tag "Interpretation"
1641 ;;Quick and dirty way to see
1642 ;;`org-todo-interpretations'. This takes the
1643 ;;place of item arguments
1644 :convert-widget
1645 (lambda (widget)
1646 (widget-put widget
1647 :args (mapcar
1648 #'(lambda (x)
1649 (widget-convert
1650 (cons 'const x)))
1651 org-todo-interpretation-widgets))
1652 widget))
1653 (repeat
1654 (string :tag "Keyword"))))))
1656 (defvar org-todo-keywords-1 nil
1657 "All TODO and DONE keywords active in a buffer.")
1658 (make-variable-buffer-local 'org-todo-keywords-1)
1659 (defvar org-todo-keywords-for-agenda nil)
1660 (defvar org-done-keywords-for-agenda nil)
1661 (defvar org-todo-keyword-alist-for-agenda nil)
1662 (defvar org-tag-alist-for-agenda nil)
1663 (defvar org-agenda-contributing-files nil)
1664 (defvar org-not-done-keywords nil)
1665 (make-variable-buffer-local 'org-not-done-keywords)
1666 (defvar org-done-keywords nil)
1667 (make-variable-buffer-local 'org-done-keywords)
1668 (defvar org-todo-heads nil)
1669 (make-variable-buffer-local 'org-todo-heads)
1670 (defvar org-todo-sets nil)
1671 (make-variable-buffer-local 'org-todo-sets)
1672 (defvar org-todo-log-states nil)
1673 (make-variable-buffer-local 'org-todo-log-states)
1674 (defvar org-todo-kwd-alist nil)
1675 (make-variable-buffer-local 'org-todo-kwd-alist)
1676 (defvar org-todo-key-alist nil)
1677 (make-variable-buffer-local 'org-todo-key-alist)
1678 (defvar org-todo-key-trigger nil)
1679 (make-variable-buffer-local 'org-todo-key-trigger)
1681 (defcustom org-todo-interpretation 'sequence
1682 "Controls how TODO keywords are interpreted.
1683 This variable is in principle obsolete and is only used for
1684 backward compatibility, if the interpretation of todo keywords is
1685 not given already in `org-todo-keywords'. See that variable for
1686 more information."
1687 :group 'org-todo
1688 :group 'org-keywords
1689 :type '(choice (const sequence)
1690 (const type)))
1692 (defcustom org-use-fast-todo-selection t
1693 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1694 This variable describes if and under what circumstances the cycling
1695 mechanism for TODO keywords will be replaced by a single-key, direct
1696 selection scheme.
1698 When nil, fast selection is never used.
1700 When the symbol `prefix', it will be used when `org-todo' is called with
1701 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1702 in an agenda buffer.
1704 When t, fast selection is used by default. In this case, the prefix
1705 argument forces cycling instead.
1707 In all cases, the special interface is only used if access keys have actually
1708 been assigned by the user, i.e. if keywords in the configuration are followed
1709 by a letter in parenthesis, like TODO(t)."
1710 :group 'org-todo
1711 :type '(choice
1712 (const :tag "Never" nil)
1713 (const :tag "By default" t)
1714 (const :tag "Only with C-u C-c C-t" prefix)))
1716 (defcustom org-provide-todo-statistics t
1717 "Non-nil means, update todo statistics after insert and toggle.
1718 When this is set, todo statistics is updated in the parent of the current
1719 entry each time a todo state is changed."
1720 :group 'org-todo
1721 :type 'boolean)
1723 (defcustom org-hierarchical-todo-statistics t
1724 "Non-nil means, TODO statistics covers just direct children.
1725 When nil, all entries in the subtree are considered.
1726 This has only an effect if `org-provide-todo-statistics' is set."
1727 :group 'org-todo
1728 :type 'boolean)
1730 (defcustom org-after-todo-state-change-hook nil
1731 "Hook which is run after the state of a TODO item was changed.
1732 The new state (a string with a TODO keyword, or nil) is available in the
1733 Lisp variable `state'."
1734 :group 'org-todo
1735 :type 'hook)
1737 (defvar org-blocker-hook nil
1738 "Hook for functions that are allowed to block a state change.
1740 Each function gets as its single argument a property list, see
1741 `org-trigger-hook' for more information about this list.
1743 If any of the functions in this hook returns nil, the state change
1744 is blocked.")
1746 (defvar org-trigger-hook nil
1747 "Hook for functions that are triggered by a state change.
1749 Each function gets as its single argument a property list with at least
1750 the following elements:
1752 (:type type-of-change :position pos-at-entry-start
1753 :from old-state :to new-state)
1755 Depending on the type, more properties may be present.
1757 This mechanism is currently implemented for:
1759 TODO state changes
1760 ------------------
1761 :type todo-state-change
1762 :from previous state (keyword as a string), or nil, or a symbol
1763 'todo' or 'done', to indicate the general type of state.
1764 :to new state, like in :from")
1766 (defcustom org-enforce-todo-dependencies nil
1767 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1768 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1769 be blocked if any prior sibling is not yet done.
1770 Finally, if the parent is blocked because of ordered siblings of its own,
1771 the child will also be blocked.
1772 This variable needs to be set before org.el is loaded, and you need to
1773 restart Emacs after a change to make the change effective. The only way
1774 to change is while Emacs is running is through the customize interface."
1775 :set (lambda (var val)
1776 (set var val)
1777 (if val
1778 (add-hook 'org-blocker-hook
1779 'org-block-todo-from-children-or-siblings-or-parent)
1780 (remove-hook 'org-blocker-hook
1781 'org-block-todo-from-children-or-siblings-or-parent)))
1782 :group 'org-todo
1783 :type 'boolean)
1785 (defcustom org-enforce-todo-checkbox-dependencies nil
1786 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1787 When this is nil, checkboxes have no influence on switching TODO states.
1788 When non-nil, you first need to check off all check boxes before the TODO
1789 entry can be switched to DONE.
1790 This variable needs to be set before org.el is loaded, and you need to
1791 restart Emacs after a change to make the change effective. The only way
1792 to change is while Emacs is running is through the customize interface."
1793 :set (lambda (var val)
1794 (set var val)
1795 (if val
1796 (add-hook 'org-blocker-hook
1797 'org-block-todo-from-checkboxes)
1798 (remove-hook 'org-blocker-hook
1799 'org-block-todo-from-checkboxes)))
1800 :group 'org-todo
1801 :type 'boolean)
1803 (defcustom org-treat-insert-todo-heading-as-state-change nil
1804 "Non-nil means, inserting a TODO heading is treated as state change.
1805 So when the command \\[org-insert-todo-heading] is used, state change
1806 logging will apply if appropriate. When nil, the new TODO item will
1807 be inserted directly, and no logging will take place."
1808 :group 'org-todo
1809 :type 'boolean)
1811 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1812 "Non-nil means, switching TODO states with S-cursor counts as state change.
1813 This is the default behavior. However, setting this to nil allows a
1814 convenient way to select a TODO state and bypass any logging associated
1815 with that."
1816 :group 'org-todo
1817 :type 'boolean)
1819 (defcustom org-todo-state-tags-triggers nil
1820 "Tag changes that should be triggered by TODO state changes.
1821 This is a list. Each entry is
1823 (state-change (tag . flag) .......)
1825 State-change can be a string with a state, and empty string to indicate the
1826 state that has no TODO keyword, or it can be one of the symbols `todo'
1827 or `done', meaning any not-done or done state, respectively."
1828 :group 'org-todo
1829 :group 'org-tags
1830 :type '(repeat
1831 (cons (choice :tag "When changing to"
1832 (const :tag "Not-done state" todo)
1833 (const :tag "Done state" done)
1834 (string :tag "State"))
1835 (repeat
1836 (cons :tag "Tag action"
1837 (string :tag "Tag")
1838 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1840 (defcustom org-log-done nil
1841 "Information to record when a task moves to the DONE state.
1843 Possible values are:
1845 nil Don't add anything, just change the keyword
1846 time Add a time stamp to the task
1847 note Prompt a closing note and add it with template `org-log-note-headings'
1849 This option can also be set with on a per-file-basis with
1851 #+STARTUP: nologdone
1852 #+STARTUP: logdone
1853 #+STARTUP: lognotedone
1855 You can have local logging settings for a subtree by setting the LOGGING
1856 property to one or more of these keywords."
1857 :group 'org-todo
1858 :group 'org-progress
1859 :type '(choice
1860 (const :tag "No logging" nil)
1861 (const :tag "Record CLOSED timestamp" time)
1862 (const :tag "Record CLOSED timestamp with closing note." note)))
1864 ;; Normalize old uses of org-log-done.
1865 (cond
1866 ((eq org-log-done t) (setq org-log-done 'time))
1867 ((and (listp org-log-done) (memq 'done org-log-done))
1868 (setq org-log-done 'note)))
1870 (defcustom org-log-note-clock-out nil
1871 "Non-nil means, record a note when clocking out of an item.
1872 This can also be configured on a per-file basis by adding one of
1873 the following lines anywhere in the buffer:
1875 #+STARTUP: lognoteclock-out
1876 #+STARTUP: nolognoteclock-out"
1877 :group 'org-todo
1878 :group 'org-progress
1879 :type 'boolean)
1881 (defcustom org-log-done-with-time t
1882 "Non-nil means, the CLOSED time stamp will contain date and time.
1883 When nil, only the date will be recorded."
1884 :group 'org-progress
1885 :type 'boolean)
1887 (defcustom org-log-note-headings
1888 '((done . "CLOSING NOTE %t")
1889 (state . "State %-12s from %-12S %t")
1890 (note . "Note taken on %t")
1891 (clock-out . ""))
1892 "Headings for notes added to entries.
1893 The value is an alist, with the car being a symbol indicating the note
1894 context, and the cdr is the heading to be used. The heading may also be the
1895 empty string.
1896 %t in the heading will be replaced by a time stamp.
1897 %s will be replaced by the new TODO state, in double quotes.
1898 %S will be replaced by the old TODO state, in double quotes.
1899 %u will be replaced by the user name.
1900 %U will be replaced by the full user name."
1901 :group 'org-todo
1902 :group 'org-progress
1903 :type '(list :greedy t
1904 (cons (const :tag "Heading when closing an item" done) string)
1905 (cons (const :tag
1906 "Heading when changing todo state (todo sequence only)"
1907 state) string)
1908 (cons (const :tag "Heading when just taking a note" note) string)
1909 (cons (const :tag "Heading when clocking out" clock-out) string)))
1911 (unless (assq 'note org-log-note-headings)
1912 (push '(note . "%t") org-log-note-headings))
1914 (defcustom org-log-into-drawer nil
1915 "Non-nil means, insert state change notes and time stamps into a drawer.
1916 When nil, state changes notes will be inserted after the headline and
1917 any scheduling and clock lines, but not inside a drawer.
1919 The value of this variable should be the name of the drawer to use.
1920 LOGBOOK is proposed at the default drawer for this purpose, you can
1921 also set this to a string to define the drawer of your choice.
1923 A value of t is also allowed, representing \"LOGBOOK\".
1925 If this variable is set, `org-log-state-notes-insert-after-drawers'
1926 will be ignored.
1928 You can set the property LOG_INTO_DRAWER to overrule this setting for
1929 a subtree."
1930 :group 'org-todo
1931 :group 'org-progress
1932 :type '(choice
1933 (const :tag "Not into a drawer" nil)
1934 (const :tag "LOGBOOK" t)
1935 (string :tag "Other")))
1937 (if (fboundp 'defvaralias)
1938 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1940 (defun org-log-into-drawer ()
1941 "Return the value of `org-log-into-drawer', but let properties overrule.
1942 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
1943 used instead of the default value."
1944 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
1945 (cond
1946 ((or (not p) (equal p "nil")) org-log-into-drawer)
1947 ((equal p "t") "LOGBOOK")
1948 (t p))))
1950 (defcustom org-log-state-notes-insert-after-drawers nil
1951 "Non-nil means, insert state change notes after any drawers in entry.
1952 Only the drawers that *immediately* follow the headline and the
1953 deadline/scheduled line are skipped.
1954 When nil, insert notes right after the heading and perhaps the line
1955 with deadline/scheduling if present.
1957 This variable will have no effect if `org-log-into-drawer' is
1958 set."
1959 :group 'org-todo
1960 :group 'org-progress
1961 :type 'boolean)
1963 (defcustom org-log-states-order-reversed t
1964 "Non-nil means, the latest state change note will be directly after heading.
1965 When nil, the notes will be orderer according to time."
1966 :group 'org-todo
1967 :group 'org-progress
1968 :type 'boolean)
1970 (defcustom org-log-repeat 'time
1971 "Non-nil means, record moving through the DONE state when triggering repeat.
1972 An auto-repeating tasks is immediately switched back to TODO when marked
1973 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1974 the TODO keyword definition, or recording a closing note by setting
1975 `org-log-done', there will be no record of the task moving through DONE.
1976 This variable forces taking a note anyway. Possible values are:
1978 nil Don't force a record
1979 time Record a time stamp
1980 note Record a note
1982 This option can also be set with on a per-file-basis with
1984 #+STARTUP: logrepeat
1985 #+STARTUP: lognoterepeat
1986 #+STARTUP: nologrepeat
1988 You can have local logging settings for a subtree by setting the LOGGING
1989 property to one or more of these keywords."
1990 :group 'org-todo
1991 :group 'org-progress
1992 :type '(choice
1993 (const :tag "Don't force a record" nil)
1994 (const :tag "Force recording the DONE state" time)
1995 (const :tag "Force recording a note with the DONE state" note)))
1998 (defgroup org-priorities nil
1999 "Priorities in Org-mode."
2000 :tag "Org Priorities"
2001 :group 'org-todo)
2003 (defcustom org-enable-priority-commands t
2004 "Non-nil means, priority commands are active.
2005 When nil, these commands will be disabled, so that you never accidentally
2006 set a priority."
2007 :group 'org-priorities
2008 :type 'boolean)
2010 (defcustom org-highest-priority ?A
2011 "The highest priority of TODO items. A character like ?A, ?B etc.
2012 Must have a smaller ASCII number than `org-lowest-priority'."
2013 :group 'org-priorities
2014 :type 'character)
2016 (defcustom org-lowest-priority ?C
2017 "The lowest priority of TODO items. A character like ?A, ?B etc.
2018 Must have a larger ASCII number than `org-highest-priority'."
2019 :group 'org-priorities
2020 :type 'character)
2022 (defcustom org-default-priority ?B
2023 "The default priority of TODO items.
2024 This is the priority an item get if no explicit priority is given."
2025 :group 'org-priorities
2026 :type 'character)
2028 (defcustom org-priority-start-cycle-with-default t
2029 "Non-nil means, start with default priority when starting to cycle.
2030 When this is nil, the first step in the cycle will be (depending on the
2031 command used) one higher or lower that the default priority."
2032 :group 'org-priorities
2033 :type 'boolean)
2035 (defgroup org-time nil
2036 "Options concerning time stamps and deadlines in Org-mode."
2037 :tag "Org Time"
2038 :group 'org)
2040 (defcustom org-insert-labeled-timestamps-at-point nil
2041 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2042 When nil, these labeled time stamps are forces into the second line of an
2043 entry, just after the headline. When scheduling from the global TODO list,
2044 the time stamp will always be forced into the second line."
2045 :group 'org-time
2046 :type 'boolean)
2048 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2049 "Formats for `format-time-string' which are used for time stamps.
2050 It is not recommended to change this constant.")
2052 (defcustom org-time-stamp-rounding-minutes '(0 5)
2053 "Number of minutes to round time stamps to.
2054 These are two values, the first applies when first creating a time stamp.
2055 The second applies when changing it with the commands `S-up' and `S-down'.
2056 When changing the time stamp, this means that it will change in steps
2057 of N minutes, as given by the second value.
2059 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2060 numbers should be factors of 60, so for example 5, 10, 15.
2062 When this is larger than 1, you can still force an exact time-stamp by using
2063 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2064 and by using a prefix arg to `S-up/down' to specify the exact number
2065 of minutes to shift."
2066 :group 'org-time
2067 :get '(lambda (var) ; Make sure all entries have 5 elements
2068 (if (integerp (default-value var))
2069 (list (default-value var) 5)
2070 (default-value var)))
2071 :type '(list
2072 (integer :tag "when inserting times")
2073 (integer :tag "when modifying times")))
2075 ;; Normalize old customizations of this variable.
2076 (when (integerp org-time-stamp-rounding-minutes)
2077 (setq org-time-stamp-rounding-minutes
2078 (list org-time-stamp-rounding-minutes
2079 org-time-stamp-rounding-minutes)))
2081 (defcustom org-display-custom-times nil
2082 "Non-nil means, overlay custom formats over all time stamps.
2083 The formats are defined through the variable `org-time-stamp-custom-formats'.
2084 To turn this on on a per-file basis, insert anywhere in the file:
2085 #+STARTUP: customtime"
2086 :group 'org-time
2087 :set 'set-default
2088 :type 'sexp)
2089 (make-variable-buffer-local 'org-display-custom-times)
2091 (defcustom org-time-stamp-custom-formats
2092 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2093 "Custom formats for time stamps. See `format-time-string' for the syntax.
2094 These are overlayed over the default ISO format if the variable
2095 `org-display-custom-times' is set. Time like %H:%M should be at the
2096 end of the second format. The custom formats are also honored by export
2097 commands, if custom time display is turned on at the time of export."
2098 :group 'org-time
2099 :type 'sexp)
2101 (defun org-time-stamp-format (&optional long inactive)
2102 "Get the right format for a time string."
2103 (let ((f (if long (cdr org-time-stamp-formats)
2104 (car org-time-stamp-formats))))
2105 (if inactive
2106 (concat "[" (substring f 1 -1) "]")
2107 f)))
2109 (defcustom org-time-clocksum-format "%d:%02d"
2110 "The format string used when creating CLOCKSUM lines, or when
2111 org-mode generates a time duration."
2112 :group 'org-time
2113 :type 'string)
2115 (defcustom org-deadline-warning-days 14
2116 "No. of days before expiration during which a deadline becomes active.
2117 This variable governs the display in sparse trees and in the agenda.
2118 When 0 or negative, it means use this number (the absolute value of it)
2119 even if a deadline has a different individual lead time specified.
2121 Custom commands can set this variable in the options section."
2122 :group 'org-time
2123 :group 'org-agenda-daily/weekly
2124 :type 'integer)
2126 (defcustom org-read-date-prefer-future t
2127 "Non-nil means, assume future for incomplete date input from user.
2128 This affects the following situations:
2129 1. The user gives a day, but no month.
2130 For example, if today is the 15th, and you enter \"3\", Org-mode will
2131 read this as the third of *next* month. However, if you enter \"17\",
2132 it will be considered as *this* month.
2133 2. The user gives a month but not a year.
2134 For example, if it is april and you enter \"feb 2\", this will be read
2135 as feb 2, *next* year. \"May 5\", however, will be this year.
2137 Currently this does not work for ISO week specifications.
2139 When this option is nil, the current month and year will always be used
2140 as defaults."
2141 :group 'org-time
2142 :type 'boolean)
2144 (defcustom org-read-date-display-live t
2145 "Non-nil means, display current interpretation of date prompt live.
2146 This display will be in an overlay, in the minibuffer."
2147 :group 'org-time
2148 :type 'boolean)
2150 (defcustom org-read-date-popup-calendar t
2151 "Non-nil means, pop up a calendar when prompting for a date.
2152 In the calendar, the date can be selected with mouse-1. However, the
2153 minibuffer will also be active, and you can simply enter the date as well.
2154 When nil, only the minibuffer will be available."
2155 :group 'org-time
2156 :type 'boolean)
2157 (if (fboundp 'defvaralias)
2158 (defvaralias 'org-popup-calendar-for-date-prompt
2159 'org-read-date-popup-calendar))
2161 (defcustom org-read-date-minibuffer-setup-hook nil
2162 "Hook to be used to set up keys for the date/time interface.
2163 Add key definitions to `minibuffer-local-map', which will be a temporary
2164 copy."
2165 :group 'org-time
2166 :type 'hook)
2168 (defcustom org-extend-today-until 0
2169 "The hour when your day really ends. Must be an integer.
2170 This has influence for the following applications:
2171 - When switching the agenda to \"today\". It it is still earlier than
2172 the time given here, the day recognized as TODAY is actually yesterday.
2173 - When a date is read from the user and it is still before the time given
2174 here, the current date and time will be assumed to be yesterday, 23:59.
2175 Also, timestamps inserted in remember templates follow this rule.
2177 IMPORTANT: This is a feature whose implementation is and likely will
2178 remain incomplete. Really, it is only here because past midnight seems to
2179 be the favorite working time of John Wiegley :-)"
2180 :group 'org-time
2181 :type 'integer)
2183 (defcustom org-edit-timestamp-down-means-later nil
2184 "Non-nil means, S-down will increase the time in a time stamp.
2185 When nil, S-up will increase."
2186 :group 'org-time
2187 :type 'boolean)
2189 (defcustom org-calendar-follow-timestamp-change t
2190 "Non-nil means, make the calendar window follow timestamp changes.
2191 When a timestamp is modified and the calendar window is visible, it will be
2192 moved to the new date."
2193 :group 'org-time
2194 :type 'boolean)
2196 (defgroup org-tags nil
2197 "Options concerning tags in Org-mode."
2198 :tag "Org Tags"
2199 :group 'org)
2201 (defcustom org-tag-alist nil
2202 "List of tags allowed in Org-mode files.
2203 When this list is nil, Org-mode will base TAG input on what is already in the
2204 buffer.
2205 The value of this variable is an alist, the car of each entry must be a
2206 keyword as a string, the cdr may be a character that is used to select
2207 that tag through the fast-tag-selection interface.
2208 See the manual for details."
2209 :group 'org-tags
2210 :type '(repeat
2211 (choice
2212 (cons (string :tag "Tag name")
2213 (character :tag "Access char"))
2214 (const :tag "Start radio group" (:startgroup))
2215 (const :tag "End radio group" (:endgroup))
2216 (const :tag "New line" (:newline)))))
2218 (defcustom org-tag-persistent-alist nil
2219 "List of tags that will always appear in all Org-mode files.
2220 This is in addition to any in buffer settings or customizations
2221 of `org-tag-alist'.
2222 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2223 The value of this variable is an alist, the car of each entry must be a
2224 keyword as a string, the cdr may be a character that is used to select
2225 that tag through the fast-tag-selection interface.
2226 See the manual for details.
2227 To disable these tags on a per-file basis, insert anywhere in the file:
2228 #+STARTUP: noptag"
2229 :group 'org-tags
2230 :type '(repeat
2231 (choice
2232 (cons (string :tag "Tag name")
2233 (character :tag "Access char"))
2234 (const :tag "Start radio group" (:startgroup))
2235 (const :tag "End radio group" (:endgroup))
2236 (const :tag "New line" (:newline)))))
2238 (defvar org-file-tags nil
2239 "List of tags that can be inherited by all entries in the file.
2240 The tags will be inherited if the variable `org-use-tag-inheritance'
2241 says they should be.
2242 This variable is populated from #+TAG lines.")
2244 (defcustom org-use-fast-tag-selection 'auto
2245 "Non-nil means, use fast tag selection scheme.
2246 This is a special interface to select and deselect tags with single keys.
2247 When nil, fast selection is never used.
2248 When the symbol `auto', fast selection is used if and only if selection
2249 characters for tags have been configured, either through the variable
2250 `org-tag-alist' or through a #+TAGS line in the buffer.
2251 When t, fast selection is always used and selection keys are assigned
2252 automatically if necessary."
2253 :group 'org-tags
2254 :type '(choice
2255 (const :tag "Always" t)
2256 (const :tag "Never" nil)
2257 (const :tag "When selection characters are configured" 'auto)))
2259 (defcustom org-fast-tag-selection-single-key nil
2260 "Non-nil means, fast tag selection exits after first change.
2261 When nil, you have to press RET to exit it.
2262 During fast tag selection, you can toggle this flag with `C-c'.
2263 This variable can also have the value `expert'. In this case, the window
2264 displaying the tags menu is not even shown, until you press C-c again."
2265 :group 'org-tags
2266 :type '(choice
2267 (const :tag "No" nil)
2268 (const :tag "Yes" t)
2269 (const :tag "Expert" expert)))
2271 (defvar org-fast-tag-selection-include-todo nil
2272 "Non-nil means, fast tags selection interface will also offer TODO states.
2273 This is an undocumented feature, you should not rely on it.")
2275 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2276 "The column to which tags should be indented in a headline.
2277 If this number is positive, it specifies the column. If it is negative,
2278 it means that the tags should be flushright to that column. For example,
2279 -80 works well for a normal 80 character screen."
2280 :group 'org-tags
2281 :type 'integer)
2283 (defcustom org-auto-align-tags t
2284 "Non-nil means, realign tags after pro/demotion of TODO state change.
2285 These operations change the length of a headline and therefore shift
2286 the tags around. With this options turned on, after each such operation
2287 the tags are again aligned to `org-tags-column'."
2288 :group 'org-tags
2289 :type 'boolean)
2291 (defcustom org-use-tag-inheritance t
2292 "Non-nil means, tags in levels apply also for sublevels.
2293 When nil, only the tags directly given in a specific line apply there.
2294 This may also be a list of tags that should be inherited, or a regexp that
2295 matches tags that should be inherited. Additional control is possible
2296 with the variable `org-tags-exclude-from-inheritance' which gives an
2297 explicit list of tags to be excluded from inheritance., even if the value of
2298 `org-use-tag-inheritance' would select it for inheritance.
2300 If this option is t, a match early-on in a tree can lead to a large
2301 number of matches in the subtree when constructing the agenda or creating
2302 a sparse tree. If you only want to see the first match in a tree during
2303 a search, check out the variable `org-tags-match-list-sublevels'."
2304 :group 'org-tags
2305 :type '(choice
2306 (const :tag "Not" nil)
2307 (const :tag "Always" t)
2308 (repeat :tag "Specific tags" (string :tag "Tag"))
2309 (regexp :tag "Tags matched by regexp")))
2311 (defcustom org-tags-exclude-from-inheritance nil
2312 "List of tags that should never be inherited.
2313 This is a way to exclude a few tags from inheritance. For way to do
2314 the opposite, to actively allow inheritance for selected tags,
2315 see the variable `org-use-tag-inheritance'."
2316 :group 'org-tags
2317 :type '(repeat (string :tag "Tag")))
2319 (defun org-tag-inherit-p (tag)
2320 "Check if TAG is one that should be inherited."
2321 (cond
2322 ((member tag org-tags-exclude-from-inheritance) nil)
2323 ((eq org-use-tag-inheritance t) t)
2324 ((not org-use-tag-inheritance) nil)
2325 ((stringp org-use-tag-inheritance)
2326 (string-match org-use-tag-inheritance tag))
2327 ((listp org-use-tag-inheritance)
2328 (member tag org-use-tag-inheritance))
2329 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2331 (defcustom org-tags-match-list-sublevels t
2332 "Non-nil means list also sublevels of headlines matching a search.
2333 This variable applies to tags/property searches, and also to stuck
2334 projects because this search is based on a tags match as well.
2336 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2337 the sublevels of a headline matching a tag search often also match
2338 the same search. Listing all of them can create very long lists.
2339 Setting this variable to nil causes subtrees of a match to be skipped.
2341 This variable is semi-obsolete and probably should always be true. It
2342 is better to limit inheritance to certain tags using the variables
2343 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2344 :group 'org-tags
2345 :type '(choice
2346 (const :tag "No, don't list them" nil)
2347 (const :tag "Yes, do list them" t)
2348 (const :tag "List them, indented with leading dots" indented)))
2350 (defvar org-tags-history nil
2351 "History of minibuffer reads for tags.")
2352 (defvar org-last-tags-completion-table nil
2353 "The last used completion table for tags.")
2354 (defvar org-after-tags-change-hook nil
2355 "Hook that is run after the tags in a line have changed.")
2357 (defgroup org-properties nil
2358 "Options concerning properties in Org-mode."
2359 :tag "Org Properties"
2360 :group 'org)
2362 (defcustom org-property-format "%-10s %s"
2363 "How property key/value pairs should be formatted by `indent-line'.
2364 When `indent-line' hits a property definition, it will format the line
2365 according to this format, mainly to make sure that the values are
2366 lined-up with respect to each other."
2367 :group 'org-properties
2368 :type 'string)
2370 (defcustom org-use-property-inheritance nil
2371 "Non-nil means, properties apply also for sublevels.
2373 This setting is chiefly used during property searches. Turning it on can
2374 cause significant overhead when doing a search, which is why it is not
2375 on by default.
2377 When nil, only the properties directly given in the current entry count.
2378 When t, every property is inherited. The value may also be a list of
2379 properties that should have inheritance, or a regular expression matching
2380 properties that should be inherited.
2382 However, note that some special properties use inheritance under special
2383 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2384 and the properties ending in \"_ALL\" when they are used as descriptor
2385 for valid values of a property.
2387 Note for programmers:
2388 When querying an entry with `org-entry-get', you can control if inheritance
2389 should be used. By default, `org-entry-get' looks only at the local
2390 properties. You can request inheritance by setting the inherit argument
2391 to t (to force inheritance) or to `selective' (to respect the setting
2392 in this variable)."
2393 :group 'org-properties
2394 :type '(choice
2395 (const :tag "Not" nil)
2396 (const :tag "Always" t)
2397 (repeat :tag "Specific properties" (string :tag "Property"))
2398 (regexp :tag "Properties matched by regexp")))
2400 (defun org-property-inherit-p (property)
2401 "Check if PROPERTY is one that should be inherited."
2402 (cond
2403 ((eq org-use-property-inheritance t) t)
2404 ((not org-use-property-inheritance) nil)
2405 ((stringp org-use-property-inheritance)
2406 (string-match org-use-property-inheritance property))
2407 ((listp org-use-property-inheritance)
2408 (member property org-use-property-inheritance))
2409 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2411 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2412 "The default column format, if no other format has been defined.
2413 This variable can be set on the per-file basis by inserting a line
2415 #+COLUMNS: %25ITEM ....."
2416 :group 'org-properties
2417 :type 'string)
2419 (defcustom org-columns-ellipses ".."
2420 "The ellipses to be used when a field in column view is truncated.
2421 When this is the empty string, as many characters as possible are shown,
2422 but then there will be no visual indication that the field has been truncated.
2423 When this is a string of length N, the last N characters of a truncated
2424 field are replaced by this string. If the column is narrower than the
2425 ellipses string, only part of the ellipses string will be shown."
2426 :group 'org-properties
2427 :type 'string)
2429 (defcustom org-columns-modify-value-for-display-function nil
2430 "Function that modifies values for display in column view.
2431 For example, it can be used to cut out a certain part from a time stamp.
2432 The function must take 2 arguments:
2434 column-title The title of the column (*not* the property name)
2435 value The value that should be modified.
2437 The function should return the value that should be displayed,
2438 or nil if the normal value should be used."
2439 :group 'org-properties
2440 :type 'function)
2442 (defcustom org-effort-property "Effort"
2443 "The property that is being used to keep track of effort estimates.
2444 Effort estimates given in this property need to have the format H:MM."
2445 :group 'org-properties
2446 :group 'org-progress
2447 :type '(string :tag "Property"))
2449 (defconst org-global-properties-fixed
2450 '(("VISIBILITY_ALL" . "folded children content all")
2451 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2452 "List of property/value pairs that can be inherited by any entry.
2454 These are fixed values, for the preset properties. The user variable
2455 that can be used to add to this list is `org-global-properties'.
2457 The entries in this list are cons cells where the car is a property
2458 name and cdr is a string with the value. If the value represents
2459 multiple items like an \"_ALL\" property, separate the items by
2460 spaces.")
2462 (defcustom org-global-properties nil
2463 "List of property/value pairs that can be inherited by any entry.
2465 This list will be combined with the constant `org-global-properties-fixed'.
2467 The entries in this list are cons cells where the car is a property
2468 name and cdr is a string with the value.
2470 You can set buffer-local values for the same purpose in the variable
2471 `org-file-properties' this by adding lines like
2473 #+PROPERTY: NAME VALUE"
2474 :group 'org-properties
2475 :type '(repeat
2476 (cons (string :tag "Property")
2477 (string :tag "Value"))))
2479 (defvar org-file-properties nil
2480 "List of property/value pairs that can be inherited by any entry.
2481 Valid for the current buffer.
2482 This variable is populated from #+PROPERTY lines.")
2483 (make-variable-buffer-local 'org-file-properties)
2485 (defgroup org-agenda nil
2486 "Options concerning agenda views in Org-mode."
2487 :tag "Org Agenda"
2488 :group 'org)
2490 (defvar org-category nil
2491 "Variable used by org files to set a category for agenda display.
2492 Such files should use a file variable to set it, for example
2494 # -*- mode: org; org-category: \"ELisp\"
2496 or contain a special line
2498 #+CATEGORY: ELisp
2500 If the file does not specify a category, then file's base name
2501 is used instead.")
2502 (make-variable-buffer-local 'org-category)
2503 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2505 (defcustom org-agenda-files nil
2506 "The files to be used for agenda display.
2507 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2508 \\[org-remove-file]. You can also use customize to edit the list.
2510 If an entry is a directory, all files in that directory that are matched by
2511 `org-agenda-file-regexp' will be part of the file list.
2513 If the value of the variable is not a list but a single file name, then
2514 the list of agenda files is actually stored and maintained in that file, one
2515 agenda file per line."
2516 :group 'org-agenda
2517 :type '(choice
2518 (repeat :tag "List of files and directories" file)
2519 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2521 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2522 "Regular expression to match files for `org-agenda-files'.
2523 If any element in the list in that variable contains a directory instead
2524 of a normal file, all files in that directory that are matched by this
2525 regular expression will be included."
2526 :group 'org-agenda
2527 :type 'regexp)
2529 (defcustom org-agenda-text-search-extra-files nil
2530 "List of extra files to be searched by text search commands.
2531 These files will be search in addition to the agenda files by the
2532 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2533 Note that these files will only be searched for text search commands,
2534 not for the other agenda views like todo lists, tag searches or the weekly
2535 agenda. This variable is intended to list notes and possibly archive files
2536 that should also be searched by these two commands.
2537 In fact, if the first element in the list is the symbol `agenda-archives',
2538 than all archive files of all agenda files will be added to the search
2539 scope."
2540 :group 'org-agenda
2541 :type '(set :greedy t
2542 (const :tag "Agenda Archives" agenda-archives)
2543 (repeat :inline t (file))))
2545 (if (fboundp 'defvaralias)
2546 (defvaralias 'org-agenda-multi-occur-extra-files
2547 'org-agenda-text-search-extra-files))
2549 (defcustom org-agenda-skip-unavailable-files nil
2550 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2551 A nil value means to remove them, after a query, from the list."
2552 :group 'org-agenda
2553 :type 'boolean)
2555 (defcustom org-calendar-to-agenda-key [?c]
2556 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2557 The command `org-calendar-goto-agenda' will be bound to this key. The
2558 default is the character `c' because then `c' can be used to switch back and
2559 forth between agenda and calendar."
2560 :group 'org-agenda
2561 :type 'sexp)
2563 (defcustom org-calendar-agenda-action-key [?k]
2564 "The key to be installed in `calendar-mode-map' for agenda-action.
2565 The command `org-agenda-action' will be bound to this key. The
2566 default is the character `k' because we use the same key in the agenda."
2567 :group 'org-agenda
2568 :type 'sexp)
2570 (eval-after-load "calendar"
2571 '(progn
2572 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2573 'org-calendar-goto-agenda)
2574 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2575 'org-agenda-action)))
2577 (defgroup org-latex nil
2578 "Options for embedding LaTeX code into Org-mode."
2579 :tag "Org LaTeX"
2580 :group 'org)
2582 (defcustom org-format-latex-options
2583 '(:foreground default :background default :scale 1.0
2584 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2585 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2586 "Options for creating images from LaTeX fragments.
2587 This is a property list with the following properties:
2588 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2589 `default' means use the foreground of the default face.
2590 :background the background color, or \"Transparent\".
2591 `default' means use the background of the default face.
2592 :scale a scaling factor for the size of the images.
2593 :html-foreground, :html-background, :html-scale
2594 the same numbers for HTML export.
2595 :matchers a list indicating which matchers should be used to
2596 find LaTeX fragments. Valid members of this list are:
2597 \"begin\" find environments
2598 \"$1\" find single characters surrounded by $.$
2599 \"$\" find math expressions surrounded by $...$
2600 \"$$\" find math expressions surrounded by $$....$$
2601 \"\\(\" find math expressions surrounded by \\(...\\)
2602 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2603 :group 'org-latex
2604 :type 'plist)
2606 (defcustom org-format-latex-header "\\documentclass{article}
2607 \\usepackage{fullpage} % do not remove
2608 \\usepackage{amssymb}
2609 \\usepackage[usenames]{color}
2610 \\usepackage{amsmath}
2611 \\usepackage{latexsym}
2612 \\usepackage[mathscr]{eucal}
2613 \\pagestyle{empty} % do not remove"
2614 "The document header used for processing LaTeX fragments."
2615 :group 'org-latex
2616 :type 'string)
2619 (defgroup org-font-lock nil
2620 "Font-lock settings for highlighting in Org-mode."
2621 :tag "Org Font Lock"
2622 :group 'org)
2624 (defcustom org-level-color-stars-only nil
2625 "Non-nil means fontify only the stars in each headline.
2626 When nil, the entire headline is fontified.
2627 Changing it requires restart of `font-lock-mode' to become effective
2628 also in regions already fontified."
2629 :group 'org-font-lock
2630 :type 'boolean)
2632 (defcustom org-hide-leading-stars nil
2633 "Non-nil means, hide the first N-1 stars in a headline.
2634 This works by using the face `org-hide' for these stars. This
2635 face is white for a light background, and black for a dark
2636 background. You may have to customize the face `org-hide' to
2637 make this work.
2638 Changing it requires restart of `font-lock-mode' to become effective
2639 also in regions already fontified.
2640 You may also set this on a per-file basis by adding one of the following
2641 lines to the buffer:
2643 #+STARTUP: hidestars
2644 #+STARTUP: showstars"
2645 :group 'org-font-lock
2646 :type 'boolean)
2648 (defcustom org-fontify-done-headline nil
2649 "Non-nil means, change the face of a headline if it is marked DONE.
2650 Normally, only the TODO/DONE keyword indicates the state of a headline.
2651 When this is non-nil, the headline after the keyword is set to the
2652 `org-headline-done' as an additional indication."
2653 :group 'org-font-lock
2654 :type 'boolean)
2656 (defcustom org-fontify-emphasized-text t
2657 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2658 Changing this variable requires a restart of Emacs to take effect."
2659 :group 'org-font-lock
2660 :type 'boolean)
2662 (defcustom org-highlight-latex-fragments-and-specials nil
2663 "Non-nil means, fontify what is treated specially by the exporters."
2664 :group 'org-font-lock
2665 :type 'boolean)
2667 (defcustom org-hide-emphasis-markers nil
2668 "Non-nil mean font-lock should hide the emphasis marker characters."
2669 :group 'org-font-lock
2670 :type 'boolean)
2672 (defvar org-emph-re nil
2673 "Regular expression for matching emphasis.")
2674 (defvar org-verbatim-re nil
2675 "Regular expression for matching verbatim text.")
2676 (defvar org-emphasis-regexp-components) ; defined just below
2677 (defvar org-emphasis-alist) ; defined just below
2678 (defun org-set-emph-re (var val)
2679 "Set variable and compute the emphasis regular expression."
2680 (set var val)
2681 (when (and (boundp 'org-emphasis-alist)
2682 (boundp 'org-emphasis-regexp-components)
2683 org-emphasis-alist org-emphasis-regexp-components)
2684 (let* ((e org-emphasis-regexp-components)
2685 (pre (car e))
2686 (post (nth 1 e))
2687 (border (nth 2 e))
2688 (body (nth 3 e))
2689 (nl (nth 4 e))
2690 (body1 (concat body "*?"))
2691 (markers (mapconcat 'car org-emphasis-alist ""))
2692 (vmarkers (mapconcat
2693 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2694 org-emphasis-alist "")))
2695 ;; make sure special characters appear at the right position in the class
2696 (if (string-match "\\^" markers)
2697 (setq markers (concat (replace-match "" t t markers) "^")))
2698 (if (string-match "-" markers)
2699 (setq markers (concat (replace-match "" t t markers) "-")))
2700 (if (string-match "\\^" vmarkers)
2701 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2702 (if (string-match "-" vmarkers)
2703 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2704 (if (> nl 0)
2705 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2706 (int-to-string nl) "\\}")))
2707 ;; Make the regexp
2708 (setq org-emph-re
2709 (concat "\\([" pre "]\\|^\\)"
2710 "\\("
2711 "\\([" markers "]\\)"
2712 "\\("
2713 "[^" border "]\\|"
2714 "[^" border "]"
2715 body1
2716 "[^" border "]"
2717 "\\)"
2718 "\\3\\)"
2719 "\\([" post "]\\|$\\)"))
2720 (setq org-verbatim-re
2721 (concat "\\([" pre "]\\|^\\)"
2722 "\\("
2723 "\\([" vmarkers "]\\)"
2724 "\\("
2725 "[^" border "]\\|"
2726 "[^" border "]"
2727 body1
2728 "[^" border "]"
2729 "\\)"
2730 "\\3\\)"
2731 "\\([" post "]\\|$\\)")))))
2733 (defcustom org-emphasis-regexp-components
2734 '(" \t('\"{" "- \t.,:!?;'\")}" " \t\r\n,\"'" "." 1)
2735 "Components used to build the regular expression for emphasis.
2736 This is a list with 6 entries. Terminology: In an emphasis string
2737 like \" *strong word* \", we call the initial space PREMATCH, the final
2738 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2739 and \"trong wor\" is the body. The different components in this variable
2740 specify what is allowed/forbidden in each part:
2742 pre Chars allowed as prematch. Beginning of line will be allowed too.
2743 post Chars allowed as postmatch. End of line will be allowed too.
2744 border The chars *forbidden* as border characters.
2745 body-regexp A regexp like \".\" to match a body character. Don't use
2746 non-shy groups here, and don't allow newline here.
2747 newline The maximum number of newlines allowed in an emphasis exp.
2749 Use customize to modify this, or restart Emacs after changing it."
2750 :group 'org-font-lock
2751 :set 'org-set-emph-re
2752 :type '(list
2753 (sexp :tag "Allowed chars in pre ")
2754 (sexp :tag "Allowed chars in post ")
2755 (sexp :tag "Forbidden chars in border ")
2756 (sexp :tag "Regexp for body ")
2757 (integer :tag "number of newlines allowed")
2758 (option (boolean :tag "Please ignore this button"))))
2760 (defcustom org-emphasis-alist
2761 `(("*" bold "<b>" "</b>")
2762 ("/" italic "<i>" "</i>")
2763 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2764 ("=" org-code "<code>" "</code>" verbatim)
2765 ("~" org-verbatim "<code>" "</code>" verbatim)
2766 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2767 "<del>" "</del>")
2769 "Special syntax for emphasized text.
2770 Text starting and ending with a special character will be emphasized, for
2771 example *bold*, _underlined_ and /italic/. This variable sets the marker
2772 characters, the face to be used by font-lock for highlighting in Org-mode
2773 Emacs buffers, and the HTML tags to be used for this.
2774 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2775 Use customize to modify this, or restart Emacs after changing it."
2776 :group 'org-font-lock
2777 :set 'org-set-emph-re
2778 :type '(repeat
2779 (list
2780 (string :tag "Marker character")
2781 (choice
2782 (face :tag "Font-lock-face")
2783 (plist :tag "Face property list"))
2784 (string :tag "HTML start tag")
2785 (string :tag "HTML end tag")
2786 (option (const verbatim)))))
2788 (defvar org-protecting-blocks
2789 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
2790 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
2791 This is needed for font-lock setup.")
2793 ;;; Miscellaneous options
2795 (defgroup org-completion nil
2796 "Completion in Org-mode."
2797 :tag "Org Completion"
2798 :group 'org)
2800 (defcustom org-completion-use-ido nil
2801 "Non-nil means, use ido completion wherever possible.
2802 Note that `ido-mode' must be active for this variable to be relevant.
2803 If you decide to turn this variable on, you might well want to turn off
2804 `org-outline-path-complete-in-steps'."
2805 :group 'org-completion
2806 :type 'boolean)
2808 (defcustom org-completion-fallback-command 'hippie-expand
2809 "The expansion command called by \\[org-complete] in normal context.
2810 Normal means, no org-mode-specific context."
2811 :group 'org-completion
2812 :type 'function)
2814 ;;; Functions and variables from ther packages
2815 ;; Declared here to avoid compiler warnings
2817 ;; XEmacs only
2818 (defvar outline-mode-menu-heading)
2819 (defvar outline-mode-menu-show)
2820 (defvar outline-mode-menu-hide)
2821 (defvar zmacs-regions) ; XEmacs regions
2823 ;; Emacs only
2824 (defvar mark-active)
2826 ;; Various packages
2827 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2828 (declare-function calendar-forward-day "cal-move" (arg))
2829 (declare-function calendar-goto-date "cal-move" (date))
2830 (declare-function calendar-goto-today "cal-move" ())
2831 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2832 (defvar calc-embedded-close-formula)
2833 (defvar calc-embedded-open-formula)
2834 (declare-function cdlatex-tab "ext:cdlatex" ())
2835 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2836 (defvar font-lock-unfontify-region-function)
2837 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2838 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2839 (defvar iswitchb-temp-buflist)
2840 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2841 (defvar org-agenda-tags-todo-honor-ignore-options)
2842 (declare-function org-agenda-skip "org-agenda" ())
2843 (declare-function org-format-agenda-item "org-agenda"
2844 (extra txt &optional category tags dotime noprefix remove-re))
2845 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2846 (declare-function org-agenda-change-all-lines "org-agenda"
2847 (newhead hdmarker &optional fixface just-this))
2848 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2849 (declare-function org-agenda-maybe-redo "org-agenda" ())
2850 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2851 (beg end))
2852 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2853 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2854 "org-agenda" (&optional end))
2855 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
2856 (declare-function parse-time-string "parse-time" (string))
2857 (declare-function remember "remember" (&optional initial))
2858 (declare-function remember-buffer-desc "remember" ())
2859 (declare-function remember-finalize "remember" ())
2860 (defvar remember-save-after-remembering)
2861 (defvar remember-data-file)
2862 (defvar remember-register)
2863 (defvar remember-buffer)
2864 (defvar remember-handler-functions)
2865 (defvar remember-annotation-functions)
2866 (defvar texmathp-why)
2867 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2868 (declare-function table--at-cell-p "table" (position &optional object at-column))
2870 (defvar w3m-current-url)
2871 (defvar w3m-current-title)
2873 (defvar org-latex-regexps)
2875 ;;; Autoload and prepare some org modules
2877 ;; Some table stuff that needs to be defined here, because it is used
2878 ;; by the functions setting up org-mode or checking for table context.
2880 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2881 "Detects an org-type or table-type table.")
2882 (defconst org-table-line-regexp "^[ \t]*|"
2883 "Detects an org-type table line.")
2884 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2885 "Detects an org-type table line.")
2886 (defconst org-table-hline-regexp "^[ \t]*|-"
2887 "Detects an org-type table hline.")
2888 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2889 "Detects a table-type table hline.")
2890 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2891 "Searching from within a table (any type) this finds the first line
2892 outside the table.")
2894 ;; Autoload the functions in org-table.el that are needed by functions here.
2896 (eval-and-compile
2897 (org-autoload "org-table"
2898 '(org-table-align org-table-begin org-table-blank-field
2899 org-table-convert org-table-convert-region org-table-copy-down
2900 org-table-copy-region org-table-create
2901 org-table-create-or-convert-from-region
2902 org-table-create-with-table.el org-table-current-dline
2903 org-table-cut-region org-table-delete-column org-table-edit-field
2904 org-table-edit-formulas org-table-end org-table-eval-formula
2905 org-table-export org-table-field-info
2906 org-table-get-stored-formulas org-table-goto-column
2907 org-table-hline-and-move org-table-import org-table-insert-column
2908 org-table-insert-hline org-table-insert-row org-table-iterate
2909 org-table-justify-field-maybe org-table-kill-row
2910 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2911 org-table-move-column org-table-move-column-left
2912 org-table-move-column-right org-table-move-row
2913 org-table-move-row-down org-table-move-row-up
2914 org-table-next-field org-table-next-row org-table-paste-rectangle
2915 org-table-previous-field org-table-recalculate
2916 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2917 org-table-toggle-coordinate-overlays
2918 org-table-toggle-formula-debugger org-table-wrap-region
2919 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2921 (defun org-at-table-p (&optional table-type)
2922 "Return t if the cursor is inside an org-type table.
2923 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2924 (if org-enable-table-editor
2925 (save-excursion
2926 (beginning-of-line 1)
2927 (looking-at (if table-type org-table-any-line-regexp
2928 org-table-line-regexp)))
2929 nil))
2930 (defsubst org-table-p () (org-at-table-p))
2932 (defun org-at-table.el-p ()
2933 "Return t if and only if we are at a table.el table."
2934 (and (org-at-table-p 'any)
2935 (save-excursion
2936 (goto-char (org-table-begin 'any))
2937 (looking-at org-table1-hline-regexp))))
2938 (defun org-table-recognize-table.el ()
2939 "If there is a table.el table nearby, recognize it and move into it."
2940 (if org-table-tab-recognizes-table.el
2941 (if (org-at-table.el-p)
2942 (progn
2943 (beginning-of-line 1)
2944 (if (looking-at org-table-dataline-regexp)
2946 (if (looking-at org-table1-hline-regexp)
2947 (progn
2948 (beginning-of-line 2)
2949 (if (looking-at org-table-any-border-regexp)
2950 (beginning-of-line -1)))))
2951 (if (re-search-forward "|" (org-table-end t) t)
2952 (progn
2953 (require 'table)
2954 (if (table--at-cell-p (point))
2956 (message "recognizing table.el table...")
2957 (table-recognize-table)
2958 (message "recognizing table.el table...done")))
2959 (error "This should not happen..."))
2961 nil)
2962 nil))
2964 (defun org-at-table-hline-p ()
2965 "Return t if the cursor is inside a hline in a table."
2966 (if org-enable-table-editor
2967 (save-excursion
2968 (beginning-of-line 1)
2969 (looking-at org-table-hline-regexp))
2970 nil))
2972 (defvar org-table-clean-did-remove-column nil)
2974 (defun org-table-map-tables (function)
2975 "Apply FUNCTION to the start of all tables in the buffer."
2976 (save-excursion
2977 (save-restriction
2978 (widen)
2979 (goto-char (point-min))
2980 (while (re-search-forward org-table-any-line-regexp nil t)
2981 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2982 (beginning-of-line 1)
2983 (if (looking-at org-table-line-regexp)
2984 (save-excursion (funcall function)))
2985 (re-search-forward org-table-any-border-regexp nil 1))))
2986 (message "Mapping tables: done"))
2988 ;; Declare and autoload functions from org-exp.el & Co
2990 (declare-function org-default-export-plist "org-exp")
2991 (declare-function org-infile-export-plist "org-exp")
2992 (declare-function org-get-current-options "org-exp")
2993 (eval-and-compile
2994 (org-autoload "org-exp"
2995 '(org-export org-export-visible
2996 org-insert-export-options-template
2997 org-table-clean-before-export))
2998 (org-autoload "org-ascii"
2999 '(org-export-as-ascii org-export-ascii-preprocess
3000 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3001 org-export-region-as-ascii))
3002 (org-autoload "org-html"
3003 '(org-export-as-html-and-open
3004 org-export-as-html-batch org-export-as-html-to-buffer
3005 org-replace-region-by-html org-export-region-as-html
3006 org-export-as-html))
3007 (org-autoload "org-icalendar"
3008 '(org-export-icalendar-this-file
3009 org-export-icalendar-all-agenda-files
3010 org-export-icalendar-combine-agenda-files))
3011 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3013 ;; Declare and autoload functions from org-agenda.el
3015 (eval-and-compile
3016 (org-autoload "org-agenda"
3017 '(org-agenda org-agenda-list org-search-view
3018 org-todo-list org-tags-view org-agenda-list-stuck-projects
3019 org-diary org-agenda-to-appt
3020 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3022 ;; Autoload org-remember
3024 (eval-and-compile
3025 (org-autoload "org-remember"
3026 '(org-remember-insinuate org-remember-annotation
3027 org-remember-apply-template org-remember org-remember-handler)))
3029 ;; Autoload org-clock.el
3032 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3033 (beg end))
3034 (declare-function org-clock-update-mode-line "org-clock" ())
3035 (defvar org-clock-start-time)
3036 (defvar org-clock-marker (make-marker)
3037 "Marker recording the last clock-in.")
3038 (defun org-clock-is-active ()
3039 "Return non-nil if clock is currently running.
3040 The return value is actually the clock marker."
3041 (marker-buffer org-clock-marker))
3043 (eval-and-compile
3044 (org-autoload
3045 "org-clock"
3046 '(org-clock-in org-clock-out org-clock-cancel
3047 org-clock-goto org-clock-sum org-clock-display
3048 org-clock-remove-overlays org-clock-report
3049 org-clocktable-shift org-dblock-write:clocktable
3050 org-get-clocktable)))
3052 (defun org-clock-update-time-maybe ()
3053 "If this is a CLOCK line, update it and return t.
3054 Otherwise, return nil."
3055 (interactive)
3056 (save-excursion
3057 (beginning-of-line 1)
3058 (skip-chars-forward " \t")
3059 (when (looking-at org-clock-string)
3060 (let ((re (concat "[ \t]*" org-clock-string
3061 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3062 "\\([ \t]*=>.*\\)?\\)?"))
3063 ts te h m s neg)
3064 (cond
3065 ((not (looking-at re))
3066 nil)
3067 ((not (match-end 2))
3068 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3069 (> org-clock-marker (point))
3070 (<= org-clock-marker (point-at-eol)))
3071 ;; The clock is running here
3072 (setq org-clock-start-time
3073 (apply 'encode-time
3074 (org-parse-time-string (match-string 1))))
3075 (org-clock-update-mode-line)))
3077 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3078 (end-of-line 1)
3079 (setq ts (match-string 1)
3080 te (match-string 3))
3081 (setq s (- (time-to-seconds
3082 (apply 'encode-time (org-parse-time-string te)))
3083 (time-to-seconds
3084 (apply 'encode-time (org-parse-time-string ts))))
3085 neg (< s 0)
3086 s (abs s)
3087 h (floor (/ s 3600))
3088 s (- s (* 3600 h))
3089 m (floor (/ s 60))
3090 s (- s (* 60 s)))
3091 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3092 t))))))
3094 (defun org-check-running-clock ()
3095 "Check if the current buffer contains the running clock.
3096 If yes, offer to stop it and to save the buffer with the changes."
3097 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3098 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3099 (buffer-name))))
3100 (org-clock-out)
3101 (when (y-or-n-p "Save changed buffer?")
3102 (save-buffer))))
3104 (defun org-clocktable-try-shift (dir n)
3105 "Check if this line starts a clock table, if yes, shift the time block."
3106 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3107 (org-clocktable-shift dir n)))
3109 ;; Autoload org-timer.el
3111 (eval-and-compile
3112 (org-autoload
3113 "org-timer"
3114 '(org-timer-start org-timer org-timer-item
3115 org-timer-change-times-in-region)))
3117 ;; Autoload org-feed.el
3119 (eval-and-compile
3120 (org-autoload
3121 "org-feed"
3122 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3125 ;; Autoload archiving code
3126 ;; The stuff that is needed for cycling and tags has to be defined here.
3128 (defgroup org-archive nil
3129 "Options concerning archiving in Org-mode."
3130 :tag "Org Archive"
3131 :group 'org-structure)
3133 (defcustom org-archive-location "%s_archive::"
3134 "The location where subtrees should be archived.
3136 The value of this variable is a string, consisting of two parts,
3137 separated by a double-colon. The first part is a filename and
3138 the second part is a headline.
3140 When the filename is omitted, archiving happens in the same file.
3141 %s in the filename will be replaced by the current file
3142 name (without the directory part). Archiving to a different file
3143 is useful to keep archived entries from contributing to the
3144 Org-mode Agenda.
3146 The archived entries will be filed as subtrees of the specified
3147 headline. When the headline is omitted, the subtrees are simply
3148 filed away at the end of the file, as top-level entries. Also in
3149 the heading you can use %s to represent the file name, this can be
3150 useful when using the same archive for a number of different files.
3152 Here are a few examples:
3153 \"%s_archive::\"
3154 If the current file is Projects.org, archive in file
3155 Projects.org_archive, as top-level trees. This is the default.
3157 \"::* Archived Tasks\"
3158 Archive in the current file, under the top-level headline
3159 \"* Archived Tasks\".
3161 \"~/org/archive.org::\"
3162 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3164 \"~/org/archive.org::From %s\"
3165 Archive in file ~/org/archive.org (absolute path), und headlines
3166 \"From FILENAME\" where file name is the current file name.
3168 \"basement::** Finished Tasks\"
3169 Archive in file ./basement (relative path), as level 3 trees
3170 below the level 2 heading \"** Finished Tasks\".
3172 You may set this option on a per-file basis by adding to the buffer a
3173 line like
3175 #+ARCHIVE: basement::** Finished Tasks
3177 You may also define it locally for a subtree by setting an ARCHIVE property
3178 in the entry. If such a property is found in an entry, or anywhere up
3179 the hierarchy, it will be used."
3180 :group 'org-archive
3181 :type 'string)
3183 (defcustom org-archive-tag "ARCHIVE"
3184 "The tag that marks a subtree as archived.
3185 An archived subtree does not open during visibility cycling, and does
3186 not contribute to the agenda listings.
3187 After changing this, font-lock must be restarted in the relevant buffers to
3188 get the proper fontification."
3189 :group 'org-archive
3190 :group 'org-keywords
3191 :type 'string)
3193 (defcustom org-agenda-skip-archived-trees t
3194 "Non-nil means, the agenda will skip any items located in archived trees.
3195 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3196 variable is no longer recommended, you should leave it at the value t.
3197 Instead, use the key `v' to cycle the archives-mode in the agenda."
3198 :group 'org-archive
3199 :group 'org-agenda-skip
3200 :type 'boolean)
3202 (defcustom org-columns-skip-arrchived-trees t
3203 "Non-nil means, irgnore archived trees when creating column view."
3204 :group 'org-archive
3205 :group 'org-properties
3206 :type 'boolean)
3208 (defcustom org-cycle-open-archived-trees nil
3209 "Non-nil means, `org-cycle' will open archived trees.
3210 An archived tree is a tree marked with the tag ARCHIVE.
3211 When nil, archived trees will stay folded. You can still open them with
3212 normal outline commands like `show-all', but not with the cycling commands."
3213 :group 'org-archive
3214 :group 'org-cycle
3215 :type 'boolean)
3217 (defcustom org-sparse-tree-open-archived-trees nil
3218 "Non-nil means sparse tree construction shows matches in archived trees.
3219 When nil, matches in these trees are highlighted, but the trees are kept in
3220 collapsed state."
3221 :group 'org-archive
3222 :group 'org-sparse-trees
3223 :type 'boolean)
3225 (defun org-cycle-hide-archived-subtrees (state)
3226 "Re-hide all archived subtrees after a visibility state change."
3227 (when (and (not org-cycle-open-archived-trees)
3228 (not (memq state '(overview folded))))
3229 (save-excursion
3230 (let* ((globalp (memq state '(contents all)))
3231 (beg (if globalp (point-min) (point)))
3232 (end (if globalp (point-max) (org-end-of-subtree t))))
3233 (org-hide-archived-subtrees beg end)
3234 (goto-char beg)
3235 (if (looking-at (concat ".*:" org-archive-tag ":"))
3236 (message "%s" (substitute-command-keys
3237 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3239 (defun org-force-cycle-archived ()
3240 "Cycle subtree even if it is archived."
3241 (interactive)
3242 (setq this-command 'org-cycle)
3243 (let ((org-cycle-open-archived-trees t))
3244 (call-interactively 'org-cycle)))
3246 (defun org-hide-archived-subtrees (beg end)
3247 "Re-hide all archived subtrees after a visibility state change."
3248 (save-excursion
3249 (let* ((re (concat ":" org-archive-tag ":")))
3250 (goto-char beg)
3251 (while (re-search-forward re end t)
3252 (and (org-on-heading-p) (hide-subtree))
3253 (org-end-of-subtree t)))))
3255 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3257 (eval-and-compile
3258 (org-autoload "org-archive"
3259 '(org-add-archive-files org-archive-subtree
3260 org-archive-to-archive-sibling org-toggle-archive-tag)))
3262 ;; Autoload Column View Code
3264 (declare-function org-columns-number-to-string "org-colview")
3265 (declare-function org-columns-get-format-and-top-level "org-colview")
3266 (declare-function org-columns-compute "org-colview")
3268 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3269 '(org-columns-number-to-string org-columns-get-format-and-top-level
3270 org-columns-compute org-agenda-columns org-columns-remove-overlays
3271 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3273 ;; Autoload ID code
3275 (declare-function org-id-store-link "org-id")
3276 (declare-function org-id-locations-load "org-id")
3277 (declare-function org-id-locations-save "org-id")
3278 (defvar org-id-track-globally)
3279 (org-autoload "org-id"
3280 '(org-id-get-create org-id-new org-id-copy org-id-get
3281 org-id-get-with-outline-path-completion
3282 org-id-get-with-outline-drilling
3283 org-id-goto org-id-find org-id-store-link))
3285 ;; Autoload Plotting Code
3287 (org-autoload "org-plot"
3288 '(org-plot/gnuplot))
3290 ;;; Variables for pre-computed regular expressions, all buffer local
3292 (defvar org-drawer-regexp nil
3293 "Matches first line of a hidden block.")
3294 (make-variable-buffer-local 'org-drawer-regexp)
3295 (defvar org-todo-regexp nil
3296 "Matches any of the TODO state keywords.")
3297 (make-variable-buffer-local 'org-todo-regexp)
3298 (defvar org-not-done-regexp nil
3299 "Matches any of the TODO state keywords except the last one.")
3300 (make-variable-buffer-local 'org-not-done-regexp)
3301 (defvar org-not-done-heading-regexp nil
3302 "Matches a TODO headline that is not done.")
3303 (make-variable-buffer-local 'org-not-done-regexp)
3304 (defvar org-todo-line-regexp nil
3305 "Matches a headline and puts TODO state into group 2 if present.")
3306 (make-variable-buffer-local 'org-todo-line-regexp)
3307 (defvar org-complex-heading-regexp nil
3308 "Matches a headline and puts everything into groups:
3309 group 1: the stars
3310 group 2: The todo keyword, maybe
3311 group 3: Priority cookie
3312 group 4: True headline
3313 group 5: Tags")
3314 (make-variable-buffer-local 'org-complex-heading-regexp)
3315 (defvar org-todo-line-tags-regexp nil
3316 "Matches a headline and puts TODO state into group 2 if present.
3317 Also put tags into group 4 if tags are present.")
3318 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3319 (defvar org-nl-done-regexp nil
3320 "Matches newline followed by a headline with the DONE keyword.")
3321 (make-variable-buffer-local 'org-nl-done-regexp)
3322 (defvar org-looking-at-done-regexp nil
3323 "Matches the DONE keyword a point.")
3324 (make-variable-buffer-local 'org-looking-at-done-regexp)
3325 (defvar org-ds-keyword-length 12
3326 "Maximum length of the Deadline and SCHEDULED keywords.")
3327 (make-variable-buffer-local 'org-ds-keyword-length)
3328 (defvar org-deadline-regexp nil
3329 "Matches the DEADLINE keyword.")
3330 (make-variable-buffer-local 'org-deadline-regexp)
3331 (defvar org-deadline-time-regexp nil
3332 "Matches the DEADLINE keyword together with a time stamp.")
3333 (make-variable-buffer-local 'org-deadline-time-regexp)
3334 (defvar org-deadline-line-regexp nil
3335 "Matches the DEADLINE keyword and the rest of the line.")
3336 (make-variable-buffer-local 'org-deadline-line-regexp)
3337 (defvar org-scheduled-regexp nil
3338 "Matches the SCHEDULED keyword.")
3339 (make-variable-buffer-local 'org-scheduled-regexp)
3340 (defvar org-scheduled-time-regexp nil
3341 "Matches the SCHEDULED keyword together with a time stamp.")
3342 (make-variable-buffer-local 'org-scheduled-time-regexp)
3343 (defvar org-closed-time-regexp nil
3344 "Matches the CLOSED keyword together with a time stamp.")
3345 (make-variable-buffer-local 'org-closed-time-regexp)
3347 (defvar org-keyword-time-regexp nil
3348 "Matches any of the 4 keywords, together with the time stamp.")
3349 (make-variable-buffer-local 'org-keyword-time-regexp)
3350 (defvar org-keyword-time-not-clock-regexp nil
3351 "Matches any of the 3 keywords, together with the time stamp.")
3352 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3353 (defvar org-maybe-keyword-time-regexp nil
3354 "Matches a timestamp, possibly preceeded by a keyword.")
3355 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3356 (defvar org-planning-or-clock-line-re nil
3357 "Matches a line with planning or clock info.")
3358 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3360 (defconst org-plain-time-of-day-regexp
3361 (concat
3362 "\\(\\<[012]?[0-9]"
3363 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3364 "\\(--?"
3365 "\\(\\<[012]?[0-9]"
3366 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3367 "\\)?")
3368 "Regular expression to match a plain time or time range.
3369 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3370 groups carry important information:
3371 0 the full match
3372 1 the first time, range or not
3373 8 the second time, if it is a range.")
3375 (defconst org-plain-time-extension-regexp
3376 (concat
3377 "\\(\\<[012]?[0-9]"
3378 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3379 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3380 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3381 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3382 groups carry important information:
3383 0 the full match
3384 7 hours of duration
3385 9 minutes of duration")
3387 (defconst org-stamp-time-of-day-regexp
3388 (concat
3389 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3390 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3391 "\\(--?"
3392 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3393 "Regular expression to match a timestamp time or time range.
3394 After a match, the following groups carry important information:
3395 0 the full match
3396 1 date plus weekday, for backreferencing to make sure both times on same day
3397 2 the first time, range or not
3398 4 the second time, if it is a range.")
3400 (defconst org-startup-options
3401 '(("fold" org-startup-folded t)
3402 ("overview" org-startup-folded t)
3403 ("nofold" org-startup-folded nil)
3404 ("showall" org-startup-folded nil)
3405 ("content" org-startup-folded content)
3406 ("hidestars" org-hide-leading-stars t)
3407 ("showstars" org-hide-leading-stars nil)
3408 ("odd" org-odd-levels-only t)
3409 ("oddeven" org-odd-levels-only nil)
3410 ("align" org-startup-align-all-tables t)
3411 ("noalign" org-startup-align-all-tables nil)
3412 ("customtime" org-display-custom-times t)
3413 ("logdone" org-log-done time)
3414 ("lognotedone" org-log-done note)
3415 ("nologdone" org-log-done nil)
3416 ("lognoteclock-out" org-log-note-clock-out t)
3417 ("nolognoteclock-out" org-log-note-clock-out nil)
3418 ("logrepeat" org-log-repeat state)
3419 ("lognoterepeat" org-log-repeat note)
3420 ("nologrepeat" org-log-repeat nil)
3421 ("fninline" org-footnote-define-inline t)
3422 ("nofninline" org-footnote-define-inline nil)
3423 ("fnlocal" org-footnote-section nil)
3424 ("fnauto" org-footnote-auto-label t)
3425 ("fnprompt" org-footnote-auto-label nil)
3426 ("fnconfirm" org-footnote-auto-label confirm)
3427 ("fnplain" org-footnote-auto-label plain)
3428 ("fnadjust" org-footnote-auto-adjust t)
3429 ("nofnadjust" org-footnote-auto-adjust nil)
3430 ("constcgs" constants-unit-system cgs)
3431 ("constSI" constants-unit-system SI)
3432 ("noptag" org-tag-persistent-alist nil)
3433 ("hideblocks" org-hide-block-startup t)
3434 ("nohideblocks" org-hide-block-startup nil))
3435 "Variable associated with STARTUP options for org-mode.
3436 Each element is a list of three items: The startup options as written
3437 in the #+STARTUP line, the corresponding variable, and the value to
3438 set this variable to if the option is found. An optional forth element PUSH
3439 means to push this value onto the list in the variable.")
3441 (defun org-set-regexps-and-options ()
3442 "Precompute regular expressions for current buffer."
3443 (when (org-mode-p)
3444 (org-set-local 'org-todo-kwd-alist nil)
3445 (org-set-local 'org-todo-key-alist nil)
3446 (org-set-local 'org-todo-key-trigger nil)
3447 (org-set-local 'org-todo-keywords-1 nil)
3448 (org-set-local 'org-done-keywords nil)
3449 (org-set-local 'org-todo-heads nil)
3450 (org-set-local 'org-todo-sets nil)
3451 (org-set-local 'org-todo-log-states nil)
3452 (org-set-local 'org-file-properties nil)
3453 (org-set-local 'org-file-tags nil)
3454 (let ((re (org-make-options-regexp
3455 '("CATEGORY" "TODO" "COLUMNS"
3456 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3457 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3458 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3459 (splitre "[ \t]+")
3460 kwds kws0 kwsa key log value cat arch tags const links hw dws
3461 tail sep kws1 prio props ftags drawers
3462 ext-setup-or-nil setup-contents (start 0))
3463 (save-excursion
3464 (save-restriction
3465 (widen)
3466 (goto-char (point-min))
3467 (while (or (and ext-setup-or-nil
3468 (string-match re ext-setup-or-nil start)
3469 (setq start (match-end 0)))
3470 (and (setq ext-setup-or-nil nil start 0)
3471 (re-search-forward re nil t)))
3472 (setq key (upcase (match-string 1 ext-setup-or-nil))
3473 value (org-match-string-no-properties 2 ext-setup-or-nil))
3474 (cond
3475 ((equal key "CATEGORY")
3476 (if (string-match "[ \t]+$" value)
3477 (setq value (replace-match "" t t value)))
3478 (setq cat value))
3479 ((member key '("SEQ_TODO" "TODO"))
3480 (push (cons 'sequence (org-split-string value splitre)) kwds))
3481 ((equal key "TYP_TODO")
3482 (push (cons 'type (org-split-string value splitre)) kwds))
3483 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3484 ;; general TODO-like setup
3485 (push (cons (intern (downcase (match-string 1 key)))
3486 (org-split-string value splitre)) kwds))
3487 ((equal key "TAGS")
3488 (setq tags (append tags (if tags '("\\n") nil)
3489 (org-split-string value splitre))))
3490 ((equal key "COLUMNS")
3491 (org-set-local 'org-columns-default-format value))
3492 ((equal key "LINK")
3493 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3494 (push (cons (match-string 1 value)
3495 (org-trim (match-string 2 value)))
3496 links)))
3497 ((equal key "PRIORITIES")
3498 (setq prio (org-split-string value " +")))
3499 ((equal key "PROPERTY")
3500 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3501 (push (cons (match-string 1 value) (match-string 2 value))
3502 props)))
3503 ((equal key "FILETAGS")
3504 (when (string-match "\\S-" value)
3505 (setq ftags
3506 (append
3507 ftags
3508 (apply 'append
3509 (mapcar (lambda (x) (org-split-string x ":"))
3510 (org-split-string value)))))))
3511 ((equal key "DRAWERS")
3512 (setq drawers (org-split-string value splitre)))
3513 ((equal key "CONSTANTS")
3514 (setq const (append const (org-split-string value splitre))))
3515 ((equal key "STARTUP")
3516 (let ((opts (org-split-string value splitre))
3517 l var val)
3518 (while (setq l (pop opts))
3519 (when (setq l (assoc l org-startup-options))
3520 (setq var (nth 1 l) val (nth 2 l))
3521 (if (not (nth 3 l))
3522 (set (make-local-variable var) val)
3523 (if (not (listp (symbol-value var)))
3524 (set (make-local-variable var) nil))
3525 (set (make-local-variable var) (symbol-value var))
3526 (add-to-list var val))))))
3527 ((equal key "ARCHIVE")
3528 (string-match " *$" value)
3529 (setq arch (replace-match "" t t value))
3530 (remove-text-properties 0 (length arch)
3531 '(face t fontified t) arch))
3532 ((equal key "SETUPFILE")
3533 (setq setup-contents (org-file-contents
3534 (expand-file-name
3535 (org-remove-double-quotes value))
3536 'noerror))
3537 (if (not ext-setup-or-nil)
3538 (setq ext-setup-or-nil setup-contents start 0)
3539 (setq ext-setup-or-nil
3540 (concat (substring ext-setup-or-nil 0 start)
3541 "\n" setup-contents "\n"
3542 (substring ext-setup-or-nil start)))))
3543 ))))
3544 (when cat
3545 (org-set-local 'org-category (intern cat))
3546 (push (cons "CATEGORY" cat) props))
3547 (when prio
3548 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3549 (setq prio (mapcar 'string-to-char prio))
3550 (org-set-local 'org-highest-priority (nth 0 prio))
3551 (org-set-local 'org-lowest-priority (nth 1 prio))
3552 (org-set-local 'org-default-priority (nth 2 prio)))
3553 (and props (org-set-local 'org-file-properties (nreverse props)))
3554 (and ftags (org-set-local 'org-file-tags
3555 (mapcar 'org-add-prop-inherited ftags)))
3556 (and drawers (org-set-local 'org-drawers drawers))
3557 (and arch (org-set-local 'org-archive-location arch))
3558 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3559 ;; Process the TODO keywords
3560 (unless kwds
3561 ;; Use the global values as if they had been given locally.
3562 (setq kwds (default-value 'org-todo-keywords))
3563 (if (stringp (car kwds))
3564 (setq kwds (list (cons org-todo-interpretation
3565 (default-value 'org-todo-keywords)))))
3566 (setq kwds (reverse kwds)))
3567 (setq kwds (nreverse kwds))
3568 (let (inter kws kw)
3569 (while (setq kws (pop kwds))
3570 (let ((kws (or
3571 (run-hook-with-args-until-success
3572 'org-todo-setup-filter-hook kws)
3573 kws)))
3574 (setq inter (pop kws) sep (member "|" kws)
3575 kws0 (delete "|" (copy-sequence kws))
3576 kwsa nil
3577 kws1 (mapcar
3578 (lambda (x)
3579 ;; 1 2
3580 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3581 (progn
3582 (setq kw (match-string 1 x)
3583 key (and (match-end 2) (match-string 2 x))
3584 log (org-extract-log-state-settings x))
3585 (push (cons kw (and key (string-to-char key))) kwsa)
3586 (and log (push log org-todo-log-states))
3588 (error "Invalid TODO keyword %s" x)))
3589 kws0)
3590 kwsa (if kwsa (append '((:startgroup))
3591 (nreverse kwsa)
3592 '((:endgroup))))
3593 hw (car kws1)
3594 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3595 tail (list inter hw (car dws) (org-last dws))))
3596 (add-to-list 'org-todo-heads hw 'append)
3597 (push kws1 org-todo-sets)
3598 (setq org-done-keywords (append org-done-keywords dws nil))
3599 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3600 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3601 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3602 (setq org-todo-sets (nreverse org-todo-sets)
3603 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3604 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3605 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3606 ;; Process the constants
3607 (when const
3608 (let (e cst)
3609 (while (setq e (pop const))
3610 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3611 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3612 (setq org-table-formula-constants-local cst)))
3614 ;; Process the tags.
3615 (when tags
3616 (let (e tgs)
3617 (while (setq e (pop tags))
3618 (cond
3619 ((equal e "{") (push '(:startgroup) tgs))
3620 ((equal e "}") (push '(:endgroup) tgs))
3621 ((equal e "\\n") (push '(:newline) tgs))
3622 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3623 (push (cons (match-string 1 e)
3624 (string-to-char (match-string 2 e)))
3625 tgs))
3626 (t (push (list e) tgs))))
3627 (org-set-local 'org-tag-alist nil)
3628 (while (setq e (pop tgs))
3629 (or (and (stringp (car e))
3630 (assoc (car e) org-tag-alist))
3631 (push e org-tag-alist)))))
3633 ;; Compute the regular expressions and other local variables
3634 (if (not org-done-keywords)
3635 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3636 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3637 (length org-scheduled-string)
3638 (length org-clock-string)
3639 (length org-closed-string)))
3640 org-drawer-regexp
3641 (concat "^[ \t]*:\\("
3642 (mapconcat 'regexp-quote org-drawers "\\|")
3643 "\\):[ \t]*$")
3644 org-not-done-keywords
3645 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3646 org-todo-regexp
3647 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3648 "\\|") "\\)\\>")
3649 org-not-done-regexp
3650 (concat "\\<\\("
3651 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3652 "\\)\\>")
3653 org-not-done-heading-regexp
3654 (concat "^\\(\\*+\\)[ \t]+\\("
3655 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3656 "\\)\\>")
3657 org-todo-line-regexp
3658 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3659 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3660 "\\)\\>\\)?[ \t]*\\(.*\\)")
3661 org-complex-heading-regexp
3662 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3663 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3664 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3665 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3666 org-nl-done-regexp
3667 (concat "\n\\*+[ \t]+"
3668 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3669 "\\)" "\\>")
3670 org-todo-line-tags-regexp
3671 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3672 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3673 (org-re
3674 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3675 org-looking-at-done-regexp
3676 (concat "^" "\\(?:"
3677 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3678 "\\>")
3679 org-deadline-regexp (concat "\\<" org-deadline-string)
3680 org-deadline-time-regexp
3681 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3682 org-deadline-line-regexp
3683 (concat "\\<\\(" org-deadline-string "\\).*")
3684 org-scheduled-regexp
3685 (concat "\\<" org-scheduled-string)
3686 org-scheduled-time-regexp
3687 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3688 org-closed-time-regexp
3689 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3690 org-keyword-time-regexp
3691 (concat "\\<\\(" org-scheduled-string
3692 "\\|" org-deadline-string
3693 "\\|" org-closed-string
3694 "\\|" org-clock-string "\\)"
3695 " *[[<]\\([^]>]+\\)[]>]")
3696 org-keyword-time-not-clock-regexp
3697 (concat "\\<\\(" org-scheduled-string
3698 "\\|" org-deadline-string
3699 "\\|" org-closed-string
3700 "\\)"
3701 " *[[<]\\([^]>]+\\)[]>]")
3702 org-maybe-keyword-time-regexp
3703 (concat "\\(\\<\\(" org-scheduled-string
3704 "\\|" org-deadline-string
3705 "\\|" org-closed-string
3706 "\\|" org-clock-string "\\)\\)?"
3707 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3708 org-planning-or-clock-line-re
3709 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3710 "\\|" org-deadline-string
3711 "\\|" org-closed-string "\\|" org-clock-string
3712 "\\)\\>\\)")
3714 (org-compute-latex-and-specials-regexp)
3715 (org-set-font-lock-defaults))))
3717 (defun org-file-contents (file &optional noerror)
3718 "Return the contents of FILE, as a string."
3719 (if (or (not file)
3720 (not (file-readable-p file)))
3721 (if noerror
3722 (progn
3723 (message "Cannot read file %s" file)
3724 (ding) (sit-for 2)
3726 (error "Cannot read file %s" file))
3727 (with-temp-buffer
3728 (insert-file-contents file)
3729 (buffer-string))))
3731 (defun org-extract-log-state-settings (x)
3732 "Extract the log state setting from a TODO keyword string.
3733 This will extract info from a string like \"WAIT(w@/!)\"."
3734 (let (kw key log1 log2)
3735 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3736 (setq kw (match-string 1 x)
3737 key (and (match-end 2) (match-string 2 x))
3738 log1 (and (match-end 3) (match-string 3 x))
3739 log2 (and (match-end 4) (match-string 4 x)))
3740 (and (or log1 log2)
3741 (list kw
3742 (and log1 (if (equal log1 "!") 'time 'note))
3743 (and log2 (if (equal log2 "!") 'time 'note)))))))
3745 (defun org-remove-keyword-keys (list)
3746 "Remove a pair of parenthesis at the end of each string in LIST."
3747 (mapcar (lambda (x)
3748 (if (string-match "(.*)$" x)
3749 (substring x 0 (match-beginning 0))
3751 list))
3753 ;; FIXME: this could be done much better, using second characters etc.
3754 (defun org-assign-fast-keys (alist)
3755 "Assign fast keys to a keyword-key alist.
3756 Respect keys that are already there."
3757 (let (new e k c c1 c2 (char ?a))
3758 (while (setq e (pop alist))
3759 (cond
3760 ((equal e '(:startgroup)) (push e new))
3761 ((equal e '(:endgroup)) (push e new))
3762 ((equal e '(:newline)) (push e new))
3764 (setq k (car e) c2 nil)
3765 (if (cdr e)
3766 (setq c (cdr e))
3767 ;; automatically assign a character.
3768 (setq c1 (string-to-char
3769 (downcase (substring
3770 k (if (= (string-to-char k) ?@) 1 0)))))
3771 (if (or (rassoc c1 new) (rassoc c1 alist))
3772 (while (or (rassoc char new) (rassoc char alist))
3773 (setq char (1+ char)))
3774 (setq c2 c1))
3775 (setq c (or c2 char)))
3776 (push (cons k c) new))))
3777 (nreverse new)))
3779 ;;; Some variables used in various places
3781 (defvar org-window-configuration nil
3782 "Used in various places to store a window configuration.")
3783 (defvar org-finish-function nil
3784 "Function to be called when `C-c C-c' is used.
3785 This is for getting out of special buffers like remember.")
3788 ;; FIXME: Occasionally check by commenting these, to make sure
3789 ;; no other functions uses these, forgetting to let-bind them.
3790 (defvar entry)
3791 (defvar last-state)
3792 (defvar date)
3794 ;; Defined somewhere in this file, but used before definition.
3795 (defvar org-html-entities)
3796 (defvar org-struct-menu)
3797 (defvar org-org-menu)
3798 (defvar org-tbl-menu)
3799 (defvar org-agenda-keymap)
3801 ;;;; Define the Org-mode
3803 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3804 (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."))
3807 ;; We use a before-change function to check if a table might need
3808 ;; an update.
3809 (defvar org-table-may-need-update t
3810 "Indicates that a table might need an update.
3811 This variable is set by `org-before-change-function'.
3812 `org-table-align' sets it back to nil.")
3813 (defun org-before-change-function (beg end)
3814 "Every change indicates that a table might need an update."
3815 (setq org-table-may-need-update t))
3816 (defvar org-mode-map)
3817 (defvar org-mode-hook nil
3818 "Mode hook for Org-mode, run after the mode was turned on.")
3819 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3820 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3821 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
3822 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
3823 (defvar org-table-buffer-is-an nil)
3824 (defconst org-outline-regexp "\\*+ ")
3826 ;;;###autoload
3827 (define-derived-mode org-mode outline-mode "Org"
3828 "Outline-based notes management and organizer, alias
3829 \"Carsten's outline-mode for keeping track of everything.\"
3831 Org-mode develops organizational tasks around a NOTES file which
3832 contains information about projects as plain text. Org-mode is
3833 implemented on top of outline-mode, which is ideal to keep the content
3834 of large files well structured. It supports ToDo items, deadlines and
3835 time stamps, which magically appear in the diary listing of the Emacs
3836 calendar. Tables are easily created with a built-in table editor.
3837 Plain text URL-like links connect to websites, emails (VM), Usenet
3838 messages (Gnus), BBDB entries, and any files related to the project.
3839 For printing and sharing of notes, an Org-mode file (or a part of it)
3840 can be exported as a structured ASCII or HTML file.
3842 The following commands are available:
3844 \\{org-mode-map}"
3846 ;; Get rid of Outline menus, they are not needed
3847 ;; Need to do this here because define-derived-mode sets up
3848 ;; the keymap so late. Still, it is a waste to call this each time
3849 ;; we switch another buffer into org-mode.
3850 (if (featurep 'xemacs)
3851 (when (boundp 'outline-mode-menu-heading)
3852 ;; Assume this is Greg's port, it used easymenu
3853 (easy-menu-remove outline-mode-menu-heading)
3854 (easy-menu-remove outline-mode-menu-show)
3855 (easy-menu-remove outline-mode-menu-hide))
3856 (define-key org-mode-map [menu-bar headings] 'undefined)
3857 (define-key org-mode-map [menu-bar hide] 'undefined)
3858 (define-key org-mode-map [menu-bar show] 'undefined))
3860 (org-load-modules-maybe)
3861 (easy-menu-add org-org-menu)
3862 (easy-menu-add org-tbl-menu)
3863 (org-install-agenda-files-menu)
3864 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3865 (org-add-to-invisibility-spec '(org-cwidth))
3866 (org-add-to-invisibility-spec '(org-hide-block . t))
3867 (when (featurep 'xemacs)
3868 (org-set-local 'line-move-ignore-invisible t))
3869 (org-set-local 'outline-regexp org-outline-regexp)
3870 (org-set-local 'outline-level 'org-outline-level)
3871 (when (and org-ellipsis
3872 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3873 (fboundp 'make-glyph-code))
3874 (unless org-display-table
3875 (setq org-display-table (make-display-table)))
3876 (set-display-table-slot
3877 org-display-table 4
3878 (vconcat (mapcar
3879 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3880 org-ellipsis)))
3881 (if (stringp org-ellipsis) org-ellipsis "..."))))
3882 (setq buffer-display-table org-display-table))
3883 (org-set-regexps-and-options)
3884 (when (and org-tag-faces (not org-tags-special-faces-re))
3885 ;; tag faces set outside customize.... force initialization.
3886 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3887 ;; Calc embedded
3888 (org-set-local 'calc-embedded-open-mode "# ")
3889 (modify-syntax-entry ?# "<")
3890 (modify-syntax-entry ?@ "w")
3891 (if org-startup-truncated (setq truncate-lines t))
3892 (org-set-local 'font-lock-unfontify-region-function
3893 'org-unfontify-region)
3894 ;; Activate before-change-function
3895 (org-set-local 'org-table-may-need-update t)
3896 (org-add-hook 'before-change-functions 'org-before-change-function nil
3897 'local)
3898 ;; Check for running clock before killing a buffer
3899 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3900 ;; Paragraphs and auto-filling
3901 (org-set-autofill-regexps)
3902 (setq indent-line-function 'org-indent-line-function)
3903 (org-update-radio-target-regexp)
3904 ;; Make sure dependence stuff works reliably, even for users who set it
3905 ;; too late :-(
3906 (if org-enforce-todo-dependencies
3907 (add-hook 'org-blocker-hook
3908 'org-block-todo-from-children-or-siblings-or-parent)
3909 (remove-hook 'org-blocker-hook
3910 'org-block-todo-from-children-or-siblings-or-parent))
3911 (if org-enforce-todo-checkbox-dependencies
3912 (add-hook 'org-blocker-hook
3913 'org-block-todo-from-checkboxes)
3914 (remove-hook 'org-blocker-hook
3915 'org-block-todo-from-checkboxes))
3917 ;; Comment characters
3918 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3919 (org-set-local 'comment-padding " ")
3921 ;; Align options lines
3922 (org-set-local
3923 'align-mode-rules-list
3924 '((org-in-buffer-settings
3925 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3926 (modes . '(org-mode)))))
3928 ;; Imenu
3929 (org-set-local 'imenu-create-index-function
3930 'org-imenu-get-tree)
3932 ;; Make isearch reveal context
3933 (if (or (featurep 'xemacs)
3934 (not (boundp 'outline-isearch-open-invisible-function)))
3935 ;; Emacs 21 and XEmacs make use of the hook
3936 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3937 ;; Emacs 22 deals with this through a special variable
3938 (org-set-local 'outline-isearch-open-invisible-function
3939 (lambda (&rest ignore) (org-show-context 'isearch))))
3941 ;; If empty file that did not turn on org-mode automatically, make it to.
3942 (if (and org-insert-mode-line-in-empty-file
3943 (interactive-p)
3944 (= (point-min) (point-max)))
3945 (insert "# -*- mode: org -*-\n\n"))
3947 (unless org-inhibit-startup
3948 (when org-startup-align-all-tables
3949 (let ((bmp (buffer-modified-p)))
3950 (org-table-map-tables 'org-table-align)
3951 (set-buffer-modified-p bmp)))
3952 (org-set-startup-visibility)))
3954 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3956 (defun org-current-time ()
3957 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3958 (if (> (car org-time-stamp-rounding-minutes) 1)
3959 (let ((r (car org-time-stamp-rounding-minutes))
3960 (time (decode-time)))
3961 (apply 'encode-time
3962 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3963 (nthcdr 2 time))))
3964 (current-time)))
3966 ;;;; Font-Lock stuff, including the activators
3968 (defvar org-mouse-map (make-sparse-keymap))
3969 (org-defkey org-mouse-map
3970 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3971 (org-defkey org-mouse-map
3972 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3973 (when org-mouse-1-follows-link
3974 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3975 (when org-tab-follows-link
3976 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3977 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3979 (require 'font-lock)
3981 (defconst org-non-link-chars "]\t\n\r<>")
3982 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3983 "shell" "elisp"))
3984 (defvar org-link-types-re nil
3985 "Matches a link that has a url-like prefix like \"http:\"")
3986 (defvar org-link-re-with-space nil
3987 "Matches a link with spaces, optional angular brackets around it.")
3988 (defvar org-link-re-with-space2 nil
3989 "Matches a link with spaces, optional angular brackets around it.")
3990 (defvar org-link-re-with-space3 nil
3991 "Matches a link with spaces, only for internal part in bracket links.")
3992 (defvar org-angle-link-re nil
3993 "Matches link with angular brackets, spaces are allowed.")
3994 (defvar org-plain-link-re nil
3995 "Matches plain link, without spaces.")
3996 (defvar org-bracket-link-regexp nil
3997 "Matches a link in double brackets.")
3998 (defvar org-bracket-link-analytic-regexp nil
3999 "Regular expression used to analyze links.
4000 Here is what the match groups contain after a match:
4001 1: http:
4002 2: http
4003 3: path
4004 4: [desc]
4005 5: desc")
4006 (defvar org-bracket-link-analytic-regexp++ nil
4007 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4008 (defvar org-any-link-re nil
4009 "Regular expression matching any link.")
4011 (defun org-make-link-regexps ()
4012 "Update the link regular expressions.
4013 This should be called after the variable `org-link-types' has changed."
4014 (setq org-link-types-re
4015 (concat
4016 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4017 org-link-re-with-space
4018 (concat
4019 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4020 "\\([^" org-non-link-chars " ]"
4021 "[^" org-non-link-chars "]*"
4022 "[^" org-non-link-chars " ]\\)>?")
4023 org-link-re-with-space2
4024 (concat
4025 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4026 "\\([^" org-non-link-chars " ]"
4027 "[^\t\n\r]*"
4028 "[^" org-non-link-chars " ]\\)>?")
4029 org-link-re-with-space3
4030 (concat
4031 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4032 "\\([^" org-non-link-chars " ]"
4033 "[^\t\n\r]*\\)")
4034 org-angle-link-re
4035 (concat
4036 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4037 "\\([^" org-non-link-chars " ]"
4038 "[^" org-non-link-chars "]*"
4039 "\\)>")
4040 org-plain-link-re
4041 (concat
4042 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4043 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4044 org-bracket-link-regexp
4045 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4046 org-bracket-link-analytic-regexp
4047 (concat
4048 "\\[\\["
4049 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4050 "\\([^]]+\\)"
4051 "\\]"
4052 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4053 "\\]")
4054 org-bracket-link-analytic-regexp++
4055 (concat
4056 "\\[\\["
4057 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4058 "\\([^]]+\\)"
4059 "\\]"
4060 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4061 "\\]")
4062 org-any-link-re
4063 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4064 org-angle-link-re "\\)\\|\\("
4065 org-plain-link-re "\\)")))
4067 (org-make-link-regexps)
4069 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4070 "Regular expression for fast time stamp matching.")
4071 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4072 "Regular expression for fast time stamp matching.")
4073 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4074 "Regular expression matching time strings for analysis.
4075 This one does not require the space after the date, so it can be used
4076 on a string that terminates immediately after the date.")
4077 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4078 "Regular expression matching time strings for analysis.")
4079 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4080 "Regular expression matching time stamps, with groups.")
4081 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4082 "Regular expression matching time stamps (also [..]), with groups.")
4083 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4084 "Regular expression matching a time stamp range.")
4085 (defconst org-tr-regexp-both
4086 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4087 "Regular expression matching a time stamp range.")
4088 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4089 org-ts-regexp "\\)?")
4090 "Regular expression matching a time stamp or time stamp range.")
4091 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4092 org-ts-regexp-both "\\)?")
4093 "Regular expression matching a time stamp or time stamp range.
4094 The time stamps may be either active or inactive.")
4096 (defvar org-emph-face nil)
4098 (defun org-do-emphasis-faces (limit)
4099 "Run through the buffer and add overlays to links."
4100 (let (rtn a)
4101 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4102 (if (not (= (char-after (match-beginning 3))
4103 (char-after (match-beginning 4))))
4104 (progn
4105 (setq rtn t)
4106 (setq a (assoc (match-string 3) org-emphasis-alist))
4107 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4108 'face
4109 (nth 1 a))
4110 (and (nth 4 a)
4111 (org-remove-flyspell-overlays-in
4112 (match-beginning 0) (match-end 0)))
4113 (add-text-properties (match-beginning 2) (match-end 2)
4114 '(font-lock-multiline t))
4115 (when org-hide-emphasis-markers
4116 (add-text-properties (match-end 4) (match-beginning 5)
4117 '(invisible org-link))
4118 (add-text-properties (match-beginning 3) (match-end 3)
4119 '(invisible org-link)))))
4120 (backward-char 1))
4121 rtn))
4123 (defun org-emphasize (&optional char)
4124 "Insert or change an emphasis, i.e. a font like bold or italic.
4125 If there is an active region, change that region to a new emphasis.
4126 If there is no region, just insert the marker characters and position
4127 the cursor between them.
4128 CHAR should be either the marker character, or the first character of the
4129 HTML tag associated with that emphasis. If CHAR is a space, the means
4130 to remove the emphasis of the selected region.
4131 If char is not given (for example in an interactive call) it
4132 will be prompted for."
4133 (interactive)
4134 (let ((eal org-emphasis-alist) e det
4135 (erc org-emphasis-regexp-components)
4136 (prompt "")
4137 (string "") beg end move tag c s)
4138 (if (org-region-active-p)
4139 (setq beg (region-beginning) end (region-end)
4140 string (buffer-substring beg end))
4141 (setq move t))
4143 (while (setq e (pop eal))
4144 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4145 c (aref tag 0))
4146 (push (cons c (string-to-char (car e))) det)
4147 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4148 (substring tag 1)))))
4149 (setq det (nreverse det))
4150 (unless char
4151 (message "%s" (concat "Emphasis marker or tag:" prompt))
4152 (setq char (read-char-exclusive)))
4153 (setq char (or (cdr (assoc char det)) char))
4154 (if (equal char ?\ )
4155 (setq s "" move nil)
4156 (unless (assoc (char-to-string char) org-emphasis-alist)
4157 (error "No such emphasis marker: \"%c\"" char))
4158 (setq s (char-to-string char)))
4159 (while (and (> (length string) 1)
4160 (equal (substring string 0 1) (substring string -1))
4161 (assoc (substring string 0 1) org-emphasis-alist))
4162 (setq string (substring string 1 -1)))
4163 (setq string (concat s string s))
4164 (if beg (delete-region beg end))
4165 (unless (or (bolp)
4166 (string-match (concat "[" (nth 0 erc) "\n]")
4167 (char-to-string (char-before (point)))))
4168 (insert " "))
4169 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4170 (char-to-string (char-after (point))))
4171 (insert " ") (backward-char 1))
4172 (insert string)
4173 (and move (backward-char 1))))
4175 (defconst org-nonsticky-props
4176 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4178 (defsubst org-rear-nonsticky-at (pos)
4179 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4181 (defun org-activate-plain-links (limit)
4182 "Run through the buffer and add overlays to links."
4183 (catch 'exit
4184 (let (f)
4185 (if (re-search-forward org-plain-link-re limit t)
4186 (progn
4187 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4188 (setq f (get-text-property (match-beginning 0) 'face))
4189 (if (or (eq f 'org-tag)
4190 (and (listp f) (memq 'org-tag f)))
4192 (add-text-properties (match-beginning 0) (match-end 0)
4193 (list 'mouse-face 'highlight
4194 'keymap org-mouse-map))
4195 (org-rear-nonsticky-at (match-end 0)))
4196 t)))))
4198 (defun org-activate-code (limit)
4199 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4200 (progn
4201 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4202 (remove-text-properties (match-beginning 0) (match-end 0)
4203 '(display t invisible t intangible t))
4204 t)))
4206 (defun org-fontify-meta-lines-and-blocks (limit)
4207 "Fontify #+ lines and blocks, in the correct ways."
4208 (let ((case-fold-search t))
4209 (if (re-search-forward
4210 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4211 limit t)
4212 (let ((beg (match-beginning 0))
4213 (beg1 (line-beginning-position 2))
4214 (dc1 (downcase (match-string 2)))
4215 (dc3 (downcase (match-string 3)))
4216 end end1 quoting)
4217 (cond
4218 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4219 ;; a single line of backend-specific content
4220 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4221 (remove-text-properties (match-beginning 0) (match-end 0)
4222 '(display t invisible t intangible t))
4223 (add-text-properties (match-beginning 1) (match-end 3)
4224 '(font-lock-fontified t face org-meta-line))
4225 (add-text-properties (match-beginning 6) (match-end 6)
4226 '(font-lock-fontified t face org-block))
4228 ((and (match-end 4) (equal dc3 "begin"))
4229 ;; Truely a block
4230 (setq quoting (member (downcase (match-string 5))
4231 org-protecting-blocks))
4232 (when (re-search-forward
4233 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4234 nil t) ;; on purpose, we look further than LIMIT
4235 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4236 (when quoting
4237 (remove-text-properties beg end
4238 '(display t invisible t intangible t)))
4239 (add-text-properties
4240 beg end
4241 '(font-lock-fontified t font-lock-multiline t))
4242 (add-text-properties beg beg1 '(face org-meta-line))
4243 (add-text-properties end1 end '(face org-meta-line))
4244 (when quoting
4245 (add-text-properties beg1 end1 '(face org-block)))
4247 ((not (member (char-after beg) '(?\ ?\t)))
4248 ;; just any other in-buffer setting, but not indented
4249 (add-text-properties
4250 beg (match-end 0)
4251 '(font-lock-fontified t face org-meta-line))
4253 ((or (member dc1 '("caption:" "label:" "orgtbl:" "tblfm:" "tblname:"))
4254 (and (match-end 4) (equal dc3 "attr")))
4255 (add-text-properties
4256 beg (match-end 0)
4257 '(font-lock-fontified t face org-meta-line))
4259 (t nil))))))
4261 (defun org-activate-angle-links (limit)
4262 "Run through the buffer and add overlays to links."
4263 (if (re-search-forward org-angle-link-re limit t)
4264 (progn
4265 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4266 (add-text-properties (match-beginning 0) (match-end 0)
4267 (list 'mouse-face 'highlight
4268 'keymap org-mouse-map))
4269 (org-rear-nonsticky-at (match-end 0))
4270 t)))
4272 (defun org-activate-footnote-links (limit)
4273 "Run through the buffer and add overlays to links."
4274 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4275 limit t)
4276 (progn
4277 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4278 (add-text-properties (match-beginning 2) (match-end 2)
4279 (list 'mouse-face 'highlight
4280 'keymap org-mouse-map
4281 'help-echo
4282 (if (= (point-at-bol) (match-beginning 2))
4283 "Footnote definition"
4284 "Footnote reference")
4286 (org-rear-nonsticky-at (match-end 2))
4287 t)))
4289 (defun org-activate-bracket-links (limit)
4290 "Run through the buffer and add overlays to bracketed links."
4291 (if (re-search-forward org-bracket-link-regexp limit t)
4292 (let* ((help (concat "LINK: "
4293 (org-match-string-no-properties 1)))
4294 ;; FIXME: above we should remove the escapes.
4295 ;; but that requires another match, protecting match data,
4296 ;; a lot of overhead for font-lock.
4297 (ip (org-maybe-intangible
4298 (list 'invisible 'org-link
4299 'keymap org-mouse-map 'mouse-face 'highlight
4300 'font-lock-multiline t 'help-echo help)))
4301 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4302 'font-lock-multiline t 'help-echo help)))
4303 ;; We need to remove the invisible property here. Table narrowing
4304 ;; may have made some of this invisible.
4305 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4306 (remove-text-properties (match-beginning 0) (match-end 0)
4307 '(invisible nil))
4308 (if (match-end 3)
4309 (progn
4310 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4311 (org-rear-nonsticky-at (match-beginning 3))
4312 (add-text-properties (match-beginning 3) (match-end 3) vp)
4313 (org-rear-nonsticky-at (match-end 3))
4314 (add-text-properties (match-end 3) (match-end 0) ip)
4315 (org-rear-nonsticky-at (match-end 0)))
4316 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4317 (org-rear-nonsticky-at (match-beginning 1))
4318 (add-text-properties (match-beginning 1) (match-end 1) vp)
4319 (org-rear-nonsticky-at (match-end 1))
4320 (add-text-properties (match-end 1) (match-end 0) ip)
4321 (org-rear-nonsticky-at (match-end 0)))
4322 t)))
4324 (defun org-activate-dates (limit)
4325 "Run through the buffer and add overlays to dates."
4326 (if (re-search-forward org-tsr-regexp-both limit t)
4327 (progn
4328 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4329 (add-text-properties (match-beginning 0) (match-end 0)
4330 (list 'mouse-face 'highlight
4331 'keymap org-mouse-map))
4332 (org-rear-nonsticky-at (match-end 0))
4333 (when org-display-custom-times
4334 (if (match-end 3)
4335 (org-display-custom-time (match-beginning 3) (match-end 3)))
4336 (org-display-custom-time (match-beginning 1) (match-end 1)))
4337 t)))
4339 (defvar org-target-link-regexp nil
4340 "Regular expression matching radio targets in plain text.")
4341 (make-variable-buffer-local 'org-target-link-regexp)
4342 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4343 "Regular expression matching a link target.")
4344 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4345 "Regular expression matching a radio target.")
4346 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4347 "Regular expression matching any target.")
4349 (defun org-activate-target-links (limit)
4350 "Run through the buffer and add overlays to target matches."
4351 (when org-target-link-regexp
4352 (let ((case-fold-search t))
4353 (if (re-search-forward org-target-link-regexp limit t)
4354 (progn
4355 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4356 (add-text-properties (match-beginning 0) (match-end 0)
4357 (list 'mouse-face 'highlight
4358 'keymap org-mouse-map
4359 'help-echo "Radio target link"
4360 'org-linked-text t))
4361 (org-rear-nonsticky-at (match-end 0))
4362 t)))))
4364 (defun org-update-radio-target-regexp ()
4365 "Find all radio targets in this file and update the regular expression."
4366 (interactive)
4367 (when (memq 'radio org-activate-links)
4368 (setq org-target-link-regexp
4369 (org-make-target-link-regexp (org-all-targets 'radio)))
4370 (org-restart-font-lock)))
4372 (defun org-hide-wide-columns (limit)
4373 (let (s e)
4374 (setq s (text-property-any (point) (or limit (point-max))
4375 'org-cwidth t))
4376 (when s
4377 (setq e (next-single-property-change s 'org-cwidth))
4378 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4379 (goto-char e)
4380 t)))
4382 (defvar org-latex-and-specials-regexp nil
4383 "Regular expression for highlighting export special stuff.")
4384 (defvar org-match-substring-regexp)
4385 (defvar org-match-substring-with-braces-regexp)
4386 (defvar org-export-html-special-string-regexps)
4388 (defun org-compute-latex-and-specials-regexp ()
4389 "Compute regular expression for stuff treated specially by exporters."
4390 (if (not org-highlight-latex-fragments-and-specials)
4391 (org-set-local 'org-latex-and-specials-regexp nil)
4392 (require 'org-exp)
4393 (let*
4394 ((matchers (plist-get org-format-latex-options :matchers))
4395 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4396 org-latex-regexps)))
4397 (options (org-combine-plists (org-default-export-plist)
4398 (org-infile-export-plist)))
4399 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4400 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4401 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4402 (org-export-html-expand (plist-get options :expand-quoted-html))
4403 (org-export-with-special-strings (plist-get options :special-strings))
4404 (re-sub
4405 (cond
4406 ((equal org-export-with-sub-superscripts '{})
4407 (list org-match-substring-with-braces-regexp))
4408 (org-export-with-sub-superscripts
4409 (list org-match-substring-regexp))
4410 (t nil)))
4411 (re-latex
4412 (if org-export-with-LaTeX-fragments
4413 (mapcar (lambda (x) (nth 1 x)) latexs)))
4414 (re-macros
4415 (if org-export-with-TeX-macros
4416 (list (concat "\\\\"
4417 (regexp-opt
4418 (append (mapcar 'car org-html-entities)
4419 (if (boundp 'org-latex-entities)
4420 (mapcar (lambda (x)
4421 (or (car-safe x) x))
4422 org-latex-entities)
4423 nil))
4424 'words))) ; FIXME
4426 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4427 (re-special (if org-export-with-special-strings
4428 (mapcar (lambda (x) (car x))
4429 org-export-html-special-string-regexps)))
4430 (re-rest
4431 (delq nil
4432 (list
4433 (if org-export-html-expand "@<[^>\n]+>")
4434 ))))
4435 (org-set-local
4436 'org-latex-and-specials-regexp
4437 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4438 re-rest) "\\|")))))
4440 (defun org-do-latex-and-special-faces (limit)
4441 "Run through the buffer and add overlays to links."
4442 (when org-latex-and-specials-regexp
4443 (let (rtn d)
4444 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4445 limit t))
4446 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4447 'face))
4448 '(org-code org-verbatim underline)))
4449 (progn
4450 (setq rtn t
4451 d (cond ((member (char-after (1+ (match-beginning 0)))
4452 '(?_ ?^)) 1)
4453 (t 0)))
4454 (font-lock-prepend-text-property
4455 (+ d (match-beginning 0)) (match-end 0)
4456 'face 'org-latex-and-export-specials)
4457 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4458 '(font-lock-multiline t)))))
4459 rtn)))
4461 (defun org-restart-font-lock ()
4462 "Restart font-lock-mode, to force refontification."
4463 (when (and (boundp 'font-lock-mode) font-lock-mode)
4464 (font-lock-mode -1)
4465 (font-lock-mode 1)))
4467 (defun org-all-targets (&optional radio)
4468 "Return a list of all targets in this file.
4469 With optional argument RADIO, only find radio targets."
4470 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4471 rtn)
4472 (save-excursion
4473 (goto-char (point-min))
4474 (while (re-search-forward re nil t)
4475 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4476 rtn)))
4478 (defun org-make-target-link-regexp (targets)
4479 "Make regular expression matching all strings in TARGETS.
4480 The regular expression finds the targets also if there is a line break
4481 between words."
4482 (and targets
4483 (concat
4484 "\\<\\("
4485 (mapconcat
4486 (lambda (x)
4487 (while (string-match " +" x)
4488 (setq x (replace-match "\\s-+" t t x)))
4490 targets
4491 "\\|")
4492 "\\)\\>")))
4494 (defun org-activate-tags (limit)
4495 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4496 (progn
4497 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4498 (add-text-properties (match-beginning 1) (match-end 1)
4499 (list 'mouse-face 'highlight
4500 'keymap org-mouse-map))
4501 (org-rear-nonsticky-at (match-end 1))
4502 t)))
4504 (defun org-outline-level ()
4505 (save-excursion
4506 (looking-at outline-regexp)
4507 (if (match-beginning 1)
4508 (+ (org-get-string-indentation (match-string 1)) 1000)
4509 (1- (- (match-end 0) (match-beginning 0))))))
4511 (defvar org-font-lock-keywords nil)
4513 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4514 "Regular expression matching a property line.")
4516 (defvar org-font-lock-hook nil
4517 "Functions to be called for special font lock stuff.")
4519 (defun org-font-lock-hook (limit)
4520 (run-hook-with-args 'org-font-lock-hook limit))
4522 (defun org-set-font-lock-defaults ()
4523 (let* ((em org-fontify-emphasized-text)
4524 (lk org-activate-links)
4525 (org-font-lock-extra-keywords
4526 (list
4527 ;; Call the hook
4528 '(org-font-lock-hook)
4529 ;; Headlines
4530 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4531 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4532 ;; Table lines
4533 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4534 (1 'org-table t))
4535 ;; Table internals
4536 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4537 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4538 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4539 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4540 ;; Drawers
4541 (list org-drawer-regexp '(0 'org-special-keyword t))
4542 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4543 ;; Properties
4544 (list org-property-re
4545 '(1 'org-special-keyword t)
4546 '(3 'org-property-value t))
4547 ;; Links
4548 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4549 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4550 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4551 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4552 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4553 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4554 (if (memq 'footnote lk) '(org-activate-footnote-links
4555 (2 'org-footnote t)))
4556 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4557 '(org-hide-wide-columns (0 nil append))
4558 ;; TODO lines
4559 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4560 '(1 (org-get-todo-face 1) t))
4561 ;; DONE
4562 (if org-fontify-done-headline
4563 (list (concat "^[*]+ +\\<\\("
4564 (mapconcat 'regexp-quote org-done-keywords "\\|")
4565 "\\)\\(.*\\)")
4566 '(2 'org-headline-done t))
4567 nil)
4568 ;; Priorities
4569 '(org-font-lock-add-priority-faces)
4570 ;; Tags
4571 '(org-font-lock-add-tag-faces)
4572 ;; Special keywords
4573 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4574 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4575 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4576 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4577 ;; Emphasis
4578 (if em
4579 (if (featurep 'xemacs)
4580 '(org-do-emphasis-faces (0 nil append))
4581 '(org-do-emphasis-faces)))
4582 ;; Checkboxes
4583 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4584 2 'org-checkbox prepend)
4585 (if org-provide-checkbox-statistics
4586 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4587 (0 (org-get-checkbox-statistics-face) t)))
4588 ;; Description list items
4589 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4590 2 'bold prepend)
4591 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4592 '(1 'org-archived prepend))
4593 ;; Specials
4594 '(org-do-latex-and-special-faces)
4595 ;; Code
4596 '(org-activate-code (1 'org-code t))
4597 ;; COMMENT
4598 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4599 "\\|" org-quote-string "\\)\\>")
4600 '(1 'org-special-keyword t))
4601 '("^#.*" (0 'font-lock-comment-face t))
4602 ;; Blocks and meta lines
4603 '(org-fontify-meta-lines-and-blocks)
4605 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4606 ;; Now set the full font-lock-keywords
4607 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4608 (org-set-local 'font-lock-defaults
4609 '(org-font-lock-keywords t nil nil backward-paragraph))
4610 (kill-local-variable 'font-lock-keywords) nil))
4612 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4613 "Fontify string S like in Org-mode"
4614 (with-temp-buffer
4615 (insert s)
4616 (let ((org-odd-levels-only odd-levels))
4617 (org-mode)
4618 (font-lock-fontify-buffer)
4619 (buffer-string))))
4621 (defvar org-m nil)
4622 (defvar org-l nil)
4623 (defvar org-f nil)
4624 (defun org-get-level-face (n)
4625 "Get the right face for match N in font-lock matching of headlines."
4626 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4627 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4628 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4629 (cond
4630 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4631 ((eq n 2) org-f)
4632 (t (if org-level-color-stars-only nil org-f))))
4634 (defun org-get-todo-face (kwd)
4635 "Get the right face for a TODO keyword KWD.
4636 If KWD is a number, get the corresponding match group."
4637 (if (numberp kwd) (setq kwd (match-string kwd)))
4638 (or (cdr (assoc kwd org-todo-keyword-faces))
4639 (and (member kwd org-done-keywords) 'org-done)
4640 'org-todo))
4642 (defun org-font-lock-add-tag-faces (limit)
4643 "Add the special tag faces."
4644 (when (and org-tag-faces org-tags-special-faces-re)
4645 (while (re-search-forward org-tags-special-faces-re limit t)
4646 (add-text-properties (match-beginning 1) (match-end 1)
4647 (list 'face (org-get-tag-face 1)
4648 'font-lock-fontified t))
4649 (backward-char 1))))
4651 (defun org-font-lock-add-priority-faces (limit)
4652 "Add the special priority faces."
4653 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4654 (add-text-properties
4655 (match-beginning 0) (match-end 0)
4656 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4657 org-priority-faces))
4658 'org-special-keyword)
4659 'font-lock-fontified t))))
4661 (defun org-get-tag-face (kwd)
4662 "Get the right face for a TODO keyword KWD.
4663 If KWD is a number, get the corresponding match group."
4664 (if (numberp kwd) (setq kwd (match-string kwd)))
4665 (or (cdr (assoc kwd org-tag-faces))
4666 'org-tag))
4668 (defun org-unfontify-region (beg end &optional maybe_loudly)
4669 "Remove fontification and activation overlays from links."
4670 (font-lock-default-unfontify-region beg end)
4671 (let* ((buffer-undo-list t)
4672 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4673 (inhibit-modification-hooks t)
4674 deactivate-mark buffer-file-name buffer-file-truename)
4675 (remove-text-properties beg end
4676 '(mouse-face t keymap t org-linked-text t
4677 invisible t intangible t
4678 org-no-flyspell t))))
4680 ;;;; Visibility cycling, including org-goto and indirect buffer
4682 ;;; Cycling
4684 (defvar org-cycle-global-status nil)
4685 (make-variable-buffer-local 'org-cycle-global-status)
4686 (defvar org-cycle-subtree-status nil)
4687 (make-variable-buffer-local 'org-cycle-subtree-status)
4689 ;;;###autoload
4691 (defvar org-inlinetask-min-level)
4693 (defun org-cycle (&optional arg)
4694 "TAB-action and visibility cycling for Org-mode.
4696 This is the command invoked in Org-moe by the TAB key. It's main purpose
4697 is outine visibility cycling, but it also invokes other actions
4698 in special contexts.
4700 - When this function is called with a prefix argument, rotate the entire
4701 buffer through 3 states (global cycling)
4702 1. OVERVIEW: Show only top-level headlines.
4703 2. CONTENTS: Show all headlines of all levels, but no body text.
4704 3. SHOW ALL: Show everything.
4705 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4706 determined by the variable `org-startup-folded', and by any VISIBILITY
4707 properties in the buffer.
4708 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4709 including any drawers.
4711 - When inside a table, re-align the table and move to the next field.
4713 - When point is at the beginning of a headline, rotate the subtree started
4714 by this line through 3 different states (local cycling)
4715 1. FOLDED: Only the main headline is shown.
4716 2. CHILDREN: The main headline and the direct children are shown.
4717 From this state, you can move to one of the children
4718 and zoom in further.
4719 3. SUBTREE: Show the entire subtree, including body text.
4721 - When there is a numeric prefix, go up to a heading with level ARG, do
4722 a `show-subtree' and return to the previous cursor position. If ARG
4723 is negative, go up that many levels.
4725 - When point is not at the beginning of a headline, execute the global
4726 binding for TAB, which is re-indenting the line. See the option
4727 `org-cycle-emulate-tab' for details.
4729 - Special case: if point is at the beginning of the buffer and there is
4730 no headline in line 1, this function will act as if called with prefix arg.
4731 But only if also the variable `org-cycle-global-at-bob' is t."
4732 (interactive "P")
4733 (org-load-modules-maybe)
4734 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4735 (let* ((limit-level
4736 (or org-cycle-max-level
4737 (and (boundp 'org-inlinetask-min-level)
4738 org-inlinetask-min-level
4739 (1- org-inlinetask-min-level))))
4740 (nstars (and limit-level
4741 (if org-odd-levels-only
4742 (and limit-level (1- (* limit-level 2)))
4743 limit-level)))
4744 (outline-regexp
4745 (cond
4746 ((not (org-mode-p)) outline-regexp)
4747 ((or (eq org-cycle-include-plain-lists 'integrate)
4748 (and org-cycle-include-plain-lists (org-at-item-p)))
4749 (concat "\\(?:\\*"
4750 (if nstars (format "\\{1,%d\\}" nstars) "+")
4751 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4752 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4753 (bob-special (and org-cycle-global-at-bob (bobp)
4754 (not (looking-at outline-regexp))))
4755 (org-cycle-hook
4756 (if bob-special
4757 (delq 'org-optimize-window-after-visibility-change
4758 (copy-sequence org-cycle-hook))
4759 org-cycle-hook))
4760 (pos (point)))
4762 (if (or bob-special (equal arg '(4)))
4763 ;; special case: use global cycling
4764 (setq arg t))
4766 (cond
4768 ((equal arg '(16))
4769 (org-set-startup-visibility)
4770 (message "Startup visibility, plus VISIBILITY properties"))
4772 ((equal arg '(64))
4773 (show-all)
4774 (message "Entire buffer visible, including drawers"))
4776 ((org-at-table-p 'any)
4777 ;; Enter the table or move to the next field in the table
4778 (or (org-table-recognize-table.el)
4779 (progn
4780 (if arg (org-table-edit-field t)
4781 (org-table-justify-field-maybe)
4782 (call-interactively 'org-table-next-field)))))
4784 ((run-hook-with-args-until-success
4785 'org-tab-after-check-for-table-hook))
4787 ((eq arg t) ;; Global cycling
4788 (org-cycle-internal-global))
4790 ((and org-drawers org-drawer-regexp
4791 (save-excursion
4792 (beginning-of-line 1)
4793 (looking-at org-drawer-regexp)))
4794 ;; Toggle block visibility
4795 (org-flag-drawer
4796 (not (get-char-property (match-end 0) 'invisible))))
4798 ((integerp arg)
4799 ;; Show-subtree, ARG levels up from here.
4800 (save-excursion
4801 (org-back-to-heading)
4802 (outline-up-heading (if (< arg 0) (- arg)
4803 (- (funcall outline-level) arg)))
4804 (org-show-subtree)))
4806 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4807 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4809 (org-cycle-internal-local))
4811 ;; TAB emulation and template completion
4812 (buffer-read-only (org-back-to-heading))
4814 ((run-hook-with-args-until-success
4815 'org-tab-after-check-for-cycling-hook))
4817 ((org-try-structure-completion))
4819 ((org-try-cdlatex-tab))
4821 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4822 (or (not (bolp))
4823 (not (looking-at outline-regexp))))
4824 (call-interactively (global-key-binding "\t")))
4826 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4827 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4828 (or (and (eq org-cycle-emulate-tab 'white)
4829 (= (match-end 0) (point-at-eol)))
4830 (and (eq org-cycle-emulate-tab 'whitestart)
4831 (>= (match-end 0) pos))))
4833 (eq org-cycle-emulate-tab t))
4834 (call-interactively (global-key-binding "\t")))
4836 (t (save-excursion
4837 (org-back-to-heading)
4838 (org-cycle)))))))
4840 (defun org-cycle-internal-global ()
4841 "Do the global cycling action."
4842 (cond
4843 ((and (eq last-command this-command)
4844 (eq org-cycle-global-status 'overview))
4845 ;; We just created the overview - now do table of contents
4846 ;; This can be slow in very large buffers, so indicate action
4847 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4848 (message "CONTENTS...")
4849 (org-content)
4850 (message "CONTENTS...done")
4851 (setq org-cycle-global-status 'contents)
4852 (run-hook-with-args 'org-cycle-hook 'contents))
4854 ((and (eq last-command this-command)
4855 (eq org-cycle-global-status 'contents))
4856 ;; We just showed the table of contents - now show everything
4857 (run-hook-with-args 'org-pre-cycle-hook 'all)
4858 (show-all)
4859 (message "SHOW ALL")
4860 (setq org-cycle-global-status 'all)
4861 (run-hook-with-args 'org-cycle-hook 'all))
4864 ;; Default action: go to overview
4865 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4866 (org-overview)
4867 (message "OVERVIEW")
4868 (setq org-cycle-global-status 'overview)
4869 (run-hook-with-args 'org-cycle-hook 'overview))))
4871 (defun org-cycle-internal-local ()
4872 "Do the local cycling action."
4873 (org-back-to-heading)
4874 (let ((goal-column 0) eoh eol eos)
4875 ;; First, some boundaries
4876 (save-excursion
4877 (org-back-to-heading)
4878 (save-excursion
4879 (beginning-of-line 2)
4880 (while (and (not (eobp)) ;; this is like `next-line'
4881 (get-char-property (1- (point)) 'invisible))
4882 (beginning-of-line 2)) (setq eol (point)))
4883 (outline-end-of-heading) (setq eoh (point))
4884 (org-end-of-subtree t)
4885 (unless (eobp)
4886 (skip-chars-forward " \t\n")
4887 (beginning-of-line 1) ; in case this is an item
4889 (setq eos (1- (point))))
4890 ;; Find out what to do next and set `this-command'
4891 (cond
4892 ((= eos eoh)
4893 ;; Nothing is hidden behind this heading
4894 (run-hook-with-args 'org-pre-cycle-hook 'empty)
4895 (message "EMPTY ENTRY")
4896 (setq org-cycle-subtree-status nil)
4897 (save-excursion
4898 (goto-char eos)
4899 (outline-next-heading)
4900 (if (org-invisible-p) (org-flag-heading nil))))
4901 ((or (>= eol eos)
4902 (not (string-match "\\S-" (buffer-substring eol eos))))
4903 ;; Entire subtree is hidden in one line: open it
4904 (run-hook-with-args 'org-pre-cycle-hook 'children)
4905 (org-show-entry)
4906 (show-children)
4907 (message "CHILDREN")
4908 (save-excursion
4909 (goto-char eos)
4910 (outline-next-heading)
4911 (if (org-invisible-p) (org-flag-heading nil)))
4912 (setq org-cycle-subtree-status 'children)
4913 (run-hook-with-args 'org-cycle-hook 'children))
4914 ((and (eq last-command this-command)
4915 (eq org-cycle-subtree-status 'children))
4916 ;; We just showed the children, now show everything.
4917 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
4918 (org-show-subtree)
4919 (message "SUBTREE")
4920 (setq org-cycle-subtree-status 'subtree)
4921 (run-hook-with-args 'org-cycle-hook 'subtree))
4923 ;; Default action: hide the subtree.
4924 (run-hook-with-args 'org-pre-cycle-hook 'folded)
4925 (hide-subtree)
4926 (message "FOLDED")
4927 (setq org-cycle-subtree-status 'folded)
4928 (run-hook-with-args 'org-cycle-hook 'folded)))))
4930 ;;;###autoload
4931 (defun org-global-cycle (&optional arg)
4932 "Cycle the global visibility. For details see `org-cycle'.
4933 With C-u prefix arg, switch to startup visibility.
4934 With a numeric prefix, show all headlines up to that level."
4935 (interactive "P")
4936 (let ((org-cycle-include-plain-lists
4937 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4938 (cond
4939 ((integerp arg)
4940 (show-all)
4941 (hide-sublevels arg)
4942 (setq org-cycle-global-status 'contents))
4943 ((equal arg '(4))
4944 (org-set-startup-visibility)
4945 (message "Startup visibility, plus VISIBILITY properties."))
4947 (org-cycle '(4))))))
4949 (defun org-set-startup-visibility ()
4950 "Set the visibility required by startup options and properties."
4951 (cond
4952 ((eq org-startup-folded t)
4953 (org-cycle '(4)))
4954 ((eq org-startup-folded 'content)
4955 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4956 (org-cycle '(4)) (org-cycle '(4)))))
4957 (if org-hide-block-startup (org-hide-block-all))
4958 (org-set-visibility-according-to-property 'no-cleanup)
4959 (org-cycle-hide-archived-subtrees 'all)
4960 (org-cycle-hide-drawers 'all)
4961 (org-cycle-show-empty-lines 'all))
4963 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4964 "Switch subtree visibilities according to :VISIBILITY: property."
4965 (interactive)
4966 (let (org-show-entry-below state)
4967 (save-excursion
4968 (goto-char (point-min))
4969 (while (re-search-forward
4970 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4971 nil t)
4972 (setq state (match-string 1))
4973 (save-excursion
4974 (org-back-to-heading t)
4975 (hide-subtree)
4976 (org-reveal)
4977 (cond
4978 ((equal state '("fold" "folded"))
4979 (hide-subtree))
4980 ((equal state "children")
4981 (org-show-hidden-entry)
4982 (show-children))
4983 ((equal state "content")
4984 (save-excursion
4985 (save-restriction
4986 (org-narrow-to-subtree)
4987 (org-content))))
4988 ((member state '("all" "showall"))
4989 (show-subtree)))))
4990 (unless no-cleanup
4991 (org-cycle-hide-archived-subtrees 'all)
4992 (org-cycle-hide-drawers 'all)
4993 (org-cycle-show-empty-lines 'all)))))
4995 (defun org-overview ()
4996 "Switch to overview mode, showing only top-level headlines.
4997 Really, this shows all headlines with level equal or greater than the level
4998 of the first headline in the buffer. This is important, because if the
4999 first headline is not level one, then (hide-sublevels 1) gives confusing
5000 results."
5001 (interactive)
5002 (let ((level (save-excursion
5003 (goto-char (point-min))
5004 (if (re-search-forward (concat "^" outline-regexp) nil t)
5005 (progn
5006 (goto-char (match-beginning 0))
5007 (funcall outline-level))))))
5008 (and level (hide-sublevels level))))
5010 (defun org-content (&optional arg)
5011 "Show all headlines in the buffer, like a table of contents.
5012 With numerical argument N, show content up to level N."
5013 (interactive "P")
5014 (save-excursion
5015 ;; Visit all headings and show their offspring
5016 (and (integerp arg) (org-overview))
5017 (goto-char (point-max))
5018 (catch 'exit
5019 (while (and (progn (condition-case nil
5020 (outline-previous-visible-heading 1)
5021 (error (goto-char (point-min))))
5023 (looking-at outline-regexp))
5024 (if (integerp arg)
5025 (show-children (1- arg))
5026 (show-branches))
5027 (if (bobp) (throw 'exit nil))))))
5030 (defun org-optimize-window-after-visibility-change (state)
5031 "Adjust the window after a change in outline visibility.
5032 This function is the default value of the hook `org-cycle-hook'."
5033 (when (get-buffer-window (current-buffer))
5034 (cond
5035 ((eq state 'content) nil)
5036 ((eq state 'all) nil)
5037 ((eq state 'folded) nil)
5038 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5039 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5041 ;; FIXME: no longer in use
5042 (defun org-compact-display-after-subtree-move ()
5043 "Show a compacter version of the tree of the entry's parent."
5044 (save-excursion
5045 (if (org-up-heading-safe)
5046 (progn
5047 (hide-subtree)
5048 (show-entry)
5049 (show-children)
5050 (org-cycle-show-empty-lines 'children)
5051 (org-cycle-hide-drawers 'children))
5052 (org-overview))))
5054 (defun org-remove-empty-overlays-at (pos)
5055 "Remove outline overlays that do not contain non-white stuff."
5056 (mapc
5057 (lambda (o)
5058 (and (eq 'outline (org-overlay-get o 'invisible))
5059 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5060 (org-overlay-end o))))
5061 (org-delete-overlay o)))
5062 (org-overlays-at pos)))
5064 (defun org-clean-visibility-after-subtree-move ()
5065 "Fix visibility issues after moving a subtree."
5066 ;; First, find a reasonable region to look at:
5067 ;; Start two siblings above, end three below
5068 (let* ((beg (save-excursion
5069 (and (outline-get-last-sibling)
5070 (outline-get-last-sibling))
5071 (point)))
5072 (end (save-excursion
5073 (and (outline-get-next-sibling)
5074 (outline-get-next-sibling)
5075 (outline-get-next-sibling))
5076 (if (org-at-heading-p)
5077 (point-at-eol)
5078 (point))))
5079 (level (looking-at "\\*+"))
5080 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5081 (save-excursion
5082 (save-restriction
5083 (narrow-to-region beg end)
5084 (when re
5085 ;; Properly fold already folded siblings
5086 (goto-char (point-min))
5087 (while (re-search-forward re nil t)
5088 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5089 (hide-entry))))
5090 (org-cycle-show-empty-lines 'overview)
5091 (org-cycle-hide-drawers 'overview)))))
5093 (defun org-cycle-show-empty-lines (state)
5094 "Show empty lines above all visible headlines.
5095 The region to be covered depends on STATE when called through
5096 `org-cycle-hook'. Lisp program can use t for STATE to get the
5097 entire buffer covered. Note that an empty line is only shown if there
5098 are at least `org-cycle-separator-lines' empty lines before the headline."
5099 (when (> org-cycle-separator-lines 0)
5100 (save-excursion
5101 (let* ((n org-cycle-separator-lines)
5102 (re (cond
5103 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5104 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5105 (t (let ((ns (number-to-string (- n 2))))
5106 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5107 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5108 beg end)
5109 (cond
5110 ((memq state '(overview contents t))
5111 (setq beg (point-min) end (point-max)))
5112 ((memq state '(children folded))
5113 (setq beg (point) end (progn (org-end-of-subtree t t)
5114 (beginning-of-line 2)
5115 (point)))))
5116 (when beg
5117 (goto-char beg)
5118 (while (re-search-forward re end t)
5119 (if (not (get-char-property (match-end 1) 'invisible))
5120 (outline-flag-region
5121 (match-beginning 1) (match-end 1) nil)))))))
5122 ;; Never hide empty lines at the end of the file.
5123 (save-excursion
5124 (goto-char (point-max))
5125 (outline-previous-heading)
5126 (outline-end-of-heading)
5127 (if (and (looking-at "[ \t\n]+")
5128 (= (match-end 0) (point-max)))
5129 (outline-flag-region (point) (match-end 0) nil))))
5131 (defun org-show-empty-lines-in-parent ()
5132 "Move to the parent and re-show empty lines before visible headlines."
5133 (save-excursion
5134 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5135 (org-cycle-show-empty-lines context))))
5137 (defun org-cycle-hide-drawers (state)
5138 "Re-hide all drawers after a visibility state change."
5139 (when (and (org-mode-p)
5140 (not (memq state '(overview folded))))
5141 (save-excursion
5142 (let* ((globalp (memq state '(contents all)))
5143 (beg (if globalp (point-min) (point)))
5144 (end (if globalp (point-max) (org-end-of-subtree t))))
5145 (goto-char beg)
5146 (while (re-search-forward org-drawer-regexp end t)
5147 (org-flag-drawer t))))))
5149 (defun org-flag-drawer (flag)
5150 (save-excursion
5151 (beginning-of-line 1)
5152 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5153 (let ((b (match-end 0))
5154 (outline-regexp org-outline-regexp))
5155 (if (re-search-forward
5156 "^[ \t]*:END:"
5157 (save-excursion (outline-next-heading) (point)) t)
5158 (outline-flag-region b (point-at-eol) flag)
5159 (error ":END: line missing"))))))
5161 (defun org-subtree-end-visible-p ()
5162 "Is the end of the current subtree visible?"
5163 (pos-visible-in-window-p
5164 (save-excursion (org-end-of-subtree t) (point))))
5166 (defun org-first-headline-recenter (&optional N)
5167 "Move cursor to the first headline and recenter the headline.
5168 Optional argument N means, put the headline into the Nth line of the window."
5169 (goto-char (point-min))
5170 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5171 (beginning-of-line)
5172 (recenter (prefix-numeric-value N))))
5174 ;;; Folding of blocks
5176 (defconst org-block-regexp
5178 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5179 "Regular expression for hiding blocks.")
5181 (defvar org-hide-block-overlays nil
5182 "Overays hiding blocks.")
5183 (make-variable-buffer-local 'org-hide-block-overlays)
5185 (defun org-block-map (function &optional start end)
5186 "Call func at the head of all source blocks in the current
5187 buffer. Optional arguments START and END can be used to limit
5188 the range."
5189 (let ((start (or start (point-min)))
5190 (end (or end (point-max))))
5191 (save-excursion
5192 (goto-char start)
5193 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5194 (save-excursion
5195 (save-match-data
5196 (goto-char (match-beginning 0))
5197 (funcall function)))))))
5199 (defun org-hide-block-toggle-all ()
5200 "Toggle the visibility of all blocks in the current buffer."
5201 (org-block-map #'org-hide-block-toggle))
5203 (defun org-hide-block-all ()
5204 "Fold all blocks in the current buffer."
5205 (interactive)
5206 (org-show-block-all)
5207 (org-block-map #'org-hide-block-toggle-maybe))
5209 (defun org-show-block-all ()
5210 "Unfold all blocks in the current buffer."
5211 (mapc 'org-delete-overlay org-hide-block-overlays)
5212 (setq org-hide-block-overlays nil))
5214 (defun org-hide-block-toggle-maybe ()
5215 "Toggle visibility of block at point."
5216 (interactive)
5217 (let ((case-fold-search t))
5218 (if (save-excursion
5219 (beginning-of-line 1)
5220 (looking-at org-block-regexp))
5221 (progn (org-hide-block-toggle)
5222 t) ;; to signal that we took action
5223 nil))) ;; to signal that we did not
5225 (defun org-hide-block-toggle (&optional force)
5226 "Toggle the visibility of the current block."
5227 (interactive)
5228 (save-excursion
5229 (beginning-of-line)
5230 (if (re-search-forward org-block-regexp nil t)
5231 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5232 (end (match-end 0))
5233 ov) ;; end of entire body
5234 (if (memq t (mapcar (lambda (overlay)
5235 (eq (org-overlay-get overlay 'invisible)
5236 'org-hide-block))
5237 (org-overlays-at start)))
5238 (if (or (not force) (eq force 'off))
5239 (mapc (lambda (ov)
5240 (when (member ov org-hide-block-overlays)
5241 (setq org-hide-block-overlays
5242 (delq ov org-hide-block-overlays)))
5243 (when (eq (org-overlay-get ov 'invisible)
5244 'org-hide-block)
5245 (org-delete-overlay ov)))
5246 (org-overlays-at start)))
5247 (setq ov (org-make-overlay start end))
5248 (org-overlay-put ov 'invisible 'org-hide-block)
5249 (push ov org-hide-block-overlays)))
5250 (error "Not looking at a source block"))))
5252 ;; org-tab-after-check-for-cycling-hook
5253 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5254 ;; Remove overlays when changing major mode
5255 (add-hook 'org-mode-hook
5256 (lambda () (org-add-hook 'change-major-mode-hook
5257 'org-show-block-all 'append 'local)))
5259 ;;; Org-goto
5261 (defvar org-goto-window-configuration nil)
5262 (defvar org-goto-marker nil)
5263 (defvar org-goto-map
5264 (let ((map (make-sparse-keymap)))
5265 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5266 (while (setq cmd (pop cmds))
5267 (substitute-key-definition cmd cmd map global-map)))
5268 (suppress-keymap map)
5269 (org-defkey map "\C-m" 'org-goto-ret)
5270 (org-defkey map [(return)] 'org-goto-ret)
5271 (org-defkey map [(left)] 'org-goto-left)
5272 (org-defkey map [(right)] 'org-goto-right)
5273 (org-defkey map [(control ?g)] 'org-goto-quit)
5274 (org-defkey map "\C-i" 'org-cycle)
5275 (org-defkey map [(tab)] 'org-cycle)
5276 (org-defkey map [(down)] 'outline-next-visible-heading)
5277 (org-defkey map [(up)] 'outline-previous-visible-heading)
5278 (if org-goto-auto-isearch
5279 (if (fboundp 'define-key-after)
5280 (define-key-after map [t] 'org-goto-local-auto-isearch)
5281 nil)
5282 (org-defkey map "q" 'org-goto-quit)
5283 (org-defkey map "n" 'outline-next-visible-heading)
5284 (org-defkey map "p" 'outline-previous-visible-heading)
5285 (org-defkey map "f" 'outline-forward-same-level)
5286 (org-defkey map "b" 'outline-backward-same-level)
5287 (org-defkey map "u" 'outline-up-heading))
5288 (org-defkey map "/" 'org-occur)
5289 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5290 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5291 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5292 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5293 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5294 map))
5296 (defconst org-goto-help
5297 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5298 RET=jump to location [Q]uit and return to previous location
5299 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5301 (defvar org-goto-start-pos) ; dynamically scoped parameter
5303 ;; FIXME: Docstring doe not mention both interfaces
5304 (defun org-goto (&optional alternative-interface)
5305 "Look up a different location in the current file, keeping current visibility.
5307 When you want look-up or go to a different location in a document, the
5308 fastest way is often to fold the entire buffer and then dive into the tree.
5309 This method has the disadvantage, that the previous location will be folded,
5310 which may not be what you want.
5312 This command works around this by showing a copy of the current buffer
5313 in an indirect buffer, in overview mode. You can dive into the tree in
5314 that copy, use org-occur and incremental search to find a location.
5315 When pressing RET or `Q', the command returns to the original buffer in
5316 which the visibility is still unchanged. After RET is will also jump to
5317 the location selected in the indirect buffer and expose the
5318 the headline hierarchy above."
5319 (interactive "P")
5320 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5321 (org-refile-use-outline-path t)
5322 (org-refile-target-verify-function nil)
5323 (interface
5324 (if (not alternative-interface)
5325 org-goto-interface
5326 (if (eq org-goto-interface 'outline)
5327 'outline-path-completion
5328 'outline)))
5329 (org-goto-start-pos (point))
5330 (selected-point
5331 (if (eq interface 'outline)
5332 (car (org-get-location (current-buffer) org-goto-help))
5333 (nth 3 (org-refile-get-location "Goto: ")))))
5334 (if selected-point
5335 (progn
5336 (org-mark-ring-push org-goto-start-pos)
5337 (goto-char selected-point)
5338 (if (or (org-invisible-p) (org-invisible-p2))
5339 (org-show-context 'org-goto)))
5340 (message "Quit"))))
5342 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5343 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5344 (defvar org-goto-local-auto-isearch-map) ; defined below
5346 (defun org-get-location (buf help)
5347 "Let the user select a location in the Org-mode buffer BUF.
5348 This function uses a recursive edit. It returns the selected position
5349 or nil."
5350 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5351 (isearch-hide-immediately nil)
5352 (isearch-search-fun-function
5353 (lambda () 'org-goto-local-search-headings))
5354 (org-goto-selected-point org-goto-exit-command))
5355 (save-excursion
5356 (save-window-excursion
5357 (delete-other-windows)
5358 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5359 (switch-to-buffer
5360 (condition-case nil
5361 (make-indirect-buffer (current-buffer) "*org-goto*")
5362 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5363 (with-output-to-temp-buffer "*Help*"
5364 (princ help))
5365 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5366 (setq buffer-read-only nil)
5367 (let ((org-startup-truncated t)
5368 (org-startup-folded nil)
5369 (org-startup-align-all-tables nil))
5370 (org-mode)
5371 (org-overview))
5372 (setq buffer-read-only t)
5373 (if (and (boundp 'org-goto-start-pos)
5374 (integer-or-marker-p org-goto-start-pos))
5375 (let ((org-show-hierarchy-above t)
5376 (org-show-siblings t)
5377 (org-show-following-heading t))
5378 (goto-char org-goto-start-pos)
5379 (and (org-invisible-p) (org-show-context)))
5380 (goto-char (point-min)))
5381 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5382 (message "Select location and press RET")
5383 (use-local-map org-goto-map)
5384 (recursive-edit)
5386 (kill-buffer "*org-goto*")
5387 (cons org-goto-selected-point org-goto-exit-command)))
5389 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5390 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5391 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5392 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5394 (defun org-goto-local-search-headings (string bound noerror)
5395 "Search and make sure that any matches are in headlines."
5396 (catch 'return
5397 (while (if isearch-forward
5398 (search-forward string bound noerror)
5399 (search-backward string bound noerror))
5400 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5401 (and (member :headline context)
5402 (not (member :tags context))))
5403 (throw 'return (point))))))
5405 (defun org-goto-local-auto-isearch ()
5406 "Start isearch."
5407 (interactive)
5408 (goto-char (point-min))
5409 (let ((keys (this-command-keys)))
5410 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5411 (isearch-mode t)
5412 (isearch-process-search-char (string-to-char keys)))))
5414 (defun org-goto-ret (&optional arg)
5415 "Finish `org-goto' by going to the new location."
5416 (interactive "P")
5417 (setq org-goto-selected-point (point)
5418 org-goto-exit-command 'return)
5419 (throw 'exit nil))
5421 (defun org-goto-left ()
5422 "Finish `org-goto' by going to the new location."
5423 (interactive)
5424 (if (org-on-heading-p)
5425 (progn
5426 (beginning-of-line 1)
5427 (setq org-goto-selected-point (point)
5428 org-goto-exit-command 'left)
5429 (throw 'exit nil))
5430 (error "Not on a heading")))
5432 (defun org-goto-right ()
5433 "Finish `org-goto' by going to the new location."
5434 (interactive)
5435 (if (org-on-heading-p)
5436 (progn
5437 (setq org-goto-selected-point (point)
5438 org-goto-exit-command 'right)
5439 (throw 'exit nil))
5440 (error "Not on a heading")))
5442 (defun org-goto-quit ()
5443 "Finish `org-goto' without cursor motion."
5444 (interactive)
5445 (setq org-goto-selected-point nil)
5446 (setq org-goto-exit-command 'quit)
5447 (throw 'exit nil))
5449 ;;; Indirect buffer display of subtrees
5451 (defvar org-indirect-dedicated-frame nil
5452 "This is the frame being used for indirect tree display.")
5453 (defvar org-last-indirect-buffer nil)
5455 (defun org-tree-to-indirect-buffer (&optional arg)
5456 "Create indirect buffer and narrow it to current subtree.
5457 With numerical prefix ARG, go up to this level and then take that tree.
5458 If ARG is negative, go up that many levels.
5459 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5460 indirect buffer previously made with this command, to avoid proliferation of
5461 indirect buffers. However, when you call the command with a `C-u' prefix, or
5462 when `org-indirect-buffer-display' is `new-frame', the last buffer
5463 is kept so that you can work with several indirect buffers at the same time.
5464 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5465 requests that a new frame be made for the new buffer, so that the dedicated
5466 frame is not changed."
5467 (interactive "P")
5468 (let ((cbuf (current-buffer))
5469 (cwin (selected-window))
5470 (pos (point))
5471 beg end level heading ibuf)
5472 (save-excursion
5473 (org-back-to-heading t)
5474 (when (numberp arg)
5475 (setq level (org-outline-level))
5476 (if (< arg 0) (setq arg (+ level arg)))
5477 (while (> (setq level (org-outline-level)) arg)
5478 (outline-up-heading 1 t)))
5479 (setq beg (point)
5480 heading (org-get-heading))
5481 (org-end-of-subtree t) (setq end (point)))
5482 (if (and (buffer-live-p org-last-indirect-buffer)
5483 (not (eq org-indirect-buffer-display 'new-frame))
5484 (not arg))
5485 (kill-buffer org-last-indirect-buffer))
5486 (setq ibuf (org-get-indirect-buffer cbuf)
5487 org-last-indirect-buffer ibuf)
5488 (cond
5489 ((or (eq org-indirect-buffer-display 'new-frame)
5490 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5491 (select-frame (make-frame))
5492 (delete-other-windows)
5493 (switch-to-buffer ibuf)
5494 (org-set-frame-title heading))
5495 ((eq org-indirect-buffer-display 'dedicated-frame)
5496 (raise-frame
5497 (select-frame (or (and org-indirect-dedicated-frame
5498 (frame-live-p org-indirect-dedicated-frame)
5499 org-indirect-dedicated-frame)
5500 (setq org-indirect-dedicated-frame (make-frame)))))
5501 (delete-other-windows)
5502 (switch-to-buffer ibuf)
5503 (org-set-frame-title (concat "Indirect: " heading)))
5504 ((eq org-indirect-buffer-display 'current-window)
5505 (switch-to-buffer ibuf))
5506 ((eq org-indirect-buffer-display 'other-window)
5507 (pop-to-buffer ibuf))
5508 (t (error "Invalid value.")))
5509 (if (featurep 'xemacs)
5510 (save-excursion (org-mode) (turn-on-font-lock)))
5511 (narrow-to-region beg end)
5512 (show-all)
5513 (goto-char pos)
5514 (and (window-live-p cwin) (select-window cwin))))
5516 (defun org-get-indirect-buffer (&optional buffer)
5517 (setq buffer (or buffer (current-buffer)))
5518 (let ((n 1) (base (buffer-name buffer)) bname)
5519 (while (buffer-live-p
5520 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5521 (setq n (1+ n)))
5522 (condition-case nil
5523 (make-indirect-buffer buffer bname 'clone)
5524 (error (make-indirect-buffer buffer bname)))))
5526 (defun org-set-frame-title (title)
5527 "Set the title of the current frame to the string TITLE."
5528 ;; FIXME: how to name a single frame in XEmacs???
5529 (unless (featurep 'xemacs)
5530 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5532 ;;;; Structure editing
5534 ;;; Inserting headlines
5536 (defun org-previous-line-empty-p ()
5537 (save-excursion
5538 (and (not (bobp))
5539 (or (beginning-of-line 0) t)
5540 (save-match-data
5541 (looking-at "[ \t]*$")))))
5543 (defun org-insert-heading (&optional force-heading)
5544 "Insert a new heading or item with same depth at point.
5545 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5546 If point is at the beginning of a headline, insert a sibling before the
5547 current headline. If point is not at the beginning, do not split the line,
5548 but create the new headline after the current line."
5549 (interactive "P")
5550 (if (= (buffer-size) 0)
5551 (insert "\n* ")
5552 (when (or force-heading (not (org-insert-item)))
5553 (let* ((empty-line-p nil)
5554 (head (save-excursion
5555 (condition-case nil
5556 (progn
5557 (org-back-to-heading)
5558 (setq empty-line-p (org-previous-line-empty-p))
5559 (match-string 0))
5560 (error "*"))))
5561 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5562 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5563 pos hide-previous previous-pos)
5564 (cond
5565 ((and (org-on-heading-p) (bolp)
5566 (or (bobp)
5567 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5568 ;; insert before the current line
5569 (open-line (if blank 2 1)))
5570 ((and (bolp)
5571 (or (bobp)
5572 (save-excursion
5573 (backward-char 1) (not (org-invisible-p)))))
5574 ;; insert right here
5575 nil)
5577 ;; somewhere in the line
5578 (save-excursion
5579 (setq previous-pos (point-at-bol))
5580 (end-of-line)
5581 (setq hide-previous (org-invisible-p)))
5582 (and org-insert-heading-respect-content (org-show-subtree))
5583 (let ((split
5584 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5585 (save-excursion
5586 (let ((p (point)))
5587 (goto-char (point-at-bol))
5588 (and (looking-at org-complex-heading-regexp)
5589 (> p (match-beginning 4)))))))
5590 tags pos)
5591 (cond
5592 (org-insert-heading-respect-content
5593 (org-end-of-subtree nil t)
5594 (or (bolp) (newline))
5595 (or (org-previous-line-empty-p)
5596 (and blank (newline)))
5597 (open-line 1))
5598 ((org-on-heading-p)
5599 (when hide-previous
5600 (show-children)
5601 (org-show-entry))
5602 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5603 (setq tags (and (match-end 2) (match-string 2)))
5604 (and (match-end 1)
5605 (delete-region (match-beginning 1) (match-end 1)))
5606 (setq pos (point-at-bol))
5607 (or split (end-of-line 1))
5608 (delete-horizontal-space)
5609 (newline (if blank 2 1))
5610 (when tags
5611 (save-excursion
5612 (goto-char pos)
5613 (end-of-line 1)
5614 (insert " " tags)
5615 (org-set-tags nil 'align))))
5617 (or split (end-of-line 1))
5618 (newline (if blank 2 1)))))))
5619 (insert head) (just-one-space)
5620 (setq pos (point))
5621 (end-of-line 1)
5622 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5623 (when (and org-insert-heading-respect-content hide-previous)
5624 (save-excursion
5625 (goto-char previous-pos)
5626 (hide-subtree)))
5627 (run-hooks 'org-insert-heading-hook)))))
5629 (defun org-get-heading (&optional no-tags)
5630 "Return the heading of the current entry, without the stars."
5631 (save-excursion
5632 (org-back-to-heading t)
5633 (if (looking-at
5634 (if no-tags
5635 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5636 "\\*+[ \t]+\\([^\r\n]*\\)"))
5637 (match-string 1) "")))
5639 (defun org-heading-components ()
5640 "Return the components of the current heading.
5641 This is a list with the following elements:
5642 - the level as an integer
5643 - the reduced level, different if `org-odd-levels-only' is set.
5644 - the TODO keyword, or nil
5645 - the priority character, like ?A, or nil if no priority is given
5646 - the headline text itself, or the tags string if no headline text
5647 - the tags string, or nil."
5648 (save-excursion
5649 (org-back-to-heading t)
5650 (if (looking-at org-complex-heading-regexp)
5651 (list (length (match-string 1))
5652 (org-reduced-level (length (match-string 1)))
5653 (org-match-string-no-properties 2)
5654 (and (match-end 3) (aref (match-string 3) 2))
5655 (org-match-string-no-properties 4)
5656 (org-match-string-no-properties 5)))))
5658 (defun org-get-entry ()
5659 "Get the entry text, after heading, entire subtree."
5660 (save-excursion
5661 (org-back-to-heading t)
5662 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5664 (defun org-insert-heading-after-current ()
5665 "Insert a new heading with same level as current, after current subtree."
5666 (interactive)
5667 (org-back-to-heading)
5668 (org-insert-heading)
5669 (org-move-subtree-down)
5670 (end-of-line 1))
5672 (defun org-insert-heading-respect-content ()
5673 (interactive)
5674 (let ((org-insert-heading-respect-content t))
5675 (org-insert-heading t)))
5677 (defun org-insert-todo-heading-respect-content (&optional force-state)
5678 (interactive "P")
5679 (let ((org-insert-heading-respect-content t))
5680 (org-insert-todo-heading force-state t)))
5682 (defun org-insert-todo-heading (arg &optional force-heading)
5683 "Insert a new heading with the same level and TODO state as current heading.
5684 If the heading has no TODO state, or if the state is DONE, use the first
5685 state (TODO by default). Also with prefix arg, force first state."
5686 (interactive "P")
5687 (when (or force-heading (not (org-insert-item 'checkbox)))
5688 (org-insert-heading force-heading)
5689 (save-excursion
5690 (org-back-to-heading)
5691 (outline-previous-heading)
5692 (looking-at org-todo-line-regexp))
5693 (let*
5694 ((new-mark-x
5695 (if (or arg
5696 (not (match-beginning 2))
5697 (member (match-string 2) org-done-keywords))
5698 (car org-todo-keywords-1)
5699 (match-string 2)))
5700 (new-mark
5702 (run-hook-with-args-until-success
5703 'org-todo-get-default-hook new-mark-x nil)
5704 new-mark-x)))
5705 (beginning-of-line 1)
5706 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5707 (if org-treat-insert-todo-heading-as-state-change
5708 (org-todo new-mark)
5709 (insert new-mark " "))))
5710 (when org-provide-todo-statistics
5711 (org-update-parent-todo-statistics))))
5713 (defun org-insert-subheading (arg)
5714 "Insert a new subheading and demote it.
5715 Works for outline headings and for plain lists alike."
5716 (interactive "P")
5717 (org-insert-heading arg)
5718 (cond
5719 ((org-on-heading-p) (org-do-demote))
5720 ((org-at-item-p) (org-indent-item 1))))
5722 (defun org-insert-todo-subheading (arg)
5723 "Insert a new subheading with TODO keyword or checkbox and demote it.
5724 Works for outline headings and for plain lists alike."
5725 (interactive "P")
5726 (org-insert-todo-heading arg)
5727 (cond
5728 ((org-on-heading-p) (org-do-demote))
5729 ((org-at-item-p) (org-indent-item 1))))
5731 ;;; Promotion and Demotion
5733 (defun org-promote-subtree ()
5734 "Promote the entire subtree.
5735 See also `org-promote'."
5736 (interactive)
5737 (save-excursion
5738 (org-map-tree 'org-promote))
5739 (org-fix-position-after-promote))
5741 (defun org-demote-subtree ()
5742 "Demote the entire subtree. See `org-demote'.
5743 See also `org-promote'."
5744 (interactive)
5745 (save-excursion
5746 (org-map-tree 'org-demote))
5747 (org-fix-position-after-promote))
5750 (defun org-do-promote ()
5751 "Promote the current heading higher up the tree.
5752 If the region is active in `transient-mark-mode', promote all headings
5753 in the region."
5754 (interactive)
5755 (save-excursion
5756 (if (org-region-active-p)
5757 (org-map-region 'org-promote (region-beginning) (region-end))
5758 (org-promote)))
5759 (org-fix-position-after-promote))
5761 (defun org-do-demote ()
5762 "Demote the current heading lower down the tree.
5763 If the region is active in `transient-mark-mode', demote all headings
5764 in the region."
5765 (interactive)
5766 (save-excursion
5767 (if (org-region-active-p)
5768 (org-map-region 'org-demote (region-beginning) (region-end))
5769 (org-demote)))
5770 (org-fix-position-after-promote))
5772 (defun org-fix-position-after-promote ()
5773 "Make sure that after pro/demotion cursor position is right."
5774 (let ((pos (point)))
5775 (when (save-excursion
5776 (beginning-of-line 1)
5777 (looking-at org-todo-line-regexp)
5778 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5779 (cond ((eobp) (insert " "))
5780 ((eolp) (insert " "))
5781 ((equal (char-after) ?\ ) (forward-char 1))))))
5783 (defun org-reduced-level (l)
5784 "Compute the effective level of a heading.
5785 This takes into account the setting of `org-odd-levels-only'."
5786 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5788 (defun org-get-valid-level (level &optional change)
5789 "Rectify a level change under the influence of `org-odd-levels-only'
5790 LEVEL is a current level, CHANGE is by how much the level should be
5791 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5792 even level numbers will become the next higher odd number."
5793 (if org-odd-levels-only
5794 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5795 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5796 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5797 (max 1 (+ level (or change 0)))))
5799 (if (boundp 'define-obsolete-function-alias)
5800 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5801 (define-obsolete-function-alias 'org-get-legal-level
5802 'org-get-valid-level)
5803 (define-obsolete-function-alias 'org-get-legal-level
5804 'org-get-valid-level "23.1")))
5806 (defun org-promote ()
5807 "Promote the current heading higher up the tree.
5808 If the region is active in `transient-mark-mode', promote all headings
5809 in the region."
5810 (org-back-to-heading t)
5811 (let* ((level (save-match-data (funcall outline-level)))
5812 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5813 (diff (abs (- level (length up-head) -1))))
5814 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5815 (replace-match up-head nil t)
5816 ;; Fixup tag positioning
5817 (and org-auto-align-tags (org-set-tags nil t))
5818 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5820 (defun org-demote ()
5821 "Demote the current heading lower down the tree.
5822 If the region is active in `transient-mark-mode', demote all headings
5823 in the region."
5824 (org-back-to-heading t)
5825 (let* ((level (save-match-data (funcall outline-level)))
5826 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5827 (diff (abs (- level (length down-head) -1))))
5828 (replace-match down-head nil t)
5829 ;; Fixup tag positioning
5830 (and org-auto-align-tags (org-set-tags nil t))
5831 (if org-adapt-indentation (org-fixup-indentation diff))))
5833 (defun org-map-tree (fun)
5834 "Call FUN for every heading underneath the current one."
5835 (org-back-to-heading)
5836 (let ((level (funcall outline-level)))
5837 (save-excursion
5838 (funcall fun)
5839 (while (and (progn
5840 (outline-next-heading)
5841 (> (funcall outline-level) level))
5842 (not (eobp)))
5843 (funcall fun)))))
5845 (defun org-map-region (fun beg end)
5846 "Call FUN for every heading between BEG and END."
5847 (let ((org-ignore-region t))
5848 (save-excursion
5849 (setq end (copy-marker end))
5850 (goto-char beg)
5851 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5852 (< (point) end))
5853 (funcall fun))
5854 (while (and (progn
5855 (outline-next-heading)
5856 (< (point) end))
5857 (not (eobp)))
5858 (funcall fun)))))
5860 (defun org-fixup-indentation (diff)
5861 "Change the indentation in the current entry by DIFF
5862 However, if any line in the current entry has no indentation, or if it
5863 would end up with no indentation after the change, nothing at all is done."
5864 (save-excursion
5865 (let ((end (save-excursion (outline-next-heading)
5866 (point-marker)))
5867 (prohibit (if (> diff 0)
5868 "^\\S-"
5869 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5870 col)
5871 (unless (save-excursion (end-of-line 1)
5872 (re-search-forward prohibit end t))
5873 (while (and (< (point) end)
5874 (re-search-forward "^[ \t]+" end t))
5875 (goto-char (match-end 0))
5876 (setq col (current-column))
5877 (if (< diff 0) (replace-match ""))
5878 (org-indent-to-column (+ diff col))))
5879 (move-marker end nil))))
5881 (defun org-convert-to-odd-levels ()
5882 "Convert an org-mode file with all levels allowed to one with odd levels.
5883 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5884 level 5 etc."
5885 (interactive)
5886 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5887 (let ((org-odd-levels-only nil) n)
5888 (save-excursion
5889 (goto-char (point-min))
5890 (while (re-search-forward "^\\*\\*+ " nil t)
5891 (setq n (- (length (match-string 0)) 2))
5892 (while (>= (setq n (1- n)) 0)
5893 (org-demote))
5894 (end-of-line 1))))))
5897 (defun org-convert-to-oddeven-levels ()
5898 "Convert an org-mode file with only odd levels to one with odd and even levels.
5899 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5900 section with an even level, conversion would destroy the structure of the file. An error
5901 is signaled in this case."
5902 (interactive)
5903 (goto-char (point-min))
5904 ;; First check if there are no even levels
5905 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5906 (org-show-context t)
5907 (error "Not all levels are odd in this file. Conversion not possible."))
5908 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5909 (let ((org-odd-levels-only nil) n)
5910 (save-excursion
5911 (goto-char (point-min))
5912 (while (re-search-forward "^\\*\\*+ " nil t)
5913 (setq n (/ (1- (length (match-string 0))) 2))
5914 (while (>= (setq n (1- n)) 0)
5915 (org-promote))
5916 (end-of-line 1))))))
5918 (defun org-tr-level (n)
5919 "Make N odd if required."
5920 (if org-odd-levels-only (1+ (/ n 2)) n))
5922 ;;; Vertical tree motion, cutting and pasting of subtrees
5924 (defun org-move-subtree-up (&optional arg)
5925 "Move the current subtree up past ARG headlines of the same level."
5926 (interactive "p")
5927 (org-move-subtree-down (- (prefix-numeric-value arg))))
5929 (defun org-move-subtree-down (&optional arg)
5930 "Move the current subtree down past ARG headlines of the same level."
5931 (interactive "p")
5932 (setq arg (prefix-numeric-value arg))
5933 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5934 'outline-get-last-sibling))
5935 (ins-point (make-marker))
5936 (cnt (abs arg))
5937 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5938 ;; Select the tree
5939 (org-back-to-heading)
5940 (setq beg0 (point))
5941 (save-excursion
5942 (setq ne-beg (org-back-over-empty-lines))
5943 (setq beg (point)))
5944 (save-match-data
5945 (save-excursion (outline-end-of-heading)
5946 (setq folded (org-invisible-p)))
5947 (outline-end-of-subtree))
5948 (outline-next-heading)
5949 (setq ne-end (org-back-over-empty-lines))
5950 (setq end (point))
5951 (goto-char beg0)
5952 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5953 ;; include less whitespace
5954 (save-excursion
5955 (goto-char beg)
5956 (forward-line (- ne-beg ne-end))
5957 (setq beg (point))))
5958 ;; Find insertion point, with error handling
5959 (while (> cnt 0)
5960 (or (and (funcall movfunc) (looking-at outline-regexp))
5961 (progn (goto-char beg0)
5962 (error "Cannot move past superior level or buffer limit")))
5963 (setq cnt (1- cnt)))
5964 (if (> arg 0)
5965 ;; Moving forward - still need to move over subtree
5966 (progn (org-end-of-subtree t t)
5967 (save-excursion
5968 (org-back-over-empty-lines)
5969 (or (bolp) (newline)))))
5970 (setq ne-ins (org-back-over-empty-lines))
5971 (move-marker ins-point (point))
5972 (setq txt (buffer-substring beg end))
5973 (org-save-markers-in-region beg end)
5974 (delete-region beg end)
5975 (org-remove-empty-overlays-at beg)
5976 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5977 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5978 (and (not (bolp)) (looking-at "\n") (forward-char 1))
5979 (let ((bbb (point)))
5980 (insert-before-markers txt)
5981 (org-reinstall-markers-in-region bbb)
5982 (move-marker ins-point bbb))
5983 (or (bolp) (insert "\n"))
5984 (setq ins-end (point))
5985 (goto-char ins-point)
5986 (org-skip-whitespace)
5987 (when (and (< arg 0)
5988 (org-first-sibling-p)
5989 (> ne-ins ne-beg))
5990 ;; Move whitespace back to beginning
5991 (save-excursion
5992 (goto-char ins-end)
5993 (let ((kill-whole-line t))
5994 (kill-line (- ne-ins ne-beg)) (point)))
5995 (insert (make-string (- ne-ins ne-beg) ?\n)))
5996 (move-marker ins-point nil)
5997 (if folded
5998 (hide-entry)
5999 (org-show-entry)
6000 (show-children)
6001 (org-cycle-hide-drawers 'children))
6002 (org-clean-visibility-after-subtree-move)))
6004 (defvar org-subtree-clip ""
6005 "Clipboard for cut and paste of subtrees.
6006 This is actually only a copy of the kill, because we use the normal kill
6007 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6009 (defvar org-subtree-clip-folded nil
6010 "Was the last copied subtree folded?
6011 This is used to fold the tree back after pasting.")
6013 (defun org-cut-subtree (&optional n)
6014 "Cut the current subtree into the clipboard.
6015 With prefix arg N, cut this many sequential subtrees.
6016 This is a short-hand for marking the subtree and then cutting it."
6017 (interactive "p")
6018 (org-copy-subtree n 'cut))
6020 (defun org-copy-subtree (&optional n cut force-store-markers)
6021 "Cut the current subtree into the clipboard.
6022 With prefix arg N, cut this many sequential subtrees.
6023 This is a short-hand for marking the subtree and then copying it.
6024 If CUT is non-nil, actually cut the subtree.
6025 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6026 of some markers in the region, even if CUT is non-nil. This is
6027 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6028 (interactive "p")
6029 (let (beg end folded (beg0 (point)))
6030 (if (interactive-p)
6031 (org-back-to-heading nil) ; take what looks like a subtree
6032 (org-back-to-heading t)) ; take what is really there
6033 (org-back-over-empty-lines)
6034 (setq beg (point))
6035 (skip-chars-forward " \t\r\n")
6036 (save-match-data
6037 (save-excursion (outline-end-of-heading)
6038 (setq folded (org-invisible-p)))
6039 (condition-case nil
6040 (outline-forward-same-level (1- n))
6041 (error nil))
6042 (org-end-of-subtree t t))
6043 (org-back-over-empty-lines)
6044 (setq end (point))
6045 (goto-char beg0)
6046 (when (> end beg)
6047 (setq org-subtree-clip-folded folded)
6048 (when (or cut force-store-markers)
6049 (org-save-markers-in-region beg end))
6050 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6051 (setq org-subtree-clip (current-kill 0))
6052 (message "%s: Subtree(s) with %d characters"
6053 (if cut "Cut" "Copied")
6054 (length org-subtree-clip)))))
6056 (defun org-paste-subtree (&optional level tree for-yank)
6057 "Paste the clipboard as a subtree, with modification of headline level.
6058 The entire subtree is promoted or demoted in order to match a new headline
6059 level.
6061 If the cursor is at the beginning of a headline, the same level as
6062 that headline is used to paste the tree
6064 If not, the new level is derived from the *visible* headings
6065 before and after the insertion point, and taken to be the inferior headline
6066 level of the two. So if the previous visible heading is level 3 and the
6067 next is level 4 (or vice versa), level 4 will be used for insertion.
6068 This makes sure that the subtree remains an independent subtree and does
6069 not swallow low level entries.
6071 You can also force a different level, either by using a numeric prefix
6072 argument, or by inserting the heading marker by hand. For example, if the
6073 cursor is after \"*****\", then the tree will be shifted to level 5.
6075 If optional TREE is given, use this text instead of the kill ring.
6077 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6078 move back over whitespace before inserting, and move point to the end of
6079 the inserted text when done."
6080 (interactive "P")
6081 (unless (org-kill-is-subtree-p tree)
6082 (error "%s"
6083 (substitute-command-keys
6084 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6085 (let* ((visp (not (org-invisible-p)))
6086 (txt (or tree (and kill-ring (current-kill 0))))
6087 (^re (concat "^\\(" outline-regexp "\\)"))
6088 (re (concat "\\(" outline-regexp "\\)"))
6089 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6091 (old-level (if (string-match ^re txt)
6092 (- (match-end 0) (match-beginning 0) 1)
6093 -1))
6094 (force-level (cond (level (prefix-numeric-value level))
6095 ((and (looking-at "[ \t]*$")
6096 (string-match
6097 ^re_ (buffer-substring
6098 (point-at-bol) (point))))
6099 (- (match-end 1) (match-beginning 1)))
6100 ((and (bolp)
6101 (looking-at org-outline-regexp))
6102 (- (match-end 0) (point) 1))
6103 (t nil)))
6104 (previous-level (save-excursion
6105 (condition-case nil
6106 (progn
6107 (outline-previous-visible-heading 1)
6108 (if (looking-at re)
6109 (- (match-end 0) (match-beginning 0) 1)
6111 (error 1))))
6112 (next-level (save-excursion
6113 (condition-case nil
6114 (progn
6115 (or (looking-at outline-regexp)
6116 (outline-next-visible-heading 1))
6117 (if (looking-at re)
6118 (- (match-end 0) (match-beginning 0) 1)
6120 (error 1))))
6121 (new-level (or force-level (max previous-level next-level)))
6122 (shift (if (or (= old-level -1)
6123 (= new-level -1)
6124 (= old-level new-level))
6126 (- new-level old-level)))
6127 (delta (if (> shift 0) -1 1))
6128 (func (if (> shift 0) 'org-demote 'org-promote))
6129 (org-odd-levels-only nil)
6130 beg end newend)
6131 ;; Remove the forced level indicator
6132 (if force-level
6133 (delete-region (point-at-bol) (point)))
6134 ;; Paste
6135 (beginning-of-line 1)
6136 (unless for-yank (org-back-over-empty-lines))
6137 (setq beg (point))
6138 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6139 (insert-before-markers txt)
6140 (unless (string-match "\n\\'" txt) (insert "\n"))
6141 (setq newend (point))
6142 (org-reinstall-markers-in-region beg)
6143 (setq end (point))
6144 (goto-char beg)
6145 (skip-chars-forward " \t\n\r")
6146 (setq beg (point))
6147 (if (and (org-invisible-p) visp)
6148 (save-excursion (outline-show-heading)))
6149 ;; Shift if necessary
6150 (unless (= shift 0)
6151 (save-restriction
6152 (narrow-to-region beg end)
6153 (while (not (= shift 0))
6154 (org-map-region func (point-min) (point-max))
6155 (setq shift (+ delta shift)))
6156 (goto-char (point-min))
6157 (setq newend (point-max))))
6158 (when (or (interactive-p) for-yank)
6159 (message "Clipboard pasted as level %d subtree" new-level))
6160 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6161 kill-ring
6162 (eq org-subtree-clip (current-kill 0))
6163 org-subtree-clip-folded)
6164 ;; The tree was folded before it was killed/copied
6165 (hide-subtree))
6166 (and for-yank (goto-char newend))))
6168 (defun org-kill-is-subtree-p (&optional txt)
6169 "Check if the current kill is an outline subtree, or a set of trees.
6170 Returns nil if kill does not start with a headline, or if the first
6171 headline level is not the largest headline level in the tree.
6172 So this will actually accept several entries of equal levels as well,
6173 which is OK for `org-paste-subtree'.
6174 If optional TXT is given, check this string instead of the current kill."
6175 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6176 (start-level (and kill
6177 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6178 org-outline-regexp "\\)")
6179 kill)
6180 (- (match-end 2) (match-beginning 2) 1)))
6181 (re (concat "^" org-outline-regexp))
6182 (start (1+ (or (match-beginning 2) -1))))
6183 (if (not start-level)
6184 (progn
6185 nil) ;; does not even start with a heading
6186 (catch 'exit
6187 (while (setq start (string-match re kill (1+ start)))
6188 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6189 (throw 'exit nil)))
6190 t))))
6192 (defvar org-markers-to-move nil
6193 "Markers that should be moved with a cut-and-paste operation.
6194 Those markers are stored together with their positions relative to
6195 the start of the region.")
6197 (defun org-save-markers-in-region (beg end)
6198 "Check markers in region.
6199 If these markers are between BEG and END, record their position relative
6200 to BEG, so that after moving the block of text, we can put the markers back
6201 into place.
6202 This function gets called just before an entry or tree gets cut from the
6203 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6204 called immediately, to move the markers with the entries."
6205 (setq org-markers-to-move nil)
6206 (when (featurep 'org-clock)
6207 (org-clock-save-markers-for-cut-and-paste beg end))
6208 (when (featurep 'org-agenda)
6209 (org-agenda-save-markers-for-cut-and-paste beg end)))
6211 (defun org-check-and-save-marker (marker beg end)
6212 "Check if MARKER is between BEG and END.
6213 If yes, remember the marker and the distance to BEG."
6214 (when (and (marker-buffer marker)
6215 (equal (marker-buffer marker) (current-buffer)))
6216 (if (and (>= marker beg) (< marker end))
6217 (push (cons marker (- marker beg)) org-markers-to-move))))
6219 (defun org-reinstall-markers-in-region (beg)
6220 "Move all remembered markers to their position relative to BEG."
6221 (mapc (lambda (x)
6222 (move-marker (car x) (+ beg (cdr x))))
6223 org-markers-to-move)
6224 (setq org-markers-to-move nil))
6226 (defun org-narrow-to-subtree ()
6227 "Narrow buffer to the current subtree."
6228 (interactive)
6229 (save-excursion
6230 (save-match-data
6231 (narrow-to-region
6232 (progn (org-back-to-heading t) (point))
6233 (progn (org-end-of-subtree t) (point))))))
6235 (defun org-clone-subtree-with-time-shift (n &optional shift)
6236 "Clone the task (subtree) at point N times.
6237 The clones will be inserted as siblings.
6239 In interactive use, the user will be prompted for the number of clones
6240 to be produced, and for a time SHIFT, which may be a repeater as used
6241 in time stamps, for example `+3d'.
6243 When a valid repeater is given and the entry contains any time stamps,
6244 the clones will become a sequence in time, with time stamps in the
6245 subtree shifted for each clone produced. If SHIFT is nil or the
6246 empty string, time stamps will be left alone.
6248 If the original subtree did contain time stamps with a repeater,
6249 the following will happen:
6250 - the repeater will be removed in each clone
6251 - an additional clone will be produced, with the current, unshifted
6252 date(s) in the entry.
6253 - the original entry will be placed *after* all the clones, with
6254 repeater intact.
6255 - the start days in the repeater in the original entry will be shifted
6256 to past the last clone.
6257 I this way you can spell out a number of instances of a repeating task,
6258 and still retain the repeater to cover future instances of the task."
6259 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6260 (let (beg end template task
6261 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6262 (if (not (and (integerp n) (> n 0)))
6263 (error "Invalid number of replications %s" n))
6264 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6265 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6266 shift)))
6267 (error "Invalid shift specification %s" shift))
6268 (when doshift
6269 (setq shift-n (string-to-number (match-string 1 shift))
6270 shift-what (cdr (assoc (match-string 2 shift)
6271 '(("d" . day) ("w" . week)
6272 ("m" . month) ("y" . year))))))
6273 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6274 (setq nmin 1 nmax n)
6275 (org-back-to-heading t)
6276 (setq beg (point))
6277 (org-end-of-subtree t t)
6278 (setq end (point))
6279 (setq template (buffer-substring beg end))
6280 (when (and doshift
6281 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6282 (delete-region beg end)
6283 (setq end beg)
6284 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6285 (goto-char end)
6286 (loop for n from nmin to nmax do
6287 (if (not doshift)
6288 (setq task template)
6289 (with-temp-buffer
6290 (insert template)
6291 (org-mode)
6292 (goto-char (point-min))
6293 (while (re-search-forward org-ts-regexp-both nil t)
6294 (org-timestamp-change (* n shift-n) shift-what))
6295 (unless (= n n-no-remove)
6296 (goto-char (point-min))
6297 (while (re-search-forward org-ts-regexp nil t)
6298 (save-excursion
6299 (goto-char (match-beginning 0))
6300 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6301 (delete-region (match-beginning 1) (match-end 1))))))
6302 (setq task (buffer-string))))
6303 (insert task))
6304 (goto-char beg)))
6306 ;;; Outline Sorting
6308 (defun org-sort (with-case)
6309 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6310 Optional argument WITH-CASE means sort case-sensitively.
6311 With a double prefix argument, also remove duplicate entries."
6312 (interactive "P")
6313 (if (org-at-table-p)
6314 (org-call-with-arg 'org-table-sort-lines with-case)
6315 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6317 (defun org-sort-remove-invisible (s)
6318 (remove-text-properties 0 (length s) org-rm-props s)
6319 (while (string-match org-bracket-link-regexp s)
6320 (setq s (replace-match (if (match-end 2)
6321 (match-string 3 s)
6322 (match-string 1 s)) t t s)))
6325 (defvar org-priority-regexp) ; defined later in the file
6327 (defvar org-after-sorting-entries-or-items-hook nil
6328 "Hook that is run after a bunch of entries or items have been sorted.
6329 When children are sorted, the cursor is in the parent line when this
6330 hook gets called. When a region or a plain list is sorted, the cursor
6331 will be in the first entry of the sorted region/list.")
6333 (defun org-sort-entries-or-items
6334 (&optional with-case sorting-type getkey-func compare-func property)
6335 "Sort entries on a certain level of an outline tree, or plain list items.
6336 If there is an active region, the entries in the region are sorted.
6337 Else, if the cursor is before the first entry, sort the top-level items.
6338 Else, the children of the entry at point are sorted.
6339 If the cursor is at the first item in a plain list, the list items will be
6340 sorted.
6342 Sorting can be alphabetically, numerically, by date/time as given by
6343 a time stamp, by a property or by priority.
6345 The command prompts for the sorting type unless it has been given to the
6346 function through the SORTING-TYPE argument, which needs to a character,
6347 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6348 precise meaning of each character:
6350 n Numerically, by converting the beginning of the entry/item to a number.
6351 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6352 t By date/time, either the first active time stamp in the entry, or, if
6353 none exist, by the first inactive one.
6354 In items, only the first line will be chekced.
6355 s By the scheduled date/time.
6356 d By deadline date/time.
6357 c By creation time, which is assumed to be the first inactive time stamp
6358 at the beginning of a line.
6359 p By priority according to the cookie.
6360 r By the value of a property.
6362 Capital letters will reverse the sort order.
6364 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6365 called with point at the beginning of the record. It must return either
6366 a string or a number that should serve as the sorting key for that record.
6368 Comparing entries ignores case by default. However, with an optional argument
6369 WITH-CASE, the sorting considers case as well."
6370 (interactive "P")
6371 (let ((case-func (if with-case 'identity 'downcase))
6372 start beg end stars re re2
6373 txt what tmp plain-list-p)
6374 ;; Find beginning and end of region to sort
6375 (cond
6376 ((org-region-active-p)
6377 ;; we will sort the region
6378 (setq end (region-end)
6379 what "region")
6380 (goto-char (region-beginning))
6381 (if (not (org-on-heading-p)) (outline-next-heading))
6382 (setq start (point)))
6383 ((org-at-item-p)
6384 ;; we will sort this plain list
6385 (org-beginning-of-item-list) (setq start (point))
6386 (org-end-of-item-list) (setq end (point))
6387 (goto-char start)
6388 (setq plain-list-p t
6389 what "plain list"))
6390 ((or (org-on-heading-p)
6391 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6392 ;; we will sort the children of the current headline
6393 (org-back-to-heading)
6394 (setq start (point)
6395 end (progn (org-end-of-subtree t t)
6396 (org-back-over-empty-lines)
6397 (point))
6398 what "children")
6399 (goto-char start)
6400 (show-subtree)
6401 (outline-next-heading))
6403 ;; we will sort the top-level entries in this file
6404 (goto-char (point-min))
6405 (or (org-on-heading-p) (outline-next-heading))
6406 (setq start (point) end (point-max) what "top-level")
6407 (goto-char start)
6408 (show-all)))
6410 (setq beg (point))
6411 (if (>= beg end) (error "Nothing to sort"))
6413 (unless plain-list-p
6414 (looking-at "\\(\\*+\\)")
6415 (setq stars (match-string 1)
6416 re (concat "^" (regexp-quote stars) " +")
6417 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6418 txt (buffer-substring beg end))
6419 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6420 (if (and (not (equal stars "*")) (string-match re2 txt))
6421 (error "Region to sort contains a level above the first entry")))
6423 (unless sorting-type
6424 (message
6425 (if plain-list-p
6426 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6427 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6428 [t]ime [s]cheduled [d]eadline [c]reated
6429 A/N/T/S/D/C/P/O/F means reversed:")
6430 what)
6431 (setq sorting-type (read-char-exclusive))
6433 (and (= (downcase sorting-type) ?f)
6434 (setq getkey-func
6435 (org-ido-completing-read "Sort using function: "
6436 obarray 'fboundp t nil nil))
6437 (setq getkey-func (intern getkey-func)))
6439 (and (= (downcase sorting-type) ?r)
6440 (setq property
6441 (org-ido-completing-read "Property: "
6442 (mapcar 'list (org-buffer-property-keys t))
6443 nil t))))
6445 (message "Sorting entries...")
6447 (save-restriction
6448 (narrow-to-region start end)
6450 (let ((dcst (downcase sorting-type))
6451 (case-fold-search nil)
6452 (now (current-time)))
6453 (sort-subr
6454 (/= dcst sorting-type)
6455 ;; This function moves to the beginning character of the "record" to
6456 ;; be sorted.
6457 (if plain-list-p
6458 (lambda nil
6459 (if (org-at-item-p) t (goto-char (point-max))))
6460 (lambda nil
6461 (if (re-search-forward re nil t)
6462 (goto-char (match-beginning 0))
6463 (goto-char (point-max)))))
6464 ;; This function moves to the last character of the "record" being
6465 ;; sorted.
6466 (if plain-list-p
6467 'org-end-of-item
6468 (lambda nil
6469 (save-match-data
6470 (condition-case nil
6471 (outline-forward-same-level 1)
6472 (error
6473 (goto-char (point-max)))))))
6475 ;; This function returns the value that gets sorted against.
6476 (if plain-list-p
6477 (lambda nil
6478 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6479 (cond
6480 ((= dcst ?n)
6481 (string-to-number (buffer-substring (match-end 0)
6482 (point-at-eol))))
6483 ((= dcst ?a)
6484 (buffer-substring (match-end 0) (point-at-eol)))
6485 ((= dcst ?t)
6486 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6487 (re-search-forward org-ts-regexp-both
6488 (point-at-eol) t))
6489 (org-time-string-to-seconds (match-string 0))
6490 (time-to-seconds now)))
6491 ((= dcst ?f)
6492 (if getkey-func
6493 (progn
6494 (setq tmp (funcall getkey-func))
6495 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6496 tmp)
6497 (error "Invalid key function `%s'" getkey-func)))
6498 (t (error "Invalid sorting type `%c'" sorting-type)))))
6499 (lambda nil
6500 (cond
6501 ((= dcst ?n)
6502 (if (looking-at org-complex-heading-regexp)
6503 (string-to-number (match-string 4))
6504 nil))
6505 ((= dcst ?a)
6506 (if (looking-at org-complex-heading-regexp)
6507 (funcall case-func (match-string 4))
6508 nil))
6509 ((= dcst ?t)
6510 (let ((end (save-excursion (outline-next-heading) (point))))
6511 (if (or (re-search-forward org-ts-regexp end t)
6512 (re-search-forward org-ts-regexp-both end t))
6513 (org-time-string-to-seconds (match-string 0))
6514 (time-to-seconds now))))
6515 ((= dcst ?c)
6516 (let ((end (save-excursion (outline-next-heading) (point))))
6517 (if (re-search-forward
6518 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6519 end t)
6520 (org-time-string-to-seconds (match-string 0))
6521 (time-to-seconds now))))
6522 ((= dcst ?s)
6523 (let ((end (save-excursion (outline-next-heading) (point))))
6524 (if (re-search-forward org-scheduled-time-regexp end t)
6525 (org-time-string-to-seconds (match-string 1))
6526 (time-to-seconds now))))
6527 ((= dcst ?d)
6528 (let ((end (save-excursion (outline-next-heading) (point))))
6529 (if (re-search-forward org-deadline-time-regexp end t)
6530 (org-time-string-to-seconds (match-string 1))
6531 (time-to-seconds now))))
6532 ((= dcst ?p)
6533 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6534 (string-to-char (match-string 2))
6535 org-default-priority))
6536 ((= dcst ?r)
6537 (or (org-entry-get nil property) ""))
6538 ((= dcst ?o)
6539 (if (looking-at org-complex-heading-regexp)
6540 (- 9999 (length (member (match-string 2)
6541 org-todo-keywords-1)))))
6542 ((= dcst ?f)
6543 (if getkey-func
6544 (progn
6545 (setq tmp (funcall getkey-func))
6546 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6547 tmp)
6548 (error "Invalid key function `%s'" getkey-func)))
6549 (t (error "Invalid sorting type `%c'" sorting-type)))))
6551 (cond
6552 ((= dcst ?a) 'string<)
6553 ((= dcst ?f) compare-func)
6554 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6555 (t nil)))))
6556 (run-hooks 'org-after-sorting-entries-or-items-hook)
6557 (message "Sorting entries...done")))
6559 (defun org-do-sort (table what &optional with-case sorting-type)
6560 "Sort TABLE of WHAT according to SORTING-TYPE.
6561 The user will be prompted for the SORTING-TYPE if the call to this
6562 function does not specify it. WHAT is only for the prompt, to indicate
6563 what is being sorted. The sorting key will be extracted from
6564 the car of the elements of the table.
6565 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6566 (unless sorting-type
6567 (message
6568 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6569 what)
6570 (setq sorting-type (read-char-exclusive)))
6571 (let ((dcst (downcase sorting-type))
6572 extractfun comparefun)
6573 ;; Define the appropriate functions
6574 (cond
6575 ((= dcst ?n)
6576 (setq extractfun 'string-to-number
6577 comparefun (if (= dcst sorting-type) '< '>)))
6578 ((= dcst ?a)
6579 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6580 (lambda(x) (downcase (org-sort-remove-invisible x))))
6581 comparefun (if (= dcst sorting-type)
6582 'string<
6583 (lambda (a b) (and (not (string< a b))
6584 (not (string= a b)))))))
6585 ((= dcst ?t)
6586 (setq extractfun
6587 (lambda (x)
6588 (if (or (string-match org-ts-regexp x)
6589 (string-match org-ts-regexp-both x))
6590 (time-to-seconds
6591 (org-time-string-to-time (match-string 0 x)))
6593 comparefun (if (= dcst sorting-type) '< '>)))
6594 (t (error "Invalid sorting type `%c'" sorting-type)))
6596 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6597 table)
6598 (lambda (a b) (funcall comparefun (car a) (car b))))))
6601 ;;; The orgstruct minor mode
6603 ;; Define a minor mode which can be used in other modes in order to
6604 ;; integrate the org-mode structure editing commands.
6606 ;; This is really a hack, because the org-mode structure commands use
6607 ;; keys which normally belong to the major mode. Here is how it
6608 ;; works: The minor mode defines all the keys necessary to operate the
6609 ;; structure commands, but wraps the commands into a function which
6610 ;; tests if the cursor is currently at a headline or a plain list
6611 ;; item. If that is the case, the structure command is used,
6612 ;; temporarily setting many Org-mode variables like regular
6613 ;; expressions for filling etc. However, when any of those keys is
6614 ;; used at a different location, function uses `key-binding' to look
6615 ;; up if the key has an associated command in another currently active
6616 ;; keymap (minor modes, major mode, global), and executes that
6617 ;; command. There might be problems if any of the keys is otherwise
6618 ;; used as a prefix key.
6620 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6621 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6622 ;; addresses this by checking explicitly for both bindings.
6624 (defvar orgstruct-mode-map (make-sparse-keymap)
6625 "Keymap for the minor `orgstruct-mode'.")
6627 (defvar org-local-vars nil
6628 "List of local variables, for use by `orgstruct-mode'")
6630 ;;;###autoload
6631 (define-minor-mode orgstruct-mode
6632 "Toggle the minor more `orgstruct-mode'.
6633 This mode is for using Org-mode structure commands in other modes.
6634 The following key behave as if Org-mode was active, if the cursor
6635 is on a headline, or on a plain list item (both in the definition
6636 of Org-mode).
6638 M-up Move entry/item up
6639 M-down Move entry/item down
6640 M-left Promote
6641 M-right Demote
6642 M-S-up Move entry/item up
6643 M-S-down Move entry/item down
6644 M-S-left Promote subtree
6645 M-S-right Demote subtree
6646 M-q Fill paragraph and items like in Org-mode
6647 C-c ^ Sort entries
6648 C-c - Cycle list bullet
6649 TAB Cycle item visibility
6650 M-RET Insert new heading/item
6651 S-M-RET Insert new TODO heading / Checkbox item
6652 C-c C-c Set tags / toggle checkbox"
6653 nil " OrgStruct" nil
6654 (org-load-modules-maybe)
6655 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6657 ;;;###autoload
6658 (defun turn-on-orgstruct ()
6659 "Unconditionally turn on `orgstruct-mode'."
6660 (orgstruct-mode 1))
6662 (defun orgstruct++-mode (&optional arg)
6663 "Toggle `orgstruct-mode', the enhanced version of it.
6664 In addition to setting orgstruct-mode, this also exports all indentation and
6665 autofilling variables from org-mode into the buffer. It will also
6666 recognize item context in multiline items.
6667 Note that turning off orgstruct-mode will *not* remove the
6668 indentation/paragraph settings. This can only be done by refreshing the
6669 major mode, for example with \[normal-mode]."
6670 (interactive "P")
6671 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6672 (if (< arg 1)
6673 (orgstruct-mode -1)
6674 (orgstruct-mode 1)
6675 (let (var val)
6676 (mapc
6677 (lambda (x)
6678 (when (string-match
6679 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6680 (symbol-name (car x)))
6681 (setq var (car x) val (nth 1 x))
6682 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6683 org-local-vars)
6684 (org-set-local 'orgstruct-is-++ t))))
6686 (defvar orgstruct-is-++ nil
6687 "Is orgstruct-mode in ++ version in the current-buffer?")
6688 (make-variable-buffer-local 'orgstruct-is-++)
6690 ;;;###autoload
6691 (defun turn-on-orgstruct++ ()
6692 "Unconditionally turn on `orgstruct++-mode'."
6693 (orgstruct++-mode 1))
6695 (defun orgstruct-error ()
6696 "Error when there is no default binding for a structure key."
6697 (interactive)
6698 (error "This key has no function outside structure elements"))
6700 (defun orgstruct-setup ()
6701 "Setup orgstruct keymaps."
6702 (let ((nfunc 0)
6703 (bindings
6704 (list
6705 '([(meta up)] org-metaup)
6706 '([(meta down)] org-metadown)
6707 '([(meta left)] org-metaleft)
6708 '([(meta right)] org-metaright)
6709 '([(meta shift up)] org-shiftmetaup)
6710 '([(meta shift down)] org-shiftmetadown)
6711 '([(meta shift left)] org-shiftmetaleft)
6712 '([(meta shift right)] org-shiftmetaright)
6713 '([?\e (up)] org-metaup)
6714 '([?\e (down)] org-metadown)
6715 '([?\e (left)] org-metaleft)
6716 '([?\e (right)] org-metaright)
6717 '([?\e (shift up)] org-shiftmetaup)
6718 '([?\e (shift down)] org-shiftmetadown)
6719 '([?\e (shift left)] org-shiftmetaleft)
6720 '([?\e (shift right)] org-shiftmetaright)
6721 '([(shift up)] org-shiftup)
6722 '([(shift down)] org-shiftdown)
6723 '([(shift left)] org-shiftleft)
6724 '([(shift right)] org-shiftright)
6725 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6726 '("\M-q" fill-paragraph)
6727 '("\C-c^" org-sort)
6728 '("\C-c-" org-cycle-list-bullet)))
6729 elt key fun cmd)
6730 (while (setq elt (pop bindings))
6731 (setq nfunc (1+ nfunc))
6732 (setq key (org-key (car elt))
6733 fun (nth 1 elt)
6734 cmd (orgstruct-make-binding fun nfunc key))
6735 (org-defkey orgstruct-mode-map key cmd))
6737 ;; Special treatment needed for TAB and RET
6738 (org-defkey orgstruct-mode-map [(tab)]
6739 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6740 (org-defkey orgstruct-mode-map "\C-i"
6741 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6743 (org-defkey orgstruct-mode-map "\M-\C-m"
6744 (orgstruct-make-binding 'org-insert-heading 105
6745 "\M-\C-m" [(meta return)]))
6746 (org-defkey orgstruct-mode-map [(meta return)]
6747 (orgstruct-make-binding 'org-insert-heading 106
6748 [(meta return)] "\M-\C-m"))
6750 (org-defkey orgstruct-mode-map [(shift meta return)]
6751 (orgstruct-make-binding 'org-insert-todo-heading 107
6752 [(meta return)] "\M-\C-m"))
6754 (org-defkey orgstruct-mode-map "\e\C-m"
6755 (orgstruct-make-binding 'org-insert-heading 108
6756 "\e\C-m" [?\e (return)]))
6757 (org-defkey orgstruct-mode-map [?\e (return)]
6758 (orgstruct-make-binding 'org-insert-heading 109
6759 [?\e (return)] "\e\C-m"))
6760 (org-defkey orgstruct-mode-map [?\e (shift return)]
6761 (orgstruct-make-binding 'org-insert-todo-heading 110
6762 [?\e (return)] "\e\C-m"))
6764 (unless org-local-vars
6765 (setq org-local-vars (org-get-local-variables)))
6769 (defun orgstruct-make-binding (fun n &rest keys)
6770 "Create a function for binding in the structure minor mode.
6771 FUN is the command to call inside a table. N is used to create a unique
6772 command name. KEYS are keys that should be checked in for a command
6773 to execute outside of tables."
6774 (eval
6775 (list 'defun
6776 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6777 '(arg)
6778 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6779 "Outside of structure, run the binding of `"
6780 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6781 "'.")
6782 '(interactive "p")
6783 (list 'if
6784 `(org-context-p 'headline 'item
6785 (and orgstruct-is-++
6786 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6787 'item-body))
6788 (list 'org-run-like-in-org-mode (list 'quote fun))
6789 (list 'let '(orgstruct-mode)
6790 (list 'call-interactively
6791 (append '(or)
6792 (mapcar (lambda (k)
6793 (list 'key-binding k))
6794 keys)
6795 '('orgstruct-error))))))))
6797 (defun org-context-p (&rest contexts)
6798 "Check if local context is any of CONTEXTS.
6799 Possible values in the list of contexts are `table', `headline', and `item'."
6800 (let ((pos (point)))
6801 (goto-char (point-at-bol))
6802 (prog1 (or (and (memq 'table contexts)
6803 (looking-at "[ \t]*|"))
6804 (and (memq 'headline contexts)
6805 ;;????????? (looking-at "\\*+"))
6806 (looking-at outline-regexp))
6807 (and (memq 'item contexts)
6808 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6809 (and (memq 'item-body contexts)
6810 (org-in-item-p)))
6811 (goto-char pos))))
6813 (defun org-get-local-variables ()
6814 "Return a list of all local variables in an org-mode buffer."
6815 (let (varlist)
6816 (with-current-buffer (get-buffer-create "*Org tmp*")
6817 (erase-buffer)
6818 (org-mode)
6819 (setq varlist (buffer-local-variables)))
6820 (kill-buffer "*Org tmp*")
6821 (delq nil
6822 (mapcar
6823 (lambda (x)
6824 (setq x
6825 (if (symbolp x)
6826 (list x)
6827 (list (car x) (list 'quote (cdr x)))))
6828 (if (string-match
6829 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6830 (symbol-name (car x)))
6831 x nil))
6832 varlist))))
6834 ;;;###autoload
6835 (defun org-run-like-in-org-mode (cmd)
6836 "Run a command, pretending that the current buffer is in Org-mode.
6837 This will temporarily bind local variables that are typically bound in
6838 Org-mode to the values they have in Org-mode, and then interactively
6839 call CMD."
6840 (org-load-modules-maybe)
6841 (unless org-local-vars
6842 (setq org-local-vars (org-get-local-variables)))
6843 (eval (list 'let org-local-vars
6844 (list 'call-interactively (list 'quote cmd)))))
6846 ;;;; Archiving
6848 (defun org-get-category (&optional pos)
6849 "Get the category applying to position POS."
6850 (get-text-property (or pos (point)) 'org-category))
6852 (defun org-refresh-category-properties ()
6853 "Refresh category text properties in the buffer."
6854 (let ((def-cat (cond
6855 ((null org-category)
6856 (if buffer-file-name
6857 (file-name-sans-extension
6858 (file-name-nondirectory buffer-file-name))
6859 "???"))
6860 ((symbolp org-category) (symbol-name org-category))
6861 (t org-category)))
6862 beg end cat pos optionp)
6863 (org-unmodified
6864 (save-excursion
6865 (save-restriction
6866 (widen)
6867 (goto-char (point-min))
6868 (put-text-property (point) (point-max) 'org-category def-cat)
6869 (while (re-search-forward
6870 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6871 (setq pos (match-end 0)
6872 optionp (equal (char-after (match-beginning 0)) ?#)
6873 cat (org-trim (match-string 2)))
6874 (if optionp
6875 (setq beg (point-at-bol) end (point-max))
6876 (org-back-to-heading t)
6877 (setq beg (point) end (org-end-of-subtree t t)))
6878 (put-text-property beg end 'org-category cat)
6879 (goto-char pos)))))))
6882 ;;;; Link Stuff
6884 ;;; Link abbreviations
6886 (defun org-link-expand-abbrev (link)
6887 "Apply replacements as defined in `org-link-abbrev-alist."
6888 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6889 (let* ((key (match-string 1 link))
6890 (as (or (assoc key org-link-abbrev-alist-local)
6891 (assoc key org-link-abbrev-alist)))
6892 (tag (and (match-end 2) (match-string 3 link)))
6893 rpl)
6894 (if (not as)
6895 link
6896 (setq rpl (cdr as))
6897 (cond
6898 ((symbolp rpl) (funcall rpl tag))
6899 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6900 ((string-match "%h" rpl)
6901 (replace-match (url-hexify-string (or tag "")) t t rpl))
6902 (t (concat rpl tag)))))
6903 link))
6905 ;;; Storing and inserting links
6907 (defvar org-insert-link-history nil
6908 "Minibuffer history for links inserted with `org-insert-link'.")
6910 (defvar org-stored-links nil
6911 "Contains the links stored with `org-store-link'.")
6913 (defvar org-store-link-plist nil
6914 "Plist with info about the most recently link created with `org-store-link'.")
6916 (defvar org-link-protocols nil
6917 "Link protocols added to Org-mode using `org-add-link-type'.")
6919 (defvar org-store-link-functions nil
6920 "List of functions that are called to create and store a link.
6921 Each function will be called in turn until one returns a non-nil
6922 value. Each function should check if it is responsible for creating
6923 this link (for example by looking at the major mode).
6924 If not, it must exit and return nil.
6925 If yes, it should return a non-nil value after a calling
6926 `org-store-link-props' with a list of properties and values.
6927 Special properties are:
6929 :type The link prefix. like \"http\". This must be given.
6930 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6931 This is obligatory as well.
6932 :description Optional default description for the second pair
6933 of brackets in an Org-mode link. The user can still change
6934 this when inserting this link into an Org-mode buffer.
6936 In addition to these, any additional properties can be specified
6937 and then used in remember templates.")
6939 (defun org-add-link-type (type &optional follow export)
6940 "Add TYPE to the list of `org-link-types'.
6941 Re-compute all regular expressions depending on `org-link-types'
6943 FOLLOW and EXPORT are two functions.
6945 FOLLOW should take the link path as the single argument and do whatever
6946 is necessary to follow the link, for example find a file or display
6947 a mail message.
6949 EXPORT should format the link path for export to one of the export formats.
6950 It should be a function accepting three arguments:
6952 path the path of the link, the text after the prefix (like \"http:\")
6953 desc the description of the link, if any, nil if there was no description
6954 format the export format, a symbol like `html' or `latex'.
6956 The function may use the FORMAT information to return different values
6957 depending on the format. The return value will be put literally into
6958 the exported file.
6959 Org-mode has a built-in default for exporting links. If you are happy with
6960 this default, there is no need to define an export function for the link
6961 type. For a simple example of an export function, see `org-bbdb.el'."
6962 (add-to-list 'org-link-types type t)
6963 (org-make-link-regexps)
6964 (if (assoc type org-link-protocols)
6965 (setcdr (assoc type org-link-protocols) (list follow export))
6966 (push (list type follow export) org-link-protocols)))
6968 ;;;###autoload
6969 (defun org-store-link (arg)
6970 "\\<org-mode-map>Store an org-link to the current location.
6971 This link is added to `org-stored-links' and can later be inserted
6972 into an org-buffer with \\[org-insert-link].
6974 For some link types, a prefix arg is interpreted:
6975 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6976 For file links, arg negates `org-context-in-file-links'."
6977 (interactive "P")
6978 (org-load-modules-maybe)
6979 (setq org-store-link-plist nil) ; reset
6980 (let ((outline-regexp (org-get-limited-outline-regexp))
6981 link cpltxt desc description search txt custom-id)
6982 (cond
6984 ((run-hook-with-args-until-success 'org-store-link-functions)
6985 (setq link (plist-get org-store-link-plist :link)
6986 desc (or (plist-get org-store-link-plist :description) link)))
6988 ((equal (buffer-name) "*Org Edit Src Example*")
6989 (let (label gc)
6990 (while (or (not label)
6991 (save-excursion
6992 (save-restriction
6993 (widen)
6994 (goto-char (point-min))
6995 (re-search-forward
6996 (regexp-quote (format org-coderef-label-format label))
6997 nil t))))
6998 (when label (message "Label exists already") (sit-for 2))
6999 (setq label (read-string "Code line label: " label)))
7000 (end-of-line 1)
7001 (setq link (format org-coderef-label-format label))
7002 (setq gc (- 79 (length link)))
7003 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7004 (insert link)
7005 (setq link (concat "(" label ")") desc nil)))
7007 ((eq major-mode 'calendar-mode)
7008 (let ((cd (calendar-cursor-to-date)))
7009 (setq link
7010 (format-time-string
7011 (car org-time-stamp-formats)
7012 (apply 'encode-time
7013 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7014 nil nil nil))))
7015 (org-store-link-props :type "calendar" :date cd)))
7017 ((eq major-mode 'w3-mode)
7018 (setq cpltxt (if (and (buffer-name)
7019 (not (string-match "Untitled" (buffer-name))))
7020 (buffer-name)
7021 (url-view-url t))
7022 link (org-make-link (url-view-url t)))
7023 (org-store-link-props :type "w3" :url (url-view-url t)))
7025 ((eq major-mode 'w3m-mode)
7026 (setq cpltxt (or w3m-current-title w3m-current-url)
7027 link (org-make-link w3m-current-url))
7028 (org-store-link-props :type "w3m" :url (url-view-url t)))
7030 ((setq search (run-hook-with-args-until-success
7031 'org-create-file-search-functions))
7032 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7033 "::" search))
7034 (setq cpltxt (or description link)))
7036 ((eq major-mode 'image-mode)
7037 (setq cpltxt (concat "file:"
7038 (abbreviate-file-name buffer-file-name))
7039 link (org-make-link cpltxt))
7040 (org-store-link-props :type "image" :file buffer-file-name))
7042 ((eq major-mode 'dired-mode)
7043 ;; link to the file in the current line
7044 (setq cpltxt (concat "file:"
7045 (abbreviate-file-name
7046 (expand-file-name
7047 (dired-get-filename nil t))))
7048 link (org-make-link cpltxt)))
7050 ((and buffer-file-name (org-mode-p))
7051 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7052 (cond
7053 ((org-in-regexp "<<\\(.*?\\)>>")
7054 (setq cpltxt
7055 (concat "file:"
7056 (abbreviate-file-name buffer-file-name)
7057 "::" (match-string 1))
7058 link (org-make-link cpltxt)))
7059 ((and (featurep 'org-id)
7060 (or (eq org-link-to-org-use-id t)
7061 (and (eq org-link-to-org-use-id 'create-if-interactive)
7062 (interactive-p))
7063 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7064 (interactive-p)
7065 (not custom-id))
7066 (and org-link-to-org-use-id
7067 (condition-case nil
7068 (org-entry-get nil "ID")
7069 (error nil)))))
7070 ;; We can make a link using the ID.
7071 (setq link (condition-case nil
7072 (prog1 (org-id-store-link)
7073 (setq desc (plist-get org-store-link-plist
7074 :description)))
7075 (error
7076 ;; probably before first headline, link to file only
7077 (concat "file:"
7078 (abbreviate-file-name buffer-file-name))))))
7080 ;; Just link to current headline
7081 (setq cpltxt (concat "file:"
7082 (abbreviate-file-name buffer-file-name)))
7083 ;; Add a context search string
7084 (when (org-xor org-context-in-file-links arg)
7085 (setq txt (cond
7086 ((org-on-heading-p) nil)
7087 ((org-region-active-p)
7088 (buffer-substring (region-beginning) (region-end)))
7089 (t nil)))
7090 (when (or (null txt) (string-match "\\S-" txt))
7091 (setq cpltxt
7092 (concat cpltxt "::"
7093 (condition-case nil
7094 (org-make-org-heading-search-string txt)
7095 (error "")))
7096 desc (or (nth 4 (org-heading-components)) "NONE"))))
7097 (if (string-match "::\\'" cpltxt)
7098 (setq cpltxt (substring cpltxt 0 -2)))
7099 (setq link (org-make-link cpltxt)))))
7101 ((buffer-file-name (buffer-base-buffer))
7102 ;; Just link to this file here.
7103 (setq cpltxt (concat "file:"
7104 (abbreviate-file-name
7105 (buffer-file-name (buffer-base-buffer)))))
7106 ;; Add a context string
7107 (when (org-xor org-context-in-file-links arg)
7108 (setq txt (if (org-region-active-p)
7109 (buffer-substring (region-beginning) (region-end))
7110 (buffer-substring (point-at-bol) (point-at-eol))))
7111 ;; Only use search option if there is some text.
7112 (when (string-match "\\S-" txt)
7113 (setq cpltxt
7114 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7115 desc "NONE")))
7116 (setq link (org-make-link cpltxt)))
7118 ((interactive-p)
7119 (error "Cannot link to a buffer which is not visiting a file"))
7121 (t (setq link nil)))
7123 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7124 (setq link (or link cpltxt)
7125 desc (or desc cpltxt))
7126 (if (equal desc "NONE") (setq desc nil))
7128 (if (and (or (interactive-p) executing-kbd-macro) link)
7129 (progn
7130 (setq org-stored-links
7131 (cons (list link desc) org-stored-links))
7132 (message "Stored: %s" (or desc link))
7133 (when custom-id
7134 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7135 "::#" custom-id))
7136 (setq org-stored-links
7137 (cons (list link desc) org-stored-links))))
7138 (and link (org-make-link-string link desc)))))
7140 (defun org-store-link-props (&rest plist)
7141 "Store link properties, extract names and addresses."
7142 (let (x adr)
7143 (when (setq x (plist-get plist :from))
7144 (setq adr (mail-extract-address-components x))
7145 (setq plist (plist-put plist :fromname (car adr)))
7146 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7147 (when (setq x (plist-get plist :to))
7148 (setq adr (mail-extract-address-components x))
7149 (setq plist (plist-put plist :toname (car adr)))
7150 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7151 (let ((from (plist-get plist :from))
7152 (to (plist-get plist :to)))
7153 (when (and from to org-from-is-user-regexp)
7154 (setq plist
7155 (plist-put plist :fromto
7156 (if (string-match org-from-is-user-regexp from)
7157 (concat "to %t")
7158 (concat "from %f"))))))
7159 (setq org-store-link-plist plist))
7161 (defun org-add-link-props (&rest plist)
7162 "Add these properties to the link property list."
7163 (let (key value)
7164 (while plist
7165 (setq key (pop plist) value (pop plist))
7166 (setq org-store-link-plist
7167 (plist-put org-store-link-plist key value)))))
7169 (defun org-email-link-description (&optional fmt)
7170 "Return the description part of an email link.
7171 This takes information from `org-store-link-plist' and formats it
7172 according to FMT (default from `org-email-link-description-format')."
7173 (setq fmt (or fmt org-email-link-description-format))
7174 (let* ((p org-store-link-plist)
7175 (to (plist-get p :toaddress))
7176 (from (plist-get p :fromaddress))
7177 (table
7178 (list
7179 (cons "%c" (plist-get p :fromto))
7180 (cons "%F" (plist-get p :from))
7181 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7182 (cons "%T" (plist-get p :to))
7183 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7184 (cons "%s" (plist-get p :subject))
7185 (cons "%m" (plist-get p :message-id)))))
7186 (when (string-match "%c" fmt)
7187 ;; Check if the user wrote this message
7188 (if (and org-from-is-user-regexp from to
7189 (save-match-data (string-match org-from-is-user-regexp from)))
7190 (setq fmt (replace-match "to %t" t t fmt))
7191 (setq fmt (replace-match "from %f" t t fmt))))
7192 (org-replace-escapes fmt table)))
7194 (defun org-make-org-heading-search-string (&optional string heading)
7195 "Make search string for STRING or current headline."
7196 (interactive)
7197 (let ((s (or string (org-get-heading))))
7198 (unless (and string (not heading))
7199 ;; We are using a headline, clean up garbage in there.
7200 (if (string-match org-todo-regexp s)
7201 (setq s (replace-match "" t t s)))
7202 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7203 (setq s (replace-match "" t t s)))
7204 (setq s (org-trim s))
7205 (if (string-match (concat "^\\(" org-quote-string "\\|"
7206 org-comment-string "\\)") s)
7207 (setq s (replace-match "" t t s)))
7208 (while (string-match org-ts-regexp s)
7209 (setq s (replace-match "" t t s))))
7210 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7211 (setq s (replace-match " " t t s)))
7212 (or string (setq s (concat "*" s))) ; Add * for headlines
7213 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7215 (defun org-make-link (&rest strings)
7216 "Concatenate STRINGS."
7217 (apply 'concat strings))
7219 (defun org-make-link-string (link &optional description)
7220 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7221 (unless (string-match "\\S-" link)
7222 (error "Empty link"))
7223 (when (stringp description)
7224 ;; Remove brackets from the description, they are fatal.
7225 (while (string-match "\\[" description)
7226 (setq description (replace-match "{" t t description)))
7227 (while (string-match "\\]" description)
7228 (setq description (replace-match "}" t t description))))
7229 (when (equal (org-link-escape link) description)
7230 ;; No description needed, it is identical
7231 (setq description nil))
7232 (when (and (not description)
7233 (not (equal link (org-link-escape link))))
7234 (setq description (org-extract-attributes link)))
7235 (concat "[[" (org-link-escape link) "]"
7236 (if description (concat "[" description "]") "")
7237 "]"))
7239 (defconst org-link-escape-chars
7240 '((?\ . "%20")
7241 (?\[ . "%5B")
7242 (?\] . "%5D")
7243 (?\340 . "%E0") ; `a
7244 (?\342 . "%E2") ; ^a
7245 (?\347 . "%E7") ; ,c
7246 (?\350 . "%E8") ; `e
7247 (?\351 . "%E9") ; 'e
7248 (?\352 . "%EA") ; ^e
7249 (?\356 . "%EE") ; ^i
7250 (?\364 . "%F4") ; ^o
7251 (?\371 . "%F9") ; `u
7252 (?\373 . "%FB") ; ^u
7253 (?\; . "%3B")
7254 (?? . "%3F")
7255 (?= . "%3D")
7256 (?+ . "%2B")
7258 "Association list of escapes for some characters problematic in links.
7259 This is the list that is used for internal purposes.")
7261 (defvar org-url-encoding-use-url-hexify nil)
7263 (defconst org-link-escape-chars-browser
7264 '((?\ . "%20")) ; 32 for the SPC char
7265 "Association list of escapes for some characters problematic in links.
7266 This is the list that is used before handing over to the browser.")
7268 (defun org-link-escape (text &optional table)
7269 "Escape characters in TEXT that are problematic for links."
7270 (if org-url-encoding-use-url-hexify
7271 (url-hexify-string text)
7272 (setq table (or table org-link-escape-chars))
7273 (when text
7274 (let ((re (mapconcat (lambda (x) (regexp-quote
7275 (char-to-string (car x))))
7276 table "\\|")))
7277 (while (string-match re text)
7278 (setq text
7279 (replace-match
7280 (cdr (assoc (string-to-char (match-string 0 text))
7281 table))
7282 t t text)))
7283 text))))
7285 (defun org-link-unescape (text &optional table)
7286 "Reverse the action of `org-link-escape'."
7287 (if org-url-encoding-use-url-hexify
7288 (url-unhex-string text)
7289 (setq table (or table org-link-escape-chars))
7290 (when text
7291 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7292 table "\\|")))
7293 (while (string-match re text)
7294 (setq text
7295 (replace-match
7296 (char-to-string (car (rassoc (match-string 0 text) table)))
7297 t t text)))
7298 text))))
7300 (defun org-xor (a b)
7301 "Exclusive or."
7302 (if a (not b) b))
7304 (defun org-fixup-message-id-for-http (s)
7305 "Replace special characters in a message id, so it can be used in an http query."
7306 (while (string-match "<" s)
7307 (setq s (replace-match "%3C" t t s)))
7308 (while (string-match ">" s)
7309 (setq s (replace-match "%3E" t t s)))
7310 (while (string-match "@" s)
7311 (setq s (replace-match "%40" t t s)))
7314 ;;;###autoload
7315 (defun org-insert-link-global ()
7316 "Insert a link like Org-mode does.
7317 This command can be called in any mode to insert a link in Org-mode syntax."
7318 (interactive)
7319 (org-load-modules-maybe)
7320 (org-run-like-in-org-mode 'org-insert-link))
7322 (defun org-insert-link (&optional complete-file link-location)
7323 "Insert a link. At the prompt, enter the link.
7325 Completion can be used to insert any of the link protocol prefixes like
7326 http or ftp in use.
7328 The history can be used to select a link previously stored with
7329 `org-store-link'. When the empty string is entered (i.e. if you just
7330 press RET at the prompt), the link defaults to the most recently
7331 stored link. As SPC triggers completion in the minibuffer, you need to
7332 use M-SPC or C-q SPC to force the insertion of a space character.
7334 You will also be prompted for a description, and if one is given, it will
7335 be displayed in the buffer instead of the link.
7337 If there is already a link at point, this command will allow you to edit link
7338 and description parts.
7340 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7341 be selected using completion. The path to the file will be relative to the
7342 current directory if the file is in the current directory or a subdirectory.
7343 Otherwise, the link will be the absolute path as completed in the minibuffer
7344 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7345 option `org-link-file-path-type'.
7347 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7348 the current directory or below.
7350 With three \\[universal-argument] prefixes, negate the meaning of
7351 `org-keep-stored-link-after-insertion'.
7353 If `org-make-link-description-function' is non-nil, this function will be
7354 called with the link target, and the result will be the default
7355 link description.
7357 If the LINK-LOCATION parameter is non-nil, this value will be
7358 used as the link location instead of reading one interactively."
7359 (interactive "P")
7360 (let* ((wcf (current-window-configuration))
7361 (region (if (org-region-active-p)
7362 (buffer-substring (region-beginning) (region-end))))
7363 (remove (and region (list (region-beginning) (region-end))))
7364 (desc region)
7365 tmphist ; byte-compile incorrectly complains about this
7366 (link link-location)
7367 entry file all-prefixes)
7368 (cond
7369 (link-location) ; specified by arg, just use it.
7370 ((org-in-regexp org-bracket-link-regexp 1)
7371 ;; We do have a link at point, and we are going to edit it.
7372 (setq remove (list (match-beginning 0) (match-end 0)))
7373 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7374 (setq link (read-string "Link: "
7375 (org-link-unescape
7376 (org-match-string-no-properties 1)))))
7377 ((or (org-in-regexp org-angle-link-re)
7378 (org-in-regexp org-plain-link-re))
7379 ;; Convert to bracket link
7380 (setq remove (list (match-beginning 0) (match-end 0))
7381 link (read-string "Link: "
7382 (org-remove-angle-brackets (match-string 0)))))
7383 ((member complete-file '((4) (16)))
7384 ;; Completing read for file names.
7385 (setq link (org-file-complete-link complete-file)))
7387 ;; Read link, with completion for stored links.
7388 (with-output-to-temp-buffer "*Org Links*"
7389 (princ "Insert a link.
7390 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7391 (when org-stored-links
7392 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7393 (princ (mapconcat
7394 (lambda (x)
7395 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7396 (reverse org-stored-links) "\n"))))
7397 (let ((cw (selected-window)))
7398 (select-window (get-buffer-window "*Org Links*"))
7399 (setq truncate-lines t)
7400 (unless (pos-visible-in-window-p (point-max))
7401 (org-fit-window-to-buffer))
7402 (and (window-live-p cw) (select-window cw)))
7403 ;; Fake a link history, containing the stored links.
7404 (setq tmphist (append (mapcar 'car org-stored-links)
7405 org-insert-link-history))
7406 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7407 (mapcar 'car org-link-abbrev-alist)
7408 org-link-types))
7409 (unwind-protect
7410 (progn
7411 (setq link
7412 (let ((org-completion-use-ido nil))
7413 (org-completing-read
7414 "Link: "
7415 (mapcar (lambda (x) (list (concat x ":")))
7416 all-prefixes)
7417 nil nil nil
7418 'tmphist
7419 (or (car (car org-stored-links))))))
7420 (if (or (member link all-prefixes)
7421 (and (equal ":" (substring link -1))
7422 (member (substring link 0 -1) all-prefixes)
7423 (setq link (substring link 0 -1))))
7424 (setq link (org-link-try-special-completion link))))
7425 (set-window-configuration wcf)
7426 (kill-buffer "*Org Links*"))
7427 (setq entry (assoc link org-stored-links))
7428 (or entry (push link org-insert-link-history))
7429 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7430 (not org-keep-stored-link-after-insertion))
7431 (setq org-stored-links (delq (assoc link org-stored-links)
7432 org-stored-links)))
7433 (setq desc (or desc (nth 1 entry)))))
7435 (if (string-match org-plain-link-re link)
7436 ;; URL-like link, normalize the use of angular brackets.
7437 (setq link (org-make-link (org-remove-angle-brackets link))))
7439 ;; Check if we are linking to the current file with a search option
7440 ;; If yes, simplify the link by using only the search option.
7441 (when (and buffer-file-name
7442 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7443 (let* ((path (match-string 1 link))
7444 (case-fold-search nil)
7445 (search (match-string 2 link)))
7446 (save-match-data
7447 (if (equal (file-truename buffer-file-name) (file-truename path))
7448 ;; We are linking to this same file, with a search option
7449 (setq link search)))))
7451 ;; Check if we can/should use a relative path. If yes, simplify the link
7452 (when (string-match "^file:\\(.*\\)" link)
7453 (let* ((path (match-string 1 link))
7454 (origpath path)
7455 (case-fold-search nil))
7456 (cond
7457 ((or (eq org-link-file-path-type 'absolute)
7458 (equal complete-file '(16)))
7459 (setq path (abbreviate-file-name (expand-file-name path))))
7460 ((eq org-link-file-path-type 'noabbrev)
7461 (setq path (expand-file-name path)))
7462 ((eq org-link-file-path-type 'relative)
7463 (setq path (file-relative-name path)))
7465 (save-match-data
7466 (if (string-match (concat "^" (regexp-quote
7467 (file-name-as-directory
7468 (expand-file-name "."))))
7469 (expand-file-name path))
7470 ;; We are linking a file with relative path name.
7471 (setq path (substring (expand-file-name path)
7472 (match-end 0)))
7473 (setq path (abbreviate-file-name (expand-file-name path)))))))
7474 (setq link (concat "file:" path))
7475 (if (equal desc origpath)
7476 (setq desc path))))
7478 (if org-make-link-description-function
7479 (setq desc (funcall org-make-link-description-function link desc)))
7481 (setq desc (read-string "Description: " desc))
7482 (unless (string-match "\\S-" desc) (setq desc nil))
7483 (if remove (apply 'delete-region remove))
7484 (insert (org-make-link-string link desc))))
7486 (defun org-link-try-special-completion (type)
7487 "If there is completion support for link type TAPE, offer it."
7488 (let ((fun (intern (concat "org-" type "-complete-link"))))
7489 (if (functionp fun)
7490 (funcall fun)
7491 (read-string "Link (no completion support): " (concat type ":")))))
7493 (defun org-file-complete-link (&optional arg)
7494 "Create a file link using completion."
7495 (let (file link)
7496 (setq file (read-file-name "File: "))
7497 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7498 (pwd1 (file-name-as-directory (abbreviate-file-name
7499 (expand-file-name ".")))))
7500 (cond
7501 ((equal arg '(16))
7502 (setq link (org-make-link
7503 "file:"
7504 (abbreviate-file-name (expand-file-name file)))))
7505 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7506 (setq link (org-make-link "file:" (match-string 1 file))))
7507 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7508 (expand-file-name file))
7509 (setq link (org-make-link
7510 "file:" (match-string 1 (expand-file-name file)))))
7511 (t (setq link (org-make-link "file:" file)))))
7512 link))
7514 (defun org-completing-read (&rest args)
7515 "Completing-read with SPACE being a normal character."
7516 (let ((minibuffer-local-completion-map
7517 (copy-keymap minibuffer-local-completion-map)))
7518 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7519 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7520 (apply 'org-ido-completing-read args)))
7522 (defun org-completing-read-no-ido (&rest args)
7523 (let (org-completion-use-ido)
7524 (apply 'org-completing-read args)))
7526 (defun org-ido-completing-read (&rest args)
7527 "Completing-read using `ido-mode' speedups if available"
7528 (if (and org-completion-use-ido
7529 (fboundp 'ido-completing-read)
7530 (boundp 'ido-mode) ido-mode
7531 (listp (second args)))
7532 (let ((ido-enter-matching-directory nil))
7533 (apply 'ido-completing-read (concat (car args))
7534 (mapcar (lambda (x) (car x)) (nth 1 args))
7535 (cddr args)))
7536 (apply 'completing-read args)))
7538 (defun org-extract-attributes (s)
7539 "Extract the attributes cookie from a string and set as text property."
7540 (let (a attr (start 0) key value)
7541 (save-match-data
7542 (when (string-match "{{\\([^}]+\\)}}$" s)
7543 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7544 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7545 (setq key (match-string 1 a) value (match-string 2 a)
7546 start (match-end 0)
7547 attr (plist-put attr (intern key) value))))
7548 (org-add-props s nil 'org-attr attr))
7551 (defun org-extract-attributes-from-string (tag)
7552 (let (key value attr)
7553 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7554 (setq key (match-string 1 tag) value (match-string 2 tag)
7555 tag (replace-match "" t t tag)
7556 attr (plist-put attr (intern key) value)))
7557 (cons tag attr)))
7559 (defun org-attributes-to-string (plist)
7560 "Format a property list into an HTML attribute list."
7561 (let ((s "") key value)
7562 (while plist
7563 (setq key (pop plist) value (pop plist))
7564 (and value
7565 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7568 ;;; Opening/following a link
7570 (defvar org-link-search-failed nil)
7572 (defun org-next-link ()
7573 "Move forward to the next link.
7574 If the link is in hidden text, expose it."
7575 (interactive)
7576 (when (and org-link-search-failed (eq this-command last-command))
7577 (goto-char (point-min))
7578 (message "Link search wrapped back to beginning of buffer"))
7579 (setq org-link-search-failed nil)
7580 (let* ((pos (point))
7581 (ct (org-context))
7582 (a (assoc :link ct)))
7583 (if a (goto-char (nth 2 a)))
7584 (if (re-search-forward org-any-link-re nil t)
7585 (progn
7586 (goto-char (match-beginning 0))
7587 (if (org-invisible-p) (org-show-context)))
7588 (goto-char pos)
7589 (setq org-link-search-failed t)
7590 (error "No further link found"))))
7592 (defun org-previous-link ()
7593 "Move backward to the previous link.
7594 If the link is in hidden text, expose it."
7595 (interactive)
7596 (when (and org-link-search-failed (eq this-command last-command))
7597 (goto-char (point-max))
7598 (message "Link search wrapped back to end of buffer"))
7599 (setq org-link-search-failed nil)
7600 (let* ((pos (point))
7601 (ct (org-context))
7602 (a (assoc :link ct)))
7603 (if a (goto-char (nth 1 a)))
7604 (if (re-search-backward org-any-link-re nil t)
7605 (progn
7606 (goto-char (match-beginning 0))
7607 (if (org-invisible-p) (org-show-context)))
7608 (goto-char pos)
7609 (setq org-link-search-failed t)
7610 (error "No further link found"))))
7612 (defun org-translate-link (s)
7613 "Translate a link string if a translation function has been defined."
7614 (if (and org-link-translation-function
7615 (fboundp org-link-translation-function)
7616 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7617 (progn
7618 (setq s (funcall org-link-translation-function
7619 (match-string 1) (match-string 2)))
7620 (concat (car s) ":" (cdr s)))
7623 (defun org-translate-link-from-planner (type path)
7624 "Translate a link from Emacs Planner syntax so that Org can follow it.
7625 This is still an experimental function, your mileage may vary."
7626 (cond
7627 ((member type '("http" "https" "news" "ftp"))
7628 ;; standard Internet links are the same.
7629 nil)
7630 ((and (equal type "irc") (string-match "^//" path))
7631 ;; Planner has two / at the beginning of an irc link, we have 1.
7632 ;; We should have zero, actually....
7633 (setq path (substring path 1)))
7634 ((and (equal type "lisp") (string-match "^/" path))
7635 ;; Planner has a slash, we do not.
7636 (setq type "elisp" path (substring path 1)))
7637 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7638 ;; A typical message link. Planner has the id after the fina slash,
7639 ;; we separate it with a hash mark
7640 (setq path (concat (match-string 1 path) "#"
7641 (org-remove-angle-brackets (match-string 2 path)))))
7643 (cons type path))
7645 (defun org-find-file-at-mouse (ev)
7646 "Open file link or URL at mouse."
7647 (interactive "e")
7648 (mouse-set-point ev)
7649 (org-open-at-point 'in-emacs))
7651 (defun org-open-at-mouse (ev)
7652 "Open file link or URL at mouse."
7653 (interactive "e")
7654 (mouse-set-point ev)
7655 (if (eq major-mode 'org-agenda-mode)
7656 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7657 (org-open-at-point))
7659 (defvar org-window-config-before-follow-link nil
7660 "The window configuration before following a link.
7661 This is saved in case the need arises to restore it.")
7663 (defvar org-open-link-marker (make-marker)
7664 "Marker pointing to the location where `org-open-at-point; was called.")
7666 ;;;###autoload
7667 (defun org-open-at-point-global ()
7668 "Follow a link like Org-mode does.
7669 This command can be called in any mode to follow a link that has
7670 Org-mode syntax."
7671 (interactive)
7672 (org-run-like-in-org-mode 'org-open-at-point))
7674 ;;;###autoload
7675 (defun org-open-link-from-string (s &optional arg)
7676 "Open a link in the string S, as if it was in Org-mode."
7677 (interactive "sLink: \nP")
7678 (let ((reference-buffer (current-buffer)))
7679 (with-temp-buffer
7680 (let ((org-inhibit-startup t))
7681 (org-mode)
7682 (insert s)
7683 (goto-char (point-min))
7684 (org-open-at-point arg reference-buffer)))))
7686 (defun org-open-at-point (&optional in-emacs reference-buffer)
7687 "Open link at or after point.
7688 If there is no link at point, this function will search forward up to
7689 the end of the current line.
7690 Normally, files will be opened by an appropriate application. If the
7691 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7692 With a double prefix argument, try to open outside of Emacs, in the
7693 application the system uses for this file type."
7694 (interactive "P")
7695 (org-load-modules-maybe)
7696 (move-marker org-open-link-marker (point))
7697 (setq org-window-config-before-follow-link (current-window-configuration))
7698 (org-remove-occur-highlights nil nil t)
7699 (cond
7700 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7701 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7702 (org-footnote-action))
7704 (let (type path link line search (pos (point)))
7705 (catch 'match
7706 (save-excursion
7707 (skip-chars-forward "^]\n\r")
7708 (when (org-in-regexp org-bracket-link-regexp)
7709 (setq link (org-extract-attributes
7710 (org-link-unescape (org-match-string-no-properties 1))))
7711 (while (string-match " *\n *" link)
7712 (setq link (replace-match " " t t link)))
7713 (setq link (org-link-expand-abbrev link))
7714 (cond
7715 ((or (file-name-absolute-p link)
7716 (string-match "^\\.\\.?/" link))
7717 (setq type "file" path link))
7718 ((string-match org-link-re-with-space3 link)
7719 (setq type (match-string 1 link) path (match-string 2 link)))
7720 (t (setq type "thisfile" path link)))
7721 (throw 'match t)))
7723 (when (get-text-property (point) 'org-linked-text)
7724 (setq type "thisfile"
7725 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7726 (1+ (point)) (point))
7727 path (buffer-substring
7728 (previous-single-property-change pos 'org-linked-text)
7729 (next-single-property-change pos 'org-linked-text)))
7730 (throw 'match t))
7732 (save-excursion
7733 (when (or (org-in-regexp org-angle-link-re)
7734 (org-in-regexp org-plain-link-re))
7735 (setq type (match-string 1) path (match-string 2))
7736 (throw 'match t)))
7737 (save-excursion
7738 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7739 (setq type "tags"
7740 path (match-string 1))
7741 (while (string-match ":" path)
7742 (setq path (replace-match "+" t t path)))
7743 (throw 'match t)))
7744 (when (org-in-regexp "<\\([^><\n]+\\)>")
7745 (setq type "tree-match"
7746 path (match-string 1))
7747 (throw 'match t)))
7748 (unless path
7749 (error "No link found"))
7751 ;; switch back to reference buffer
7752 ;; needed when if called in a temporary buffer through
7753 ;; org-open-link-from-string
7754 (and reference-buffer (switch-to-buffer reference-buffer))
7756 ;; Remove any trailing spaces in path
7757 (if (string-match " +\\'" path)
7758 (setq path (replace-match "" t t path)))
7759 (if (and org-link-translation-function
7760 (fboundp org-link-translation-function))
7761 ;; Check if we need to translate the link
7762 (let ((tmp (funcall org-link-translation-function type path)))
7763 (setq type (car tmp) path (cdr tmp))))
7765 (cond
7767 ((assoc type org-link-protocols)
7768 (funcall (nth 1 (assoc type org-link-protocols)) path))
7770 ((equal type "mailto")
7771 (let ((cmd (car org-link-mailto-program))
7772 (args (cdr org-link-mailto-program)) args1
7773 (address path) (subject "") a)
7774 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7775 (setq address (match-string 1 path)
7776 subject (org-link-escape (match-string 2 path))))
7777 (while args
7778 (cond
7779 ((not (stringp (car args))) (push (pop args) args1))
7780 (t (setq a (pop args))
7781 (if (string-match "%a" a)
7782 (setq a (replace-match address t t a)))
7783 (if (string-match "%s" a)
7784 (setq a (replace-match subject t t a)))
7785 (push a args1))))
7786 (apply cmd (nreverse args1))))
7788 ((member type '("http" "https" "ftp" "news"))
7789 (browse-url (concat type ":" (org-link-escape
7790 path org-link-escape-chars-browser))))
7792 ((member type '("message"))
7793 (browse-url (concat type ":" path)))
7795 ((string= type "tags")
7796 (org-tags-view in-emacs path))
7797 ((string= type "thisfile")
7798 (if in-emacs
7799 (switch-to-buffer-other-window
7800 (org-get-buffer-for-internal-link (current-buffer)))
7801 (org-mark-ring-push))
7802 (let ((cmd `(org-link-search
7803 ,path
7804 ,(cond ((equal in-emacs '(4)) 'occur)
7805 ((equal in-emacs '(16)) 'org-occur)
7806 (t nil))
7807 ,pos)))
7808 (condition-case nil (eval cmd)
7809 (error (progn (widen) (eval cmd))))))
7811 ((string= type "tree-match")
7812 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7814 ((string= type "file")
7815 (if (string-match "::\\([0-9]+\\)\\'" path)
7816 (setq line (string-to-number (match-string 1 path))
7817 path (substring path 0 (match-beginning 0)))
7818 (if (string-match "::\\(.+\\)\\'" path)
7819 (setq search (match-string 1 path)
7820 path (substring path 0 (match-beginning 0)))))
7821 (if (string-match "[*?{]" (file-name-nondirectory path))
7822 (dired path)
7823 (org-open-file path in-emacs line search)))
7825 ((string= type "news")
7826 (require 'org-gnus)
7827 (org-gnus-follow-link path))
7829 ((string= type "shell")
7830 (let ((cmd path))
7831 (if (or (not org-confirm-shell-link-function)
7832 (funcall org-confirm-shell-link-function
7833 (format "Execute \"%s\" in shell? "
7834 (org-add-props cmd nil
7835 'face 'org-warning))))
7836 (progn
7837 (message "Executing %s" cmd)
7838 (shell-command cmd))
7839 (error "Abort"))))
7841 ((string= type "elisp")
7842 (let ((cmd path))
7843 (if (or (not org-confirm-elisp-link-function)
7844 (funcall org-confirm-elisp-link-function
7845 (format "Execute \"%s\" as elisp? "
7846 (org-add-props cmd nil
7847 'face 'org-warning))))
7848 (message "%s => %s" cmd
7849 (if (equal (string-to-char cmd) ?\()
7850 (eval (read cmd))
7851 (call-interactively (read cmd))))
7852 (error "Abort"))))
7855 (browse-url-at-point))))))
7856 (move-marker org-open-link-marker nil)
7857 (run-hook-with-args 'org-follow-link-hook))
7859 ;;;; Time estimates
7861 (defun org-get-effort (&optional pom)
7862 "Get the effort estimate for the current entry."
7863 (org-entry-get pom org-effort-property))
7865 ;;; File search
7867 (defvar org-create-file-search-functions nil
7868 "List of functions to construct the right search string for a file link.
7869 These functions are called in turn with point at the location to
7870 which the link should point.
7872 A function in the hook should first test if it would like to
7873 handle this file type, for example by checking the major-mode or
7874 the file extension. If it decides not to handle this file, it
7875 should just return nil to give other functions a chance. If it
7876 does handle the file, it must return the search string to be used
7877 when following the link. The search string will be part of the
7878 file link, given after a double colon, and `org-open-at-point'
7879 will automatically search for it. If special measures must be
7880 taken to make the search successful, another function should be
7881 added to the companion hook `org-execute-file-search-functions',
7882 which see.
7884 A function in this hook may also use `setq' to set the variable
7885 `description' to provide a suggestion for the descriptive text to
7886 be used for this link when it gets inserted into an Org-mode
7887 buffer with \\[org-insert-link].")
7889 (defvar org-execute-file-search-functions nil
7890 "List of functions to execute a file search triggered by a link.
7892 Functions added to this hook must accept a single argument, the
7893 search string that was part of the file link, the part after the
7894 double colon. The function must first check if it would like to
7895 handle this search, for example by checking the major-mode or the
7896 file extension. If it decides not to handle this search, it
7897 should just return nil to give other functions a chance. If it
7898 does handle the search, it must return a non-nil value to keep
7899 other functions from trying.
7901 Each function can access the current prefix argument through the
7902 variable `current-prefix-argument'. Note that a single prefix is
7903 used to force opening a link in Emacs, so it may be good to only
7904 use a numeric or double prefix to guide the search function.
7906 In case this is needed, a function in this hook can also restore
7907 the window configuration before `org-open-at-point' was called using:
7909 (set-window-configuration org-window-config-before-follow-link)")
7911 (defun org-link-search (s &optional type avoid-pos)
7912 "Search for a link search option.
7913 If S is surrounded by forward slashes, it is interpreted as a
7914 regular expression. In org-mode files, this will create an `org-occur'
7915 sparse tree. In ordinary files, `occur' will be used to list matches.
7916 If the current buffer is in `dired-mode', grep will be used to search
7917 in all files. If AVOID-POS is given, ignore matches near that position."
7918 (let ((case-fold-search t)
7919 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7920 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7921 (append '(("") (" ") ("\t") ("\n"))
7922 org-emphasis-alist)
7923 "\\|") "\\)"))
7924 (pos (point))
7925 (pre nil) (post nil)
7926 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7927 (cond
7928 ;; First check if there are any special
7929 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7930 ;; Now try the builtin stuff
7931 ((and (equal (string-to-char s0) ?#)
7932 (> (length s0) 1)
7933 (save-excursion
7934 (goto-char (point-min))
7935 (and
7936 (re-search-forward
7937 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
7938 (setq type 'dedicated
7939 pos (match-beginning 0))))
7940 ;; There is an exact target for this
7941 (goto-char pos)
7942 (org-back-to-heading t)))
7943 ((save-excursion
7944 (goto-char (point-min))
7945 (and
7946 (re-search-forward
7947 (concat "<<" (regexp-quote s0) ">>") nil t)
7948 (setq type 'dedicated
7949 pos (match-beginning 0))))
7950 ;; There is an exact target for this
7951 (goto-char pos))
7952 ((and (string-match "^(\\(.*\\))$" s0)
7953 (save-excursion
7954 (goto-char (point-min))
7955 (and
7956 (re-search-forward
7957 (concat "[^[]" (regexp-quote
7958 (format org-coderef-label-format
7959 (match-string 1 s0))))
7960 nil t)
7961 (setq type 'dedicated
7962 pos (1+ (match-beginning 0))))))
7963 ;; There is a coderef target for this
7964 (goto-char pos))
7965 ((string-match "^/\\(.*\\)/$" s)
7966 ;; A regular expression
7967 (cond
7968 ((org-mode-p)
7969 (org-occur (match-string 1 s)))
7970 ;;((eq major-mode 'dired-mode)
7971 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7972 (t (org-do-occur (match-string 1 s)))))
7974 ;; A normal search strings
7975 (when (equal (string-to-char s) ?*)
7976 ;; Anchor on headlines, post may include tags.
7977 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7978 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7979 s (substring s 1)))
7980 (remove-text-properties
7981 0 (length s)
7982 '(face nil mouse-face nil keymap nil fontified nil) s)
7983 ;; Make a series of regular expressions to find a match
7984 (setq words (org-split-string s "[ \n\r\t]+")
7986 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7987 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7988 "\\)" markers)
7989 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7990 re2a (concat "[ \t\r\n]" re2a_)
7991 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7992 re4 (concat "[^a-zA-Z_]" re4_)
7994 re1 (concat pre re2 post)
7995 re3 (concat pre (if pre re4_ re4) post)
7996 re5 (concat pre ".*" re4)
7997 re2 (concat pre re2)
7998 re2a (concat pre (if pre re2a_ re2a))
7999 re4 (concat pre (if pre re4_ re4))
8000 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8001 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8002 re5 "\\)"
8004 (cond
8005 ((eq type 'org-occur) (org-occur reall))
8006 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8007 (t (goto-char (point-min))
8008 (setq type 'fuzzy)
8009 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8010 (org-search-not-self 1 re1 nil t)
8011 (org-search-not-self 1 re2 nil t)
8012 (org-search-not-self 1 re2a nil t)
8013 (org-search-not-self 1 re3 nil t)
8014 (org-search-not-self 1 re4 nil t)
8015 (org-search-not-self 1 re5 nil t)
8017 (goto-char (match-beginning 1))
8018 (goto-char pos)
8019 (error "No match")))))
8021 ;; Normal string-search
8022 (goto-char (point-min))
8023 (if (search-forward s nil t)
8024 (goto-char (match-beginning 0))
8025 (error "No match"))))
8026 (and (org-mode-p) (org-show-context 'link-search))
8027 type))
8029 (defun org-search-not-self (group &rest args)
8030 "Execute `re-search-forward', but only accept matches that do not
8031 enclose the position of `org-open-link-marker'."
8032 (let ((m org-open-link-marker))
8033 (catch 'exit
8034 (while (apply 're-search-forward args)
8035 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8036 (goto-char (match-end group))
8037 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8038 (> (match-beginning 0) (marker-position m))
8039 (< (match-end 0) (marker-position m)))
8040 (save-match-data
8041 (or (not (org-in-regexp
8042 org-bracket-link-analytic-regexp 1))
8043 (not (match-end 4)) ; no description
8044 (and (<= (match-beginning 4) (point))
8045 (>= (match-end 4) (point))))))
8046 (throw 'exit (point))))))))
8048 (defun org-get-buffer-for-internal-link (buffer)
8049 "Return a buffer to be used for displaying the link target of internal links."
8050 (cond
8051 ((not org-display-internal-link-with-indirect-buffer)
8052 buffer)
8053 ((string-match "(Clone)$" (buffer-name buffer))
8054 (message "Buffer is already a clone, not making another one")
8055 ;; we also do not modify visibility in this case
8056 buffer)
8057 (t ; make a new indirect buffer for displaying the link
8058 (let* ((bn (buffer-name buffer))
8059 (ibn (concat bn "(Clone)"))
8060 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8061 (with-current-buffer ib (org-overview))
8062 ib))))
8064 (defun org-do-occur (regexp &optional cleanup)
8065 "Call the Emacs command `occur'.
8066 If CLEANUP is non-nil, remove the printout of the regular expression
8067 in the *Occur* buffer. This is useful if the regex is long and not useful
8068 to read."
8069 (occur regexp)
8070 (when cleanup
8071 (let ((cwin (selected-window)) win beg end)
8072 (when (setq win (get-buffer-window "*Occur*"))
8073 (select-window win))
8074 (goto-char (point-min))
8075 (when (re-search-forward "match[a-z]+" nil t)
8076 (setq beg (match-end 0))
8077 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8078 (setq end (1- (match-beginning 0)))))
8079 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8080 (goto-char (point-min))
8081 (select-window cwin))))
8083 ;;; The mark ring for links jumps
8085 (defvar org-mark-ring nil
8086 "Mark ring for positions before jumps in Org-mode.")
8087 (defvar org-mark-ring-last-goto nil
8088 "Last position in the mark ring used to go back.")
8089 ;; Fill and close the ring
8090 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8091 (loop for i from 1 to org-mark-ring-length do
8092 (push (make-marker) org-mark-ring))
8093 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8094 org-mark-ring)
8096 (defun org-mark-ring-push (&optional pos buffer)
8097 "Put the current position or POS into the mark ring and rotate it."
8098 (interactive)
8099 (setq pos (or pos (point)))
8100 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8101 (move-marker (car org-mark-ring)
8102 (or pos (point))
8103 (or buffer (current-buffer)))
8104 (message "%s"
8105 (substitute-command-keys
8106 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8108 (defun org-mark-ring-goto (&optional n)
8109 "Jump to the previous position in the mark ring.
8110 With prefix arg N, jump back that many stored positions. When
8111 called several times in succession, walk through the entire ring.
8112 Org-mode commands jumping to a different position in the current file,
8113 or to another Org-mode file, automatically push the old position
8114 onto the ring."
8115 (interactive "p")
8116 (let (p m)
8117 (if (eq last-command this-command)
8118 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8119 (setq p org-mark-ring))
8120 (setq org-mark-ring-last-goto p)
8121 (setq m (car p))
8122 (switch-to-buffer (marker-buffer m))
8123 (goto-char m)
8124 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8126 (defun org-remove-angle-brackets (s)
8127 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8128 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8130 (defun org-add-angle-brackets (s)
8131 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8132 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8134 (defun org-remove-double-quotes (s)
8135 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8136 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8139 ;;; Following specific links
8141 (defun org-follow-timestamp-link ()
8142 (cond
8143 ((org-at-date-range-p t)
8144 (let ((org-agenda-start-on-weekday)
8145 (t1 (match-string 1))
8146 (t2 (match-string 2)))
8147 (setq t1 (time-to-days (org-time-string-to-time t1))
8148 t2 (time-to-days (org-time-string-to-time t2)))
8149 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8150 ((org-at-timestamp-p t)
8151 (org-agenda-list nil (time-to-days (org-time-string-to-time
8152 (substring (match-string 1) 0 10)))
8154 (t (error "This should not happen"))))
8157 ;;; Following file links
8158 (defvar org-wait nil)
8159 (defun org-open-file (path &optional in-emacs line search)
8160 "Open the file at PATH.
8161 First, this expands any special file name abbreviations. Then the
8162 configuration variable `org-file-apps' is checked if it contains an
8163 entry for this file type, and if yes, the corresponding command is launched.
8165 If no application is found, Emacs simply visits the file.
8167 With optional prefix argument IN-EMACS, Emacs will visit the file.
8168 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8169 and o use an external application to visit the file.
8171 Optional LINE specifies a line to go to, optional SEARCH a string to
8172 search for. If LINE or SEARCH is given, the file will always be
8173 opened in Emacs.
8174 If the file does not exist, an error is thrown."
8175 (setq in-emacs (or in-emacs line search))
8176 (let* ((file (if (equal path "")
8177 buffer-file-name
8178 (substitute-in-file-name (expand-file-name path))))
8179 (apps (append org-file-apps (org-default-apps)))
8180 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8181 (dirp (if remp nil (file-directory-p file)))
8182 (file (if (and dirp org-open-directory-means-index-dot-org)
8183 (concat (file-name-as-directory file) "index.org")
8184 file))
8185 (a-m-a-p (assq 'auto-mode apps))
8186 (dfile (downcase file))
8187 (old-buffer (current-buffer))
8188 (old-pos (point))
8189 (old-mode major-mode)
8190 ext cmd)
8191 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8192 (setq ext (match-string 1 dfile))
8193 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8194 (setq ext (match-string 1 dfile))))
8195 (cond
8196 ((equal in-emacs '(16))
8197 (setq cmd (cdr (assoc 'system apps))))
8198 (in-emacs (setq cmd 'emacs))
8200 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8201 (and dirp (cdr (assoc 'directory apps)))
8202 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8203 'string-match)
8204 (cdr (assoc ext apps))
8205 (cdr (assoc t apps))))))
8206 (when (eq cmd 'system)
8207 (setq cmd (cdr (assoc 'system apps))))
8208 (when (eq cmd 'default)
8209 (setq cmd (cdr (assoc t apps))))
8210 (when (eq cmd 'mailcap)
8211 (require 'mailcap)
8212 (mailcap-parse-mailcaps)
8213 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8214 (command (mailcap-mime-info mime-type)))
8215 (if (stringp command)
8216 (setq cmd command)
8217 (setq cmd 'emacs))))
8218 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8219 (not (file-exists-p file))
8220 (not org-open-non-existing-files))
8221 (error "No such file: %s" file))
8222 (cond
8223 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8224 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8225 (while (string-match "['\"]%s['\"]" cmd)
8226 (setq cmd (replace-match "%s" t t cmd)))
8227 (while (string-match "%s" cmd)
8228 (setq cmd (replace-match
8229 (save-match-data
8230 (shell-quote-argument
8231 (convert-standard-filename file)))
8232 t t cmd)))
8233 (save-window-excursion
8234 (start-process-shell-command cmd nil cmd)
8235 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8237 ((or (stringp cmd)
8238 (eq cmd 'emacs))
8239 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8240 (widen)
8241 (if line (goto-line line)
8242 (if search (org-link-search search))))
8243 ((consp cmd)
8244 (let ((file (convert-standard-filename file)))
8245 (eval cmd)))
8246 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8247 (and (org-mode-p) (eq old-mode 'org-mode)
8248 (or (not (equal old-buffer (current-buffer)))
8249 (not (equal old-pos (point))))
8250 (org-mark-ring-push old-pos old-buffer))))
8252 (defun org-default-apps ()
8253 "Return the default applications for this operating system."
8254 (cond
8255 ((eq system-type 'darwin)
8256 org-file-apps-defaults-macosx)
8257 ((eq system-type 'windows-nt)
8258 org-file-apps-defaults-windowsnt)
8259 (t org-file-apps-defaults-gnu)))
8261 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8262 "Convert extensions to regular expressions in the cars of LIST.
8263 Also, weed out any non-string entries, because the return value is used
8264 only for regexp matching.
8265 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8266 point to the symbol `emacs', indicating that the file should
8267 be opened in Emacs."
8268 (append
8269 (delq nil
8270 (mapcar (lambda (x)
8271 (if (not (stringp (car x)))
8273 (if (string-match "\\W" (car x))
8275 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8276 list))
8277 (if add-auto-mode
8278 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8280 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8281 (defun org-file-remote-p (file)
8282 "Test whether FILE specifies a location on a remote system.
8283 Return non-nil if the location is indeed remote.
8285 For example, the filename \"/user@host:/foo\" specifies a location
8286 on the system \"/user@host:\"."
8287 (cond ((fboundp 'file-remote-p)
8288 (file-remote-p file))
8289 ((fboundp 'tramp-handle-file-remote-p)
8290 (tramp-handle-file-remote-p file))
8291 ((and (boundp 'ange-ftp-name-format)
8292 (string-match (car ange-ftp-name-format) file))
8294 (t nil)))
8297 ;;;; Refiling
8299 (defun org-get-org-file ()
8300 "Read a filename, with default directory `org-directory'."
8301 (let ((default (or org-default-notes-file remember-data-file)))
8302 (read-file-name (format "File name [%s]: " default)
8303 (file-name-as-directory org-directory)
8304 default)))
8306 (defun org-notes-order-reversed-p ()
8307 "Check if the current file should receive notes in reversed order."
8308 (cond
8309 ((not org-reverse-note-order) nil)
8310 ((eq t org-reverse-note-order) t)
8311 ((not (listp org-reverse-note-order)) nil)
8312 (t (catch 'exit
8313 (let ((all org-reverse-note-order)
8314 entry)
8315 (while (setq entry (pop all))
8316 (if (string-match (car entry) buffer-file-name)
8317 (throw 'exit (cdr entry))))
8318 nil)))))
8320 (defvar org-refile-target-table nil
8321 "The list of refile targets, created by `org-refile'.")
8323 (defvar org-agenda-new-buffers nil
8324 "Buffers created to visit agenda files.")
8326 (defun org-get-refile-targets (&optional default-buffer)
8327 "Produce a table with refile targets."
8328 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8329 targets txt re files f desc descre fast-path-p level pos0)
8330 (message "Getting targets...")
8331 (with-current-buffer (or default-buffer (current-buffer))
8332 (while (setq entry (pop entries))
8333 (setq files (car entry) desc (cdr entry))
8334 (setq fast-path-p nil)
8335 (cond
8336 ((null files) (setq files (list (current-buffer))))
8337 ((eq files 'org-agenda-files)
8338 (setq files (org-agenda-files 'unrestricted)))
8339 ((and (symbolp files) (fboundp files))
8340 (setq files (funcall files)))
8341 ((and (symbolp files) (boundp files))
8342 (setq files (symbol-value files))))
8343 (if (stringp files) (setq files (list files)))
8344 (cond
8345 ((eq (car desc) :tag)
8346 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8347 ((eq (car desc) :todo)
8348 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8349 ((eq (car desc) :regexp)
8350 (setq descre (cdr desc)))
8351 ((eq (car desc) :level)
8352 (setq descre (concat "^\\*\\{" (number-to-string
8353 (if org-odd-levels-only
8354 (1- (* 2 (cdr desc)))
8355 (cdr desc)))
8356 "\\}[ \t]")))
8357 ((eq (car desc) :maxlevel)
8358 (setq fast-path-p t)
8359 (setq descre (concat "^\\*\\{1," (number-to-string
8360 (if org-odd-levels-only
8361 (1- (* 2 (cdr desc)))
8362 (cdr desc)))
8363 "\\}[ \t]")))
8364 (t (error "Bad refiling target description %s" desc)))
8365 (while (setq f (pop files))
8366 (save-excursion
8367 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8368 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8369 (setq f (expand-file-name f))
8370 (if (eq org-refile-use-outline-path 'file)
8371 (push (list (file-name-nondirectory f) f nil nil) targets))
8372 (save-excursion
8373 (save-restriction
8374 (widen)
8375 (goto-char (point-min))
8376 (while (re-search-forward descre nil t)
8377 (goto-char (setq pos0 (point-at-bol)))
8378 (catch 'next
8379 (when org-refile-target-verify-function
8380 (save-match-data
8381 (or (funcall org-refile-target-verify-function)
8382 (throw 'next t))))
8383 (when (looking-at org-complex-heading-regexp)
8384 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8385 txt (org-link-display-format (match-string 4))
8386 re (concat "^" (regexp-quote
8387 (buffer-substring (match-beginning 1)
8388 (match-end 4)))))
8389 (if (match-end 5) (setq re (concat re "[ \t]+"
8390 (regexp-quote
8391 (match-string 5)))))
8392 (setq re (concat re "[ \t]*$"))
8393 (when org-refile-use-outline-path
8394 (setq txt (mapconcat 'org-protect-slash
8395 (append
8396 (if (eq org-refile-use-outline-path 'file)
8397 (list (file-name-nondirectory
8398 (buffer-file-name (buffer-base-buffer))))
8399 (if (eq org-refile-use-outline-path 'full-file-path)
8400 (list (buffer-file-name (buffer-base-buffer)))))
8401 (org-get-outline-path fast-path-p level txt)
8402 (list txt))
8403 "/")))
8404 (push (list txt f re (point)) targets)))
8405 (when (= (point) pos0)
8406 ;; verification function has not moved point
8407 (goto-char (point-at-eol))))))))))
8408 (message "Getting targets...done")
8409 (nreverse targets)))
8411 (defun org-protect-slash (s)
8412 (while (string-match "/" s)
8413 (setq s (replace-match "\\" t t s)))
8416 (defvar org-olpa (make-vector 20 nil))
8418 (defun org-get-outline-path (&optional fastp level heading)
8419 "Return the outline path to the current entry, as a list."
8420 (if fastp
8421 (progn
8422 (if (> level 19)
8423 (error "Outline path failure, more than 19 levels."))
8424 (loop for i from level upto 19 do
8425 (aset org-olpa i nil))
8426 (prog1
8427 (delq nil (append org-olpa nil))
8428 (aset org-olpa level heading)))
8429 (let (rtn)
8430 (save-excursion
8431 (while (org-up-heading-safe)
8432 (when (looking-at org-complex-heading-regexp)
8433 (push (org-match-string-no-properties 4) rtn)))
8434 rtn))))
8436 (defvar org-refile-history nil
8437 "History for refiling operations.")
8439 (defvar org-after-refile-insert-hook nil
8440 "Hook run after `org-refile' has inserted its stuff at the new location.
8441 Note that this is still *before* the stuff will be removed from
8442 the *old* location.")
8444 (defun org-refile (&optional goto default-buffer rfloc)
8445 "Move the entry at point to another heading.
8446 The list of target headings is compiled using the information in
8447 `org-refile-targets', which see. This list is created before each use
8448 and will therefore always be up-to-date.
8450 At the target location, the entry is filed as a subitem of the target heading.
8451 Depending on `org-reverse-note-order', the new subitem will either be the
8452 first or the last subitem.
8454 If there is an active region, all entries in that region will be moved.
8455 However, the region must fulfil the requirement that the first heading
8456 is the first one sets the top-level of the moved text - at most siblings
8457 below it are allowed.
8459 With prefix arg GOTO, the command will only visit the target location,
8460 not actually move anything.
8461 With a double prefix `C-u C-u', go to the location where the last refiling
8462 operation has put the subtree.
8464 RFLOC can be a refile location obtained in a different way.
8466 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8467 (interactive "P")
8468 (let* ((cbuf (current-buffer))
8469 (regionp (org-region-active-p))
8470 (region-start (and regionp (region-beginning)))
8471 (region-end (and regionp (region-end)))
8472 (region-length (and regionp (- region-end region-start)))
8473 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8474 pos it nbuf file re level reversed)
8475 (when regionp (goto-char region-start)
8476 (unless (org-kill-is-subtree-p
8477 (buffer-substring region-start region-end))
8478 (error "The region is not a (sequence of) subtree(s)")))
8479 (if (equal goto '(16))
8480 (org-refile-goto-last-stored)
8481 (when (setq it (or rfloc
8482 (org-refile-get-location
8483 (if goto "Goto: " "Refile to: ") default-buffer
8484 org-refile-allow-creating-parent-nodes)))
8485 (setq file (nth 1 it)
8486 re (nth 2 it)
8487 pos (nth 3 it))
8488 (if (and (not goto)
8490 (equal (buffer-file-name) file)
8491 (if regionp
8492 (and (>= pos region-start)
8493 (<= pos region-end))
8494 (and (>= pos (point))
8495 (< pos (save-excursion
8496 (org-end-of-subtree t t))))))
8497 (error "Cannot refile to position inside the tree or region"))
8499 (setq nbuf (or (find-buffer-visiting file)
8500 (find-file-noselect file)))
8501 (if goto
8502 (progn
8503 (switch-to-buffer nbuf)
8504 (goto-char pos)
8505 (org-show-context 'org-goto))
8506 (if regionp
8507 (progn
8508 (kill-new (buffer-substring region-start region-end))
8509 (org-save-markers-in-region region-start region-end))
8510 (org-copy-subtree 1 nil t))
8511 (save-excursion
8512 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8513 (find-file-noselect file))))
8514 (setq reversed (org-notes-order-reversed-p))
8515 (save-excursion
8516 (save-restriction
8517 (widen)
8518 (if pos
8519 (progn
8520 (goto-char pos)
8521 (looking-at outline-regexp)
8522 (setq level (org-get-valid-level (funcall outline-level) 1))
8523 (goto-char
8524 (if reversed
8525 (or (outline-next-heading) (point-max))
8526 (or (save-excursion (outline-get-next-sibling))
8527 (org-end-of-subtree t t)
8528 (point-max)))))
8529 (setq level 1)
8530 (if (not reversed)
8531 (goto-char (point-max))
8532 (goto-char (point-min))
8533 (or (outline-next-heading) (goto-char (point-max)))))
8534 (if (not (bolp)) (newline))
8535 (bookmark-set "org-refile-last-stored")
8536 (org-paste-subtree level)
8537 (if (fboundp 'deactivate-mark) (deactivate-mark))
8538 (run-hooks 'org-after-refile-insert-hook))))
8539 (if regionp
8540 (delete-region (point) (+ (point) region-length))
8541 (org-cut-subtree))
8542 (when (featurep 'org-inlinetask)
8543 (org-inlinetask-remove-END-maybe))
8544 (setq org-markers-to-move nil)
8545 (message "Refiled to \"%s\"" (car it))))))
8546 (org-reveal))
8548 (defun org-refile-goto-last-stored ()
8549 "Go to the location where the last refile was stored."
8550 (interactive)
8551 (bookmark-jump "org-refile-last-stored")
8552 (message "This is the location of the last refile"))
8554 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8555 "Prompt the user for a refile location, using PROMPT."
8556 (let ((org-refile-targets org-refile-targets)
8557 (org-refile-use-outline-path org-refile-use-outline-path))
8558 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8559 (unless org-refile-target-table
8560 (error "No refile targets"))
8561 (let* ((cbuf (current-buffer))
8562 (partial-completion-mode nil)
8563 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8564 (cfunc (if (and org-refile-use-outline-path
8565 org-outline-path-complete-in-steps)
8566 'org-olpath-completing-read
8567 'org-ido-completing-read))
8568 (extra (if org-refile-use-outline-path "/" ""))
8569 (filename (and cfn (expand-file-name cfn)))
8570 (tbl (mapcar
8571 (lambda (x)
8572 (if (and (not (member org-refile-use-outline-path
8573 '(file full-file-path)))
8574 (not (equal filename (nth 1 x))))
8575 (cons (concat (car x) extra " ("
8576 (file-name-nondirectory (nth 1 x)) ")")
8577 (cdr x))
8578 (cons (concat (car x) extra) (cdr x))))
8579 org-refile-target-table))
8580 (completion-ignore-case t)
8581 pa answ parent-target child parent)
8582 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8583 nil 'org-refile-history))
8584 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8585 (if pa
8586 (progn
8587 (setcar org-refile-history (car pa))
8589 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8590 (setq parent (match-string 1 answ)
8591 child (match-string 2 answ))
8592 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8593 (when (and parent-target
8594 (or (eq new-nodes t)
8595 (and (eq new-nodes 'confirm)
8596 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8597 (org-refile-new-child parent-target child))))))
8599 (defun org-refile-new-child (parent-target child)
8600 "Use refile target PARENT-TARGET to add new CHILD below it."
8601 (unless parent-target
8602 (error "Cannot find parent for new node"))
8603 (let ((file (nth 1 parent-target))
8604 (pos (nth 3 parent-target))
8605 level)
8606 (with-current-buffer (or (find-buffer-visiting file)
8607 (find-file-noselect file))
8608 (save-excursion
8609 (save-restriction
8610 (widen)
8611 (if pos
8612 (goto-char pos)
8613 (goto-char (point-max))
8614 (if (not (bolp)) (newline)))
8615 (when (looking-at outline-regexp)
8616 (setq level (funcall outline-level))
8617 (org-end-of-subtree t t))
8618 (org-back-over-empty-lines)
8619 (insert "\n" (make-string
8620 (if pos (org-get-valid-level level 1) 1) ?*)
8621 " " child "\n")
8622 (beginning-of-line 0)
8623 (list (concat (car parent-target) "/" child) file "" (point)))))))
8625 (defun org-olpath-completing-read (prompt collection &rest args)
8626 "Read an outline path like a file name."
8627 (let ((thetable collection)
8628 (org-completion-use-ido nil)) ; does not work with ido.
8629 (apply
8630 'org-ido-completing-read prompt
8631 (lambda (string predicate &optional flag)
8632 (let (rtn r f (l (length string)))
8633 (cond
8634 ((eq flag nil)
8635 ;; try completion
8636 (try-completion string thetable))
8637 ((eq flag t)
8638 ;; all-completions
8639 (setq rtn (all-completions string thetable predicate))
8640 (mapcar
8641 (lambda (x)
8642 (setq r (substring x l))
8643 (if (string-match " ([^)]*)$" x)
8644 (setq f (match-string 0 x))
8645 (setq f ""))
8646 (if (string-match "/" r)
8647 (concat string (substring r 0 (match-end 0)) f)
8649 rtn))
8650 ((eq flag 'lambda)
8651 ;; exact match?
8652 (assoc string thetable)))
8654 args)))
8656 ;;;; Dynamic blocks
8658 (defun org-find-dblock (name)
8659 "Find the first dynamic block with name NAME in the buffer.
8660 If not found, stay at current position and return nil."
8661 (let (pos)
8662 (save-excursion
8663 (goto-char (point-min))
8664 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8665 nil t)
8666 (match-beginning 0))))
8667 (if pos (goto-char pos))
8668 pos))
8670 (defconst org-dblock-start-re
8671 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8672 "Matches the startline of a dynamic block, with parameters.")
8674 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8675 "Matches the end of a dynamic block.")
8677 (defun org-create-dblock (plist)
8678 "Create a dynamic block section, with parameters taken from PLIST.
8679 PLIST must contain a :name entry which is used as name of the block."
8680 (unless (bolp) (newline))
8681 (let ((name (plist-get plist :name)))
8682 (insert "#+BEGIN: " name)
8683 (while plist
8684 (if (eq (car plist) :name)
8685 (setq plist (cddr plist))
8686 (insert " " (prin1-to-string (pop plist)))))
8687 (insert "\n\n#+END:\n")
8688 (beginning-of-line -2)))
8690 (defun org-prepare-dblock ()
8691 "Prepare dynamic block for refresh.
8692 This empties the block, puts the cursor at the insert position and returns
8693 the property list including an extra property :name with the block name."
8694 (unless (looking-at org-dblock-start-re)
8695 (error "Not at a dynamic block"))
8696 (let* ((begdel (1+ (match-end 0)))
8697 (name (org-no-properties (match-string 1)))
8698 (params (append (list :name name)
8699 (read (concat "(" (match-string 3) ")")))))
8700 (unless (re-search-forward org-dblock-end-re nil t)
8701 (error "Dynamic block not terminated"))
8702 (setq params
8703 (append params
8704 (list :content (buffer-substring
8705 begdel (match-beginning 0)))))
8706 (delete-region begdel (match-beginning 0))
8707 (goto-char begdel)
8708 (open-line 1)
8709 params))
8711 (defun org-map-dblocks (&optional command)
8712 "Apply COMMAND to all dynamic blocks in the current buffer.
8713 If COMMAND is not given, use `org-update-dblock'."
8714 (let ((cmd (or command 'org-update-dblock))
8715 pos)
8716 (save-excursion
8717 (goto-char (point-min))
8718 (while (re-search-forward org-dblock-start-re nil t)
8719 (goto-char (setq pos (match-beginning 0)))
8720 (condition-case nil
8721 (funcall cmd)
8722 (error (message "Error during update of dynamic block")))
8723 (goto-char pos)
8724 (unless (re-search-forward org-dblock-end-re nil t)
8725 (error "Dynamic block not terminated"))))))
8727 (defun org-dblock-update (&optional arg)
8728 "User command for updating dynamic blocks.
8729 Update the dynamic block at point. With prefix ARG, update all dynamic
8730 blocks in the buffer."
8731 (interactive "P")
8732 (if arg
8733 (org-update-all-dblocks)
8734 (or (looking-at org-dblock-start-re)
8735 (org-beginning-of-dblock))
8736 (org-update-dblock)))
8738 (defun org-update-dblock ()
8739 "Update the dynamic block at point
8740 This means to empty the block, parse for parameters and then call
8741 the correct writing function."
8742 (save-window-excursion
8743 (let* ((pos (point))
8744 (line (org-current-line))
8745 (params (org-prepare-dblock))
8746 (name (plist-get params :name))
8747 (cmd (intern (concat "org-dblock-write:" name))))
8748 (message "Updating dynamic block `%s' at line %d..." name line)
8749 (funcall cmd params)
8750 (message "Updating dynamic block `%s' at line %d...done" name line)
8751 (goto-char pos))))
8753 (defun org-beginning-of-dblock ()
8754 "Find the beginning of the dynamic block at point.
8755 Error if there is no such block at point."
8756 (let ((pos (point))
8757 beg)
8758 (end-of-line 1)
8759 (if (and (re-search-backward org-dblock-start-re nil t)
8760 (setq beg (match-beginning 0))
8761 (re-search-forward org-dblock-end-re nil t)
8762 (> (match-end 0) pos))
8763 (goto-char beg)
8764 (goto-char pos)
8765 (error "Not in a dynamic block"))))
8767 (defun org-update-all-dblocks ()
8768 "Update all dynamic blocks in the buffer.
8769 This function can be used in a hook."
8770 (when (org-mode-p)
8771 (org-map-dblocks 'org-update-dblock)))
8774 ;;;; Completion
8776 (defconst org-additional-option-like-keywords
8777 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
8778 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
8779 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "ATTR_LaTeX"
8780 "BEGIN:" "END:"
8781 "ORGTBL" "TBLFM:" "TBLNAME:"
8782 "BEGIN_EXAMPLE" "END_EXAMPLE"
8783 "BEGIN_QUOTE" "END_QUOTE"
8784 "BEGIN_VERSE" "END_VERSE"
8785 "BEGIN_CENTER" "END_CENTER"
8786 "BEGIN_SRC" "END_SRC"
8787 "CATEGORY" "COLUMNS"
8788 "CAPTION" "LABEL"
8789 "BIND"))
8791 (defcustom org-structure-template-alist
8793 ("s" "#+begin_src ?\n\n#+end_src"
8794 "<src lang=\"?\">\n\n</src>")
8795 ("e" "#+begin_example\n?\n#+end_example"
8796 "<example>\n?\n</example>")
8797 ("q" "#+begin_quote\n?\n#+end_quote"
8798 "<quote>\n?\n</quote>")
8799 ("v" "#+begin_verse\n?\n#+end_verse"
8800 "<verse>\n?\n/verse>")
8801 ("c" "#+begin_center\n?\n#+end_center"
8802 "<center>\n?\n/center>")
8803 ("l" "#+begin_latex\n?\n#+end_latex"
8804 "<literal style=\"latex\">\n?\n</literal>")
8805 ("L" "#+latex: "
8806 "<literal style=\"latex\">?</literal>")
8807 ("h" "#+begin_html\n?\n#+end_html"
8808 "<literal style=\"html\">\n?\n</literal>")
8809 ("H" "#+html: "
8810 "<literal style=\"html\">?</literal>")
8811 ("a" "#+begin_ascii\n?\n#+end_ascii")
8812 ("A" "#+ascii: ")
8813 ("i" "#+include %file ?"
8814 "<include file=%file markup=\"?\">")
8816 "Structure completion elements.
8817 This is a list of abbreviation keys and values. The value gets inserted
8818 it you type @samp{.} followed by the key and then the completion key,
8819 usually `M-TAB'. %file will be replaced by a file name after prompting
8820 for the file using completion.
8821 There are two templates for each key, the first uses the original Org syntax,
8822 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8823 the default when the /org-mtags.el/ module has been loaded. See also the
8824 variable `org-mtags-prefer-muse-templates'.
8825 This is an experimental feature, it is undecided if it is going to stay in."
8826 :group 'org-completion
8827 :type '(repeat
8828 (string :tag "Key")
8829 (string :tag "Template")
8830 (string :tag "Muse Template")))
8832 (defun org-try-structure-completion ()
8833 "Try to complete a structure template before point.
8834 This looks for strings like \"<e\" on an otherwise empty line and
8835 expands them."
8836 (let ((l (buffer-substring (point-at-bol) (point)))
8838 (when (and (looking-at "[ \t]*$")
8839 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8840 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8841 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8842 (match-beginning 1)) a)
8843 t)))
8845 (defun org-complete-expand-structure-template (start cell)
8846 "Expand a structure template."
8847 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8848 (rpl (nth (if musep 2 1) cell))
8849 (ind ""))
8850 (delete-region start (point))
8851 (when (string-match "\\`#\\+" rpl)
8852 (cond
8853 ((bolp))
8854 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8855 (setq ind (buffer-substring (point-at-bol) (point))))
8856 (t (newline))))
8857 (setq start (point))
8858 (if (string-match "%file" rpl)
8859 (setq rpl (replace-match
8860 (concat
8861 "\""
8862 (save-match-data
8863 (abbreviate-file-name (read-file-name "Include file: ")))
8864 "\"")
8865 t t rpl)))
8866 (setq rpl (mapconcat 'identity (split-string rpl "\n")
8867 (concat "\n" ind)))
8868 (insert rpl)
8869 (if (re-search-backward "\\?" start t) (delete-char 1))))
8872 (defun org-complete (&optional arg)
8873 "Perform completion on word at point.
8874 At the beginning of a headline, this completes TODO keywords as given in
8875 `org-todo-keywords'.
8876 If the current word is preceded by a backslash, completes the TeX symbols
8877 that are supported for HTML support.
8878 If the current word is preceded by \"#+\", completes special words for
8879 setting file options.
8880 In the line after \"#+STARTUP:, complete valid keywords.\"
8881 At all other locations, this simply calls the value of
8882 `org-completion-fallback-command'."
8883 (interactive "P")
8884 (org-without-partial-completion
8885 (catch 'exit
8886 (let* ((a nil)
8887 (end (point))
8888 (beg1 (save-excursion
8889 (skip-chars-backward (org-re "[:alnum:]_@"))
8890 (point)))
8891 (beg (save-excursion
8892 (skip-chars-backward "a-zA-Z0-9_:$")
8893 (point)))
8894 (confirm (lambda (x) (stringp (car x))))
8895 (searchhead (equal (char-before beg) ?*))
8896 (struct
8897 (when (and (member (char-before beg1) '(?. ?<))
8898 (setq a (assoc (buffer-substring beg1 (point))
8899 org-structure-template-alist)))
8900 (org-complete-expand-structure-template (1- beg1) a)
8901 (throw 'exit t)))
8902 (tag (and (equal (char-before beg1) ?:)
8903 (equal (char-after (point-at-bol)) ?*)))
8904 (prop (and (equal (char-before beg1) ?:)
8905 (not (equal (char-after (point-at-bol)) ?*))))
8906 (texp (equal (char-before beg) ?\\))
8907 (link (equal (char-before beg) ?\[))
8908 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8909 beg)
8910 "#+"))
8911 (startup (string-match "^#\\+STARTUP:.*"
8912 (buffer-substring (point-at-bol) (point))))
8913 (completion-ignore-case opt)
8914 (type nil)
8915 (tbl nil)
8916 (table (cond
8917 (opt
8918 (setq type :opt)
8919 (require 'org-exp)
8920 (append
8921 (mapcar
8922 (lambda (x)
8923 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8924 (cons (match-string 2 x) (match-string 1 x)))
8925 (org-split-string (org-get-current-options) "\n"))
8926 (mapcar 'list org-additional-option-like-keywords)))
8927 (startup
8928 (setq type :startup)
8929 org-startup-options)
8930 (link (append org-link-abbrev-alist-local
8931 org-link-abbrev-alist))
8932 (texp
8933 (setq type :tex)
8934 org-html-entities)
8935 ((string-match "\\`\\*+[ \t]+\\'"
8936 (buffer-substring (point-at-bol) beg))
8937 (setq type :todo)
8938 (mapcar 'list org-todo-keywords-1))
8939 (searchhead
8940 (setq type :searchhead)
8941 (save-excursion
8942 (goto-char (point-min))
8943 (while (re-search-forward org-todo-line-regexp nil t)
8944 (push (list
8945 (org-make-org-heading-search-string
8946 (match-string 3) t))
8947 tbl)))
8948 tbl)
8949 (tag (setq type :tag beg beg1)
8950 (or org-tag-alist (org-get-buffer-tags)))
8951 (prop (setq type :prop beg beg1)
8952 (mapcar 'list (org-buffer-property-keys nil t t)))
8953 (t (progn
8954 (call-interactively org-completion-fallback-command)
8955 (throw 'exit nil)))))
8956 (pattern (buffer-substring-no-properties beg end))
8957 (completion (try-completion pattern table confirm)))
8958 (cond ((eq completion t)
8959 (if (not (assoc (upcase pattern) table))
8960 (message "Already complete")
8961 (if (and (equal type :opt)
8962 (not (member (car (assoc (upcase pattern) table))
8963 org-additional-option-like-keywords)))
8964 (insert (substring (cdr (assoc (upcase pattern) table))
8965 (length pattern)))
8966 (if (memq type '(:tag :prop)) (insert ":")))))
8967 ((null completion)
8968 (message "Can't find completion for \"%s\"" pattern)
8969 (ding))
8970 ((not (string= pattern completion))
8971 (delete-region beg end)
8972 (if (string-match " +$" completion)
8973 (setq completion (replace-match "" t t completion)))
8974 (insert completion)
8975 (if (get-buffer-window "*Completions*")
8976 (delete-window (get-buffer-window "*Completions*")))
8977 (if (assoc completion table)
8978 (if (eq type :todo) (insert " ")
8979 (if (memq type '(:tag :prop)) (insert ":"))))
8980 (if (and (equal type :opt) (assoc completion table))
8981 (message "%s" (substitute-command-keys
8982 "Press \\[org-complete] again to insert example settings"))))
8984 (message "Making completion list...")
8985 (let ((list (sort (all-completions pattern table confirm)
8986 'string<)))
8987 (with-output-to-temp-buffer "*Completions*"
8988 (condition-case nil
8989 ;; Protection needed for XEmacs and emacs 21
8990 (display-completion-list list pattern)
8991 (error (display-completion-list list)))))
8992 (message "Making completion list...%s" "done")))))))
8994 ;;;; TODO, DEADLINE, Comments
8996 (defun org-toggle-comment ()
8997 "Change the COMMENT state of an entry."
8998 (interactive)
8999 (save-excursion
9000 (org-back-to-heading)
9001 (let (case-fold-search)
9002 (if (looking-at (concat outline-regexp
9003 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9004 (replace-match "" t t nil 1)
9005 (if (looking-at outline-regexp)
9006 (progn
9007 (goto-char (match-end 0))
9008 (insert org-comment-string " ")))))))
9010 (defvar org-last-todo-state-is-todo nil
9011 "This is non-nil when the last TODO state change led to a TODO state.
9012 If the last change removed the TODO tag or switched to DONE, then
9013 this is nil.")
9015 (defvar org-setting-tags nil) ; dynamically skipped
9017 (defun org-parse-local-options (string var)
9018 "Parse STRING for startup setting relevant for variable VAR."
9019 (let ((rtn (symbol-value var))
9020 e opts)
9021 (save-match-data
9022 (if (or (not string) (not (string-match "\\S-" string)))
9024 (setq opts (delq nil (mapcar (lambda (x)
9025 (setq e (assoc x org-startup-options))
9026 (if (eq (nth 1 e) var) e nil))
9027 (org-split-string string "[ \t]+"))))
9028 (if (not opts)
9030 (setq rtn nil)
9031 (while (setq e (pop opts))
9032 (if (not (nth 3 e))
9033 (setq rtn (nth 2 e))
9034 (if (not (listp rtn)) (setq rtn nil))
9035 (push (nth 2 e) rtn)))
9036 rtn)))))
9038 (defvar org-todo-setup-filter-hook nil
9039 "Hook for functions that pre-filter todo specs.
9041 Each function takes a todo spec and returns either `nil' or the spec
9042 transformed into canonical form." )
9044 (defvar org-todo-get-default-hook nil
9045 "Hook for functions that get a default item for todo.
9047 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9048 `nil' or a string to be used for the todo mark." )
9050 (defvar org-agenda-headline-snapshot-before-repeat)
9052 (defun org-todo (&optional arg)
9053 "Change the TODO state of an item.
9054 The state of an item is given by a keyword at the start of the heading,
9055 like
9056 *** TODO Write paper
9057 *** DONE Call mom
9059 The different keywords are specified in the variable `org-todo-keywords'.
9060 By default the available states are \"TODO\" and \"DONE\".
9061 So for this example: when the item starts with TODO, it is changed to DONE.
9062 When it starts with DONE, the DONE is removed. And when neither TODO nor
9063 DONE are present, add TODO at the beginning of the heading.
9065 With C-u prefix arg, use completion to determine the new state.
9066 With numeric prefix arg, switch to that state.
9067 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9068 With a tripple C-u prefix, circumvent any state blocking.
9070 For calling through lisp, arg is also interpreted in the following way:
9071 'none -> empty state
9072 \"\"(empty string) -> switch to empty state
9073 'done -> switch to DONE
9074 'nextset -> switch to the next set of keywords
9075 'previousset -> switch to the previous set of keywords
9076 \"WAITING\" -> switch to the specified keyword, but only if it
9077 really is a member of `org-todo-keywords'."
9078 (interactive "P")
9079 (if (equal arg '(16)) (setq arg 'nextset))
9080 (let ((org-blocker-hook org-blocker-hook)
9081 (case-fold-search nil))
9082 (when (equal arg '(64))
9083 (setq arg nil org-blocker-hook nil))
9084 (when (and org-blocker-hook
9085 (or org-inhibit-blocking
9086 (org-entry-get nil "NOBLOCKING")))
9087 (setq org-blocker-hook nil))
9088 (save-excursion
9089 (catch 'exit
9090 (org-back-to-heading)
9091 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9092 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9093 (looking-at " *"))
9094 (let* ((match-data (match-data))
9095 (startpos (point-at-bol))
9096 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9097 (org-log-done org-log-done)
9098 (org-log-repeat org-log-repeat)
9099 (org-todo-log-states org-todo-log-states)
9100 (this (match-string 1))
9101 (hl-pos (match-beginning 0))
9102 (head (org-get-todo-sequence-head this))
9103 (ass (assoc head org-todo-kwd-alist))
9104 (interpret (nth 1 ass))
9105 (done-word (nth 3 ass))
9106 (final-done-word (nth 4 ass))
9107 (last-state (or this ""))
9108 (completion-ignore-case t)
9109 (member (member this org-todo-keywords-1))
9110 (tail (cdr member))
9111 (state (cond
9112 ((and org-todo-key-trigger
9113 (or (and (equal arg '(4))
9114 (eq org-use-fast-todo-selection 'prefix))
9115 (and (not arg) org-use-fast-todo-selection
9116 (not (eq org-use-fast-todo-selection
9117 'prefix)))))
9118 ;; Use fast selection
9119 (org-fast-todo-selection))
9120 ((and (equal arg '(4))
9121 (or (not org-use-fast-todo-selection)
9122 (not org-todo-key-trigger)))
9123 ;; Read a state with completion
9124 (org-ido-completing-read
9125 "State: " (mapcar (lambda(x) (list x))
9126 org-todo-keywords-1)
9127 nil t))
9128 ((eq arg 'right)
9129 (if this
9130 (if tail (car tail) nil)
9131 (car org-todo-keywords-1)))
9132 ((eq arg 'left)
9133 (if (equal member org-todo-keywords-1)
9135 (if this
9136 (nth (- (length org-todo-keywords-1)
9137 (length tail) 2)
9138 org-todo-keywords-1)
9139 (org-last org-todo-keywords-1))))
9140 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9141 (setq arg nil))) ; hack to fall back to cycling
9142 (arg
9143 ;; user or caller requests a specific state
9144 (cond
9145 ((equal arg "") nil)
9146 ((eq arg 'none) nil)
9147 ((eq arg 'done) (or done-word (car org-done-keywords)))
9148 ((eq arg 'nextset)
9149 (or (car (cdr (member head org-todo-heads)))
9150 (car org-todo-heads)))
9151 ((eq arg 'previousset)
9152 (let ((org-todo-heads (reverse org-todo-heads)))
9153 (or (car (cdr (member head org-todo-heads)))
9154 (car org-todo-heads))))
9155 ((car (member arg org-todo-keywords-1)))
9156 ((nth (1- (prefix-numeric-value arg))
9157 org-todo-keywords-1))))
9158 ((null member) (or head (car org-todo-keywords-1)))
9159 ((equal this final-done-word) nil) ;; -> make empty
9160 ((null tail) nil) ;; -> first entry
9161 ((memq interpret '(type priority))
9162 (if (eq this-command last-command)
9163 (car tail)
9164 (if (> (length tail) 0)
9165 (or done-word (car org-done-keywords))
9166 nil)))
9168 (car tail))))
9169 (state (or
9170 (run-hook-with-args-until-success
9171 'org-todo-get-default-hook state last-state)
9172 state))
9173 (next (if state (concat " " state " ") " "))
9174 (change-plist (list :type 'todo-state-change :from this :to state
9175 :position startpos))
9176 dolog now-done-p)
9177 (when org-blocker-hook
9178 (setq org-last-todo-state-is-todo
9179 (not (member this org-done-keywords)))
9180 (unless (save-excursion
9181 (save-match-data
9182 (run-hook-with-args-until-failure
9183 'org-blocker-hook change-plist)))
9184 (if (interactive-p)
9185 (error "TODO state change from %s to %s blocked" this state)
9186 ;; fail silently
9187 (message "TODO state change from %s to %s blocked" this state)
9188 (throw 'exit nil))))
9189 (store-match-data match-data)
9190 (replace-match next t t)
9191 (unless (pos-visible-in-window-p hl-pos)
9192 (message "TODO state changed to %s" (org-trim next)))
9193 (unless head
9194 (setq head (org-get-todo-sequence-head state)
9195 ass (assoc head org-todo-kwd-alist)
9196 interpret (nth 1 ass)
9197 done-word (nth 3 ass)
9198 final-done-word (nth 4 ass)))
9199 (when (memq arg '(nextset previousset))
9200 (message "Keyword-Set %d/%d: %s"
9201 (- (length org-todo-sets) -1
9202 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9203 (length org-todo-sets)
9204 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9205 (setq org-last-todo-state-is-todo
9206 (not (member state org-done-keywords)))
9207 (setq now-done-p (and (member state org-done-keywords)
9208 (not (member this org-done-keywords))))
9209 (and logging (org-local-logging logging))
9210 (when (and (or org-todo-log-states org-log-done)
9211 (not (eq org-inhibit-logging t))
9212 (not (memq arg '(nextset previousset))))
9213 ;; we need to look at recording a time and note
9214 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9215 (nth 2 (assoc this org-todo-log-states))))
9216 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9217 (setq dolog 'time))
9218 (when (and state
9219 (member state org-not-done-keywords)
9220 (not (member this org-not-done-keywords)))
9221 ;; This is now a todo state and was not one before
9222 ;; If there was a CLOSED time stamp, get rid of it.
9223 (org-add-planning-info nil nil 'closed))
9224 (when (and now-done-p org-log-done)
9225 ;; It is now done, and it was not done before
9226 (org-add-planning-info 'closed (org-current-time))
9227 (if (and (not dolog) (eq 'note org-log-done))
9228 (org-add-log-setup 'done state this 'findpos 'note)))
9229 (when (and state dolog)
9230 ;; This is a non-nil state, and we need to log it
9231 (org-add-log-setup 'state state this 'findpos dolog)))
9232 ;; Fixup tag positioning
9233 (org-todo-trigger-tag-changes state)
9234 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9235 (when org-provide-todo-statistics
9236 (org-update-parent-todo-statistics))
9237 (run-hooks 'org-after-todo-state-change-hook)
9238 (if (and arg (not (member state org-done-keywords)))
9239 (setq head (org-get-todo-sequence-head state)))
9240 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9241 ;; Do we need to trigger a repeat?
9242 (when now-done-p
9243 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9244 ;; This is for the agenda, take a snapshot of the headline.
9245 (save-match-data
9246 (setq org-agenda-headline-snapshot-before-repeat
9247 (org-get-heading))))
9248 (org-auto-repeat-maybe state))
9249 ;; Fixup cursor location if close to the keyword
9250 (if (and (outline-on-heading-p)
9251 (not (bolp))
9252 (save-excursion (beginning-of-line 1)
9253 (looking-at org-todo-line-regexp))
9254 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9255 (progn
9256 (goto-char (or (match-end 2) (match-end 1)))
9257 (and (looking-at " ") (just-one-space))))
9258 (when org-trigger-hook
9259 (save-excursion
9260 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9262 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9263 "Block turning an entry into a TODO, using the hierarchy.
9264 This checks whether the current task should be blocked from state
9265 changes. Such blocking occurs when:
9267 1. The task has children which are not all in a completed state.
9269 2. A task has a parent with the property :ORDERED:, and there
9270 are siblings prior to the current task with incomplete
9271 status.
9273 3. The parent of the task is blocked because it has siblings that should
9274 be done first, or is child of a block grandparent TODO entry."
9276 (catch 'dont-block
9277 ;; If this is not a todo state change, or if this entry is already DONE,
9278 ;; do not block
9279 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9280 (member (plist-get change-plist :from)
9281 (cons 'done org-done-keywords))
9282 (member (plist-get change-plist :to)
9283 (cons 'todo org-not-done-keywords)))
9284 (throw 'dont-block t))
9285 ;; If this task has children, and any are undone, it's blocked
9286 (save-excursion
9287 (org-back-to-heading t)
9288 (let ((this-level (funcall outline-level)))
9289 (outline-next-heading)
9290 (let ((child-level (funcall outline-level)))
9291 (while (and (not (eobp))
9292 (> child-level this-level))
9293 ;; this todo has children, check whether they are all
9294 ;; completed
9295 (if (and (not (org-entry-is-done-p))
9296 (org-entry-is-todo-p))
9297 (throw 'dont-block nil))
9298 (outline-next-heading)
9299 (setq child-level (funcall outline-level))))))
9300 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9301 ;; any previous siblings are undone, it's blocked
9302 (save-excursion
9303 (org-back-to-heading t)
9304 (let* ((pos (point))
9305 (parent-pos (and (org-up-heading-safe) (point))))
9306 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9307 (when (and (org-entry-get (point) "ORDERED")
9308 (forward-line 1)
9309 (re-search-forward org-not-done-heading-regexp pos t))
9310 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9311 ;; Search further up the hierarchy, to see if an anchestor is blocked
9312 (while t
9313 (goto-char parent-pos)
9314 (if (not (looking-at org-not-done-heading-regexp))
9315 (throw 'dont-block t)) ; do not block, parent is not a TODO
9316 (setq pos (point))
9317 (setq parent-pos (and (org-up-heading-safe) (point)))
9318 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9319 (when (and (org-entry-get (point) "ORDERED")
9320 (forward-line 1)
9321 (re-search-forward org-not-done-heading-regexp pos t))
9322 (throw 'dont-block nil))))))) ; block, older sibling not done.
9324 (defcustom org-track-ordered-property-with-tag nil
9325 "Should the ORDERED property also be shown as a tag?
9326 The ORDERED property decides if an entry should require subtasks to be
9327 completed in sequence. Since a property is not very visible, setting
9328 this option means that toggling the ORDERED property with the command
9329 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9330 not relevant for the behavior, but it makes things more visible.
9332 Note that toggling the tag with tags commands will not change the property
9333 and therefore not influence behavior!
9335 This can be t, meaning the tag ORDERED should be used, It can also be a
9336 string to select a different tag for this task."
9337 :group 'org-todo
9338 :type '(choice
9339 (const :tag "No tracking" nil)
9340 (const :tag "Track with ORDERED tag" t)
9341 (string :tag "Use other tag")))
9343 (defun org-toggle-ordered-property ()
9344 "Toggle the ORDERED property of the current entry.
9345 For better visibility, you can track the value of this property with a tag.
9346 See variable `org-track-ordered-property-with-tag'."
9347 (interactive)
9348 (let* ((t1 org-track-ordered-property-with-tag)
9349 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9350 (save-excursion
9351 (org-back-to-heading)
9352 (if (org-entry-get nil "ORDERED")
9353 (progn
9354 (org-delete-property "ORDERED")
9355 (and tag (org-toggle-tag tag 'off))
9356 (message "Subtasks can be completed in arbitrary order"))
9357 (org-entry-put nil "ORDERED" "t")
9358 (and tag (org-toggle-tag tag 'on))
9359 (message "Subtasks must be completed in sequence")))))
9361 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9362 (defun org-block-todo-from-checkboxes (change-plist)
9363 "Block turning an entry into a TODO, using checkboxes.
9364 This checks whether the current task should be blocked from state
9365 changes because there are uncheckd boxes in this entry."
9366 (catch 'dont-block
9367 ;; If this is not a todo state change, or if this entry is already DONE,
9368 ;; do not block
9369 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9370 (member (plist-get change-plist :from)
9371 (cons 'done org-done-keywords))
9372 (member (plist-get change-plist :to)
9373 (cons 'todo org-not-done-keywords)))
9374 (throw 'dont-block t))
9375 ;; If this task has checkboxes that are not checked, it's blocked
9376 (save-excursion
9377 (org-back-to-heading t)
9378 (let ((beg (point)) end)
9379 (outline-next-heading)
9380 (setq end (point))
9381 (goto-char beg)
9382 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9383 end t)
9384 (progn
9385 (if (boundp 'org-blocked-by-checkboxes)
9386 (setq org-blocked-by-checkboxes t))
9387 (throw 'dont-block nil)))))
9388 t)) ; do not block
9390 (defvar org-entry-property-inherited-from) ;; defined below
9391 (defun org-update-parent-todo-statistics ()
9392 "Update any statistics cookie in the parent of the current headline.
9393 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9394 the entire subtree and this will travel up the hierarchy and update
9395 statistics everywhere."
9396 (interactive)
9397 (let* ((lim 0) prop
9398 (recursive (or (not org-hierarchical-todo-statistics)
9399 (string-match
9400 "\\<recursive\\>"
9401 (or (setq prop (org-entry-get
9402 nil "COOKIE_DATA" 'inherit)) ""))))
9403 (lim (or (and prop (marker-position
9404 org-entry-property-inherited-from))
9405 lim))
9406 (first t)
9407 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9408 level ltoggle l1
9409 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9410 (catch 'exit
9411 (save-excursion
9412 (beginning-of-line 1)
9413 (if (org-at-heading-p)
9414 (setq ltoggle (funcall outline-level))
9415 (error "This should not happen"))
9416 (while (and (setq level (org-up-heading-safe))
9417 (or recursive first)
9418 (>= (point) lim))
9419 (setq first nil)
9420 (unless (and level
9421 (not (string-match
9422 "\\<checkbox\\>"
9423 (downcase
9424 (or (org-entry-get
9425 nil "COOKIE_DATA")
9426 "")))))
9427 (throw 'exit nil))
9428 (while (re-search-forward box-re (point-at-eol) t)
9429 (setq cnt-all 0 cnt-done 0 cookie-present t)
9430 (setq is-percent (match-end 2))
9431 (save-match-data
9432 (unless (outline-next-heading) (throw 'exit nil))
9433 (while (and (looking-at org-complex-heading-regexp)
9434 (> (setq l1 (length (match-string 1))) level))
9435 (setq kwd (and (or recursive (= l1 ltoggle))
9436 (match-string 2)))
9437 (and kwd (setq cnt-all (1+ cnt-all)))
9438 (and (member kwd org-done-keywords)
9439 (setq cnt-done (1+ cnt-done)))
9440 (outline-next-heading)))
9441 (replace-match
9442 (if is-percent
9443 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9444 (format "[%d/%d]" cnt-done cnt-all)))))
9445 (when cookie-present
9446 (run-hook-with-args 'org-after-todo-statistics-hook
9447 cnt-done (- cnt-all cnt-done)))))
9448 (run-hooks 'org-todo-statistics-hook)))
9450 (defvar org-after-todo-statistics-hook nil
9451 "Hook that is called after a TODO statistics cookie has been updated.
9452 Each function is called with two arguments: the number of not-done entries
9453 and the number of done entries.
9455 For example, the following function, when added to this hook, will switch
9456 an entry to DONE when all children are done, and back to TODO when new
9457 entries are set to a TODO status. Note that this hook is only called
9458 when there is a statistics cookie in the headline!
9460 (defun org-summary-todo (n-done n-not-done)
9461 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9462 (let (org-log-done org-log-states) ; turn off logging
9463 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9466 (defvar org-todo-statistics-hook nil
9467 "Hook that is run whenever Org thinks TODO statistics should be updated.
9468 This hook runs even if there is no statisics cookie present, in which case
9469 `org-after-todo-statistics-hook' would not run.")
9471 (defun org-todo-trigger-tag-changes (state)
9472 "Apply the changes defined in `org-todo-state-tags-triggers'."
9473 (let ((l org-todo-state-tags-triggers)
9474 changes)
9475 (when (or (not state) (equal state ""))
9476 (setq changes (append changes (cdr (assoc "" l)))))
9477 (when (and (stringp state) (> (length state) 0))
9478 (setq changes (append changes (cdr (assoc state l)))))
9479 (when (member state org-not-done-keywords)
9480 (setq changes (append changes (cdr (assoc 'todo l)))))
9481 (when (member state org-done-keywords)
9482 (setq changes (append changes (cdr (assoc 'done l)))))
9483 (dolist (c changes)
9484 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9486 (defun org-local-logging (value)
9487 "Get logging settings from a property VALUE."
9488 (let* (words w a)
9489 ;; directly set the variables, they are already local.
9490 (setq org-log-done nil
9491 org-log-repeat nil
9492 org-todo-log-states nil)
9493 (setq words (org-split-string value))
9494 (while (setq w (pop words))
9495 (cond
9496 ((setq a (assoc w org-startup-options))
9497 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9498 (set (nth 1 a) (nth 2 a))))
9499 ((setq a (org-extract-log-state-settings w))
9500 (and (member (car a) org-todo-keywords-1)
9501 (push a org-todo-log-states)))))))
9503 (defun org-get-todo-sequence-head (kwd)
9504 "Return the head of the TODO sequence to which KWD belongs.
9505 If KWD is not set, check if there is a text property remembering the
9506 right sequence."
9507 (let (p)
9508 (cond
9509 ((not kwd)
9510 (or (get-text-property (point-at-bol) 'org-todo-head)
9511 (progn
9512 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9513 nil (point-at-eol)))
9514 (get-text-property p 'org-todo-head))))
9515 ((not (member kwd org-todo-keywords-1))
9516 (car org-todo-keywords-1))
9517 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9519 (defun org-fast-todo-selection ()
9520 "Fast TODO keyword selection with single keys.
9521 Returns the new TODO keyword, or nil if no state change should occur."
9522 (let* ((fulltable org-todo-key-alist)
9523 (done-keywords org-done-keywords) ;; needed for the faces.
9524 (maxlen (apply 'max (mapcar
9525 (lambda (x)
9526 (if (stringp (car x)) (string-width (car x)) 0))
9527 fulltable)))
9528 (expert nil)
9529 (fwidth (+ maxlen 3 1 3))
9530 (ncol (/ (- (window-width) 4) fwidth))
9531 tg cnt e c tbl
9532 groups ingroup)
9533 (save-excursion
9534 (save-window-excursion
9535 (if expert
9536 (set-buffer (get-buffer-create " *Org todo*"))
9537 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9538 (erase-buffer)
9539 (org-set-local 'org-done-keywords done-keywords)
9540 (setq tbl fulltable cnt 0)
9541 (while (setq e (pop tbl))
9542 (cond
9543 ((equal e '(:startgroup))
9544 (push '() groups) (setq ingroup t)
9545 (when (not (= cnt 0))
9546 (setq cnt 0)
9547 (insert "\n"))
9548 (insert "{ "))
9549 ((equal e '(:endgroup))
9550 (setq ingroup nil cnt 0)
9551 (insert "}\n"))
9552 ((equal e '(:newline))
9553 (when (not (= cnt 0))
9554 (setq cnt 0)
9555 (insert "\n")
9556 (setq e (car tbl))
9557 (while (equal (car tbl) '(:newline))
9558 (insert "\n")
9559 (setq tbl (cdr tbl)))))
9561 (setq tg (car e) c (cdr e))
9562 (if ingroup (push tg (car groups)))
9563 (setq tg (org-add-props tg nil 'face
9564 (org-get-todo-face tg)))
9565 (if (and (= cnt 0) (not ingroup)) (insert " "))
9566 (insert "[" c "] " tg (make-string
9567 (- fwidth 4 (length tg)) ?\ ))
9568 (when (= (setq cnt (1+ cnt)) ncol)
9569 (insert "\n")
9570 (if ingroup (insert " "))
9571 (setq cnt 0)))))
9572 (insert "\n")
9573 (goto-char (point-min))
9574 (if (not expert) (org-fit-window-to-buffer))
9575 (message "[a-z..]:Set [SPC]:clear")
9576 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9577 (cond
9578 ((or (= c ?\C-g)
9579 (and (= c ?q) (not (rassoc c fulltable))))
9580 (setq quit-flag t))
9581 ((= c ?\ ) nil)
9582 ((setq e (rassoc c fulltable) tg (car e))
9584 (t (setq quit-flag t)))))))
9586 (defun org-entry-is-todo-p ()
9587 (member (org-get-todo-state) org-not-done-keywords))
9589 (defun org-entry-is-done-p ()
9590 (member (org-get-todo-state) org-done-keywords))
9592 (defun org-get-todo-state ()
9593 (save-excursion
9594 (org-back-to-heading t)
9595 (and (looking-at org-todo-line-regexp)
9596 (match-end 2)
9597 (match-string 2))))
9599 (defun org-at-date-range-p (&optional inactive-ok)
9600 "Is the cursor inside a date range?"
9601 (interactive)
9602 (save-excursion
9603 (catch 'exit
9604 (let ((pos (point)))
9605 (skip-chars-backward "^[<\r\n")
9606 (skip-chars-backward "<[")
9607 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9608 (>= (match-end 0) pos)
9609 (throw 'exit t))
9610 (skip-chars-backward "^<[\r\n")
9611 (skip-chars-backward "<[")
9612 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9613 (>= (match-end 0) pos)
9614 (throw 'exit t)))
9615 nil)))
9617 (defun org-get-repeat ()
9618 "Check if there is a deadline/schedule with repeater in this entry."
9619 (save-match-data
9620 (save-excursion
9621 (org-back-to-heading t)
9622 (if (re-search-forward
9623 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9624 (match-string 1)))))
9626 (defvar org-last-changed-timestamp)
9627 (defvar org-last-inserted-timestamp)
9628 (defvar org-log-post-message)
9629 (defvar org-log-note-purpose)
9630 (defvar org-log-note-how)
9631 (defvar org-log-note-extra)
9632 (defun org-auto-repeat-maybe (done-word)
9633 "Check if the current headline contains a repeated deadline/schedule.
9634 If yes, set TODO state back to what it was and change the base date
9635 of repeating deadline/scheduled time stamps to new date.
9636 This function is run automatically after each state change to a DONE state."
9637 ;; last-state is dynamically scoped into this function
9638 (let* ((repeat (org-get-repeat))
9639 (aa (assoc last-state org-todo-kwd-alist))
9640 (interpret (nth 1 aa))
9641 (head (nth 2 aa))
9642 (whata '(("d" . day) ("m" . month) ("y" . year)))
9643 (msg "Entry repeats: ")
9644 (org-log-done nil)
9645 (org-todo-log-states nil)
9646 (nshiftmax 10) (nshift 0)
9647 re type n what ts time)
9648 (when repeat
9649 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9650 (org-todo (if (eq interpret 'type) last-state head))
9651 (org-entry-put nil "LAST_REPEAT" (format-time-string
9652 (org-time-stamp-format t t)))
9653 (when org-log-repeat
9654 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9655 (memq 'org-add-log-note post-command-hook))
9656 ;; OK, we are already setup for some record
9657 (if (eq org-log-repeat 'note)
9658 ;; make sure we take a note, not only a time stamp
9659 (setq org-log-note-how 'note))
9660 ;; Set up for taking a record
9661 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9662 last-state
9663 'findpos org-log-repeat)))
9664 (org-back-to-heading t)
9665 (org-add-planning-info nil nil 'closed)
9666 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9667 org-deadline-time-regexp "\\)\\|\\("
9668 org-ts-regexp "\\)"))
9669 (while (re-search-forward
9670 re (save-excursion (outline-next-heading) (point)) t)
9671 (setq type (if (match-end 1) org-scheduled-string
9672 (if (match-end 3) org-deadline-string "Plain:"))
9673 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9674 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9675 (setq n (string-to-number (match-string 2 ts))
9676 what (match-string 3 ts))
9677 (if (equal what "w") (setq n (* n 7) what "d"))
9678 ;; Preparation, see if we need to modify the start date for the change
9679 (when (match-end 1)
9680 (setq time (save-match-data (org-time-string-to-time ts)))
9681 (cond
9682 ((equal (match-string 1 ts) ".")
9683 ;; Shift starting date to today
9684 (org-timestamp-change
9685 (- (time-to-days (current-time)) (time-to-days time))
9686 'day))
9687 ((equal (match-string 1 ts) "+")
9688 (while (or (= nshift 0)
9689 (<= (time-to-days time) (time-to-days (current-time))))
9690 (when (= (incf nshift) nshiftmax)
9691 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9692 (error "Abort")))
9693 (org-timestamp-change n (cdr (assoc what whata)))
9694 (org-at-timestamp-p t)
9695 (setq ts (match-string 1))
9696 (setq time (save-match-data (org-time-string-to-time ts))))
9697 (org-timestamp-change (- n) (cdr (assoc what whata)))
9698 ;; rematch, so that we have everything in place for the real shift
9699 (org-at-timestamp-p t)
9700 (setq ts (match-string 1))
9701 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9702 (org-timestamp-change n (cdr (assoc what whata)))
9703 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9704 (setq org-log-post-message msg)
9705 (message "%s" msg))))
9707 (defun org-show-todo-tree (arg)
9708 "Make a compact tree which shows all headlines marked with TODO.
9709 The tree will show the lines where the regexp matches, and all higher
9710 headlines above the match.
9711 With a \\[universal-argument] prefix, prompt for a regexp to match.
9712 With a numeric prefix N, construct a sparse tree for the Nth element
9713 of `org-todo-keywords-1'."
9714 (interactive "P")
9715 (let ((case-fold-search nil)
9716 (kwd-re
9717 (cond ((null arg) org-not-done-regexp)
9718 ((equal arg '(4))
9719 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9720 (mapcar 'list org-todo-keywords-1))))
9721 (concat "\\("
9722 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9723 "\\)\\>")))
9724 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9725 (regexp-quote (nth (1- (prefix-numeric-value arg))
9726 org-todo-keywords-1)))
9727 (t (error "Invalid prefix argument: %s" arg)))))
9728 (message "%d TODO entries found"
9729 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9731 (defun org-deadline (&optional remove time)
9732 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9733 With argument REMOVE, remove any deadline from the item.
9734 When TIME is set, it should be an internal time specification, and the
9735 scheduling will use the corresponding date."
9736 (interactive "P")
9737 (if remove
9738 (progn
9739 (org-remove-timestamp-with-keyword org-deadline-string)
9740 (message "Item no longer has a deadline."))
9741 (if (org-get-repeat)
9742 (error "Cannot change deadline on task with repeater, please do that by hand")
9743 (org-add-planning-info 'deadline time 'closed)
9744 (message "Deadline on %s" org-last-inserted-timestamp))))
9746 (defun org-schedule (&optional remove time)
9747 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9748 With argument REMOVE, remove any scheduling date from the item.
9749 When TIME is set, it should be an internal time specification, and the
9750 scheduling will use the corresponding date."
9751 (interactive "P")
9752 (if remove
9753 (progn
9754 (org-remove-timestamp-with-keyword org-scheduled-string)
9755 (message "Item is no longer scheduled."))
9756 (if (org-get-repeat)
9757 (error "Cannot reschedule task with repeater, please do that by hand")
9758 (org-add-planning-info 'scheduled time 'closed)
9759 (message "Scheduled to %s" org-last-inserted-timestamp))))
9761 (defun org-get-scheduled-time (pom &optional inherit)
9762 "Get the scheduled time as a time tuple, of a format suitable
9763 for calling org-schedule with, or if there is no scheduling,
9764 returns nil."
9765 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9766 (when time
9767 (apply 'encode-time (org-parse-time-string time)))))
9769 (defun org-get-deadline-time (pom &optional inherit)
9770 "Get the deadine as a time tuple, of a format suitable for
9771 calling org-deadlin with, or if there is no scheduling, returns
9772 nil."
9773 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9774 (when time
9775 (apply 'encode-time (org-parse-time-string time)))))
9777 (defun org-remove-timestamp-with-keyword (keyword)
9778 "Remove all time stamps with KEYWORD in the current entry."
9779 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9780 beg)
9781 (save-excursion
9782 (org-back-to-heading t)
9783 (setq beg (point))
9784 (org-end-of-subtree t t)
9785 (while (re-search-backward re beg t)
9786 (replace-match "")
9787 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9788 (equal (char-before) ?\ ))
9789 (backward-delete-char 1)
9790 (if (string-match "^[ \t]*$" (buffer-substring
9791 (point-at-bol) (point-at-eol)))
9792 (delete-region (point-at-bol)
9793 (min (point-max) (1+ (point-at-eol))))))))))
9795 (defun org-add-planning-info (what &optional time &rest remove)
9796 "Insert new timestamp with keyword in the line directly after the headline.
9797 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9798 If non is given, the user is prompted for a date.
9799 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9800 be removed."
9801 (interactive)
9802 (let (org-time-was-given org-end-time-was-given ts
9803 end default-time default-input)
9805 (catch 'exit
9806 (when (and (not time) (memq what '(scheduled deadline)))
9807 ;; Try to get a default date/time from existing timestamp
9808 (save-excursion
9809 (org-back-to-heading t)
9810 (setq end (save-excursion (outline-next-heading) (point)))
9811 (when (re-search-forward (if (eq what 'scheduled)
9812 org-scheduled-time-regexp
9813 org-deadline-time-regexp)
9814 end t)
9815 (setq ts (match-string 1)
9816 default-time
9817 (apply 'encode-time (org-parse-time-string ts))
9818 default-input (and ts (org-get-compact-tod ts))))))
9819 (when what
9820 ;; If necessary, get the time from the user
9821 (setq time (or time (org-read-date nil 'to-time nil nil
9822 default-time default-input))))
9824 (when (and org-insert-labeled-timestamps-at-point
9825 (member what '(scheduled deadline)))
9826 (insert
9827 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9828 (org-insert-time-stamp time org-time-was-given
9829 nil nil nil (list org-end-time-was-given))
9830 (setq what nil))
9831 (save-excursion
9832 (save-restriction
9833 (let (col list elt ts buffer-invisibility-spec)
9834 (org-back-to-heading t)
9835 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9836 (goto-char (match-end 1))
9837 (setq col (current-column))
9838 (goto-char (match-end 0))
9839 (if (eobp) (insert "\n") (forward-char 1))
9840 (when (and (not what)
9841 (not (looking-at
9842 (concat "[ \t]*"
9843 org-keyword-time-not-clock-regexp))))
9844 ;; Nothing to add, nothing to remove...... :-)
9845 (throw 'exit nil))
9846 (if (and (not (looking-at outline-regexp))
9847 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9848 "[^\r\n]*"))
9849 (not (equal (match-string 1) org-clock-string)))
9850 (narrow-to-region (match-beginning 0) (match-end 0))
9851 (insert-before-markers "\n")
9852 (backward-char 1)
9853 (narrow-to-region (point) (point))
9854 (and org-adapt-indentation (org-indent-to-column col)))
9855 ;; Check if we have to remove something.
9856 (setq list (cons what remove))
9857 (while list
9858 (setq elt (pop list))
9859 (goto-char (point-min))
9860 (when (or (and (eq elt 'scheduled)
9861 (re-search-forward org-scheduled-time-regexp nil t))
9862 (and (eq elt 'deadline)
9863 (re-search-forward org-deadline-time-regexp nil t))
9864 (and (eq elt 'closed)
9865 (re-search-forward org-closed-time-regexp nil t)))
9866 (replace-match "")
9867 (if (looking-at "--+<[^>]+>") (replace-match ""))
9868 (if (looking-at " +") (replace-match ""))))
9869 (goto-char (point-max))
9870 (when what
9871 (insert
9872 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9873 (cond ((eq what 'scheduled) org-scheduled-string)
9874 ((eq what 'deadline) org-deadline-string)
9875 ((eq what 'closed) org-closed-string))
9876 " ")
9877 (setq ts (org-insert-time-stamp
9878 time
9879 (or org-time-was-given
9880 (and (eq what 'closed) org-log-done-with-time))
9881 (eq what 'closed)
9882 nil nil (list org-end-time-was-given)))
9883 (end-of-line 1))
9884 (goto-char (point-min))
9885 (widen)
9886 (if (and (looking-at "[ \t]+\n")
9887 (equal (char-before) ?\n))
9888 (delete-region (1- (point)) (point-at-eol)))
9889 ts))))))
9891 (defvar org-log-note-marker (make-marker))
9892 (defvar org-log-note-purpose nil)
9893 (defvar org-log-note-state nil)
9894 (defvar org-log-note-previous-state nil)
9895 (defvar org-log-note-how nil)
9896 (defvar org-log-note-extra nil)
9897 (defvar org-log-note-window-configuration nil)
9898 (defvar org-log-note-return-to (make-marker))
9899 (defvar org-log-post-message nil
9900 "Message to be displayed after a log note has been stored.
9901 The auto-repeater uses this.")
9903 (defun org-add-note ()
9904 "Add a note to the current entry.
9905 This is done in the same way as adding a state change note."
9906 (interactive)
9907 (org-add-log-setup 'note nil nil 'findpos nil))
9909 (defvar org-property-end-re)
9910 (defun org-add-log-setup (&optional purpose state prev-state
9911 findpos how &optional extra)
9912 "Set up the post command hook to take a note.
9913 If this is about to TODO state change, the new state is expected in STATE.
9914 When FINDPOS is non-nil, find the correct position for the note in
9915 the current entry. If not, assume that it can be inserted at point.
9916 HOW is an indicator what kind of note should be created.
9917 EXTRA is additional text that will be inserted into the notes buffer."
9918 (let* ((org-log-into-drawer (org-log-into-drawer))
9919 (drawer (cond ((stringp org-log-into-drawer)
9920 org-log-into-drawer)
9921 (org-log-into-drawer "LOGBOOK")
9922 (t nil))))
9923 (save-restriction
9924 (save-excursion
9925 (when findpos
9926 (org-back-to-heading t)
9927 (narrow-to-region (point) (save-excursion
9928 (outline-next-heading) (point)))
9929 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9930 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9931 "[^\r\n]*\\)?"))
9932 (goto-char (match-end 0))
9933 (cond
9934 (drawer
9935 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9936 nil t)
9937 (progn
9938 (goto-char (match-end 0))
9939 (or org-log-states-order-reversed
9940 (and (re-search-forward org-property-end-re nil t)
9941 (goto-char (1- (match-beginning 0))))))
9942 (insert "\n:" drawer ":\n:END:")
9943 (beginning-of-line 0)
9944 (org-indent-line-function)
9945 (beginning-of-line 2)
9946 (org-indent-line-function)
9947 (end-of-line 0)))
9948 ((and org-log-state-notes-insert-after-drawers
9949 (save-excursion
9950 (forward-line) (looking-at org-drawer-regexp)))
9951 (forward-line)
9952 (while (looking-at org-drawer-regexp)
9953 (goto-char (match-end 0))
9954 (re-search-forward org-property-end-re (point-max) t)
9955 (forward-line))
9956 (forward-line -1)))
9957 (unless org-log-states-order-reversed
9958 (and (= (char-after) ?\n) (forward-char 1))
9959 (org-skip-over-state-notes)
9960 (skip-chars-backward " \t\n\r")))
9961 (move-marker org-log-note-marker (point))
9962 (setq org-log-note-purpose purpose
9963 org-log-note-state state
9964 org-log-note-previous-state prev-state
9965 org-log-note-how how
9966 org-log-note-extra extra)
9967 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9969 (defun org-skip-over-state-notes ()
9970 "Skip past the list of State notes in an entry."
9971 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9972 (while (looking-at "[ \t]*- State")
9973 (condition-case nil
9974 (org-next-item)
9975 (error (org-end-of-item)))))
9977 (defun org-add-log-note (&optional purpose)
9978 "Pop up a window for taking a note, and add this note later at point."
9979 (remove-hook 'post-command-hook 'org-add-log-note)
9980 (setq org-log-note-window-configuration (current-window-configuration))
9981 (delete-other-windows)
9982 (move-marker org-log-note-return-to (point))
9983 (switch-to-buffer (marker-buffer org-log-note-marker))
9984 (goto-char org-log-note-marker)
9985 (org-switch-to-buffer-other-window "*Org Note*")
9986 (erase-buffer)
9987 (if (memq org-log-note-how '(time state))
9988 (let (current-prefix-arg) (org-store-log-note))
9989 (let ((org-inhibit-startup t)) (org-mode))
9990 (insert (format "# Insert note for %s.
9991 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9992 (cond
9993 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9994 ((eq org-log-note-purpose 'done) "closed todo item")
9995 ((eq org-log-note-purpose 'state)
9996 (format "state change from \"%s\" to \"%s\""
9997 (or org-log-note-previous-state "")
9998 (or org-log-note-state "")))
9999 ((eq org-log-note-purpose 'note)
10000 "this entry")
10001 (t (error "This should not happen")))))
10002 (if org-log-note-extra (insert org-log-note-extra))
10003 (org-set-local 'org-finish-function 'org-store-log-note)))
10005 (defvar org-note-abort nil) ; dynamically scoped
10006 (defun org-store-log-note ()
10007 "Finish taking a log note, and insert it to where it belongs."
10008 (let ((txt (buffer-string))
10009 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10010 lines ind)
10011 (kill-buffer (current-buffer))
10012 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10013 (setq txt (replace-match "" t t txt)))
10014 (if (string-match "\\s-+\\'" txt)
10015 (setq txt (replace-match "" t t txt)))
10016 (setq lines (org-split-string txt "\n"))
10017 (when (and note (string-match "\\S-" note))
10018 (setq note
10019 (org-replace-escapes
10020 note
10021 (list (cons "%u" (user-login-name))
10022 (cons "%U" user-full-name)
10023 (cons "%t" (format-time-string
10024 (org-time-stamp-format 'long 'inactive)
10025 (current-time)))
10026 (cons "%s" (if org-log-note-state
10027 (concat "\"" org-log-note-state "\"")
10028 ""))
10029 (cons "%S" (if org-log-note-previous-state
10030 (concat "\"" org-log-note-previous-state "\"")
10031 "\"\"")))))
10032 (if lines (setq note (concat note " \\\\")))
10033 (push note lines))
10034 (when (or current-prefix-arg org-note-abort)
10035 (when org-log-into-drawer
10036 (org-remove-empty-drawer-at
10037 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10038 org-log-note-marker))
10039 (setq lines nil))
10040 (when lines
10041 (save-excursion
10042 (set-buffer (marker-buffer org-log-note-marker))
10043 (save-excursion
10044 (goto-char org-log-note-marker)
10045 (move-marker org-log-note-marker nil)
10046 (end-of-line 1)
10047 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10048 (insert "- " (pop lines))
10049 (org-indent-line-function)
10050 (beginning-of-line 1)
10051 (looking-at "[ \t]*")
10052 (setq ind (concat (match-string 0) " "))
10053 (end-of-line 1)
10054 (while lines (insert "\n" ind (pop lines)))
10055 (message "Note stored")
10056 (org-back-to-heading t)
10057 (org-cycle-hide-drawers 'children)))))
10058 (set-window-configuration org-log-note-window-configuration)
10059 (with-current-buffer (marker-buffer org-log-note-return-to)
10060 (goto-char org-log-note-return-to))
10061 (move-marker org-log-note-return-to nil)
10062 (and org-log-post-message (message "%s" org-log-post-message)))
10064 (defun org-remove-empty-drawer-at (drawer pos)
10065 "Remove an emptyr DARWER drawer at position POS.
10066 POS may also be a marker."
10067 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10068 (save-excursion
10069 (save-restriction
10070 (widen)
10071 (goto-char pos)
10072 (if (org-in-regexp
10073 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10074 (replace-match ""))))))
10076 (defun org-sparse-tree (&optional arg)
10077 "Create a sparse tree, prompt for the details.
10078 This command can create sparse trees. You first need to select the type
10079 of match used to create the tree:
10081 t Show entries with a specific TODO keyword.
10082 m Show entries selected by a tags/property match.
10083 p Enter a property name and its value (both with completion on existing
10084 names/values) and show entries with that property.
10085 r Show entries matching a regular expression.
10086 d Show deadlines due within `org-deadline-warning-days'.
10087 b Show deadlines and scheduled items before a date.
10088 a Show deadlines and scheduled items after a date."
10089 (interactive "P")
10090 (let (ans kwd value)
10091 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10092 (setq ans (read-char-exclusive))
10093 (cond
10094 ((equal ans ?d)
10095 (call-interactively 'org-check-deadlines))
10096 ((equal ans ?b)
10097 (call-interactively 'org-check-before-date))
10098 ((equal ans ?a)
10099 (call-interactively 'org-check-after-date))
10100 ((equal ans ?t)
10101 (org-show-todo-tree '(4)))
10102 ((member ans '(?T ?m))
10103 (call-interactively 'org-match-sparse-tree))
10104 ((member ans '(?p ?P))
10105 (setq kwd (org-ido-completing-read "Property: "
10106 (mapcar 'list (org-buffer-property-keys))))
10107 (setq value (org-ido-completing-read "Value: "
10108 (mapcar 'list (org-property-values kwd))))
10109 (unless (string-match "\\`{.*}\\'" value)
10110 (setq value (concat "\"" value "\"")))
10111 (org-match-sparse-tree arg (concat kwd "=" value)))
10112 ((member ans '(?r ?R ?/))
10113 (call-interactively 'org-occur))
10114 (t (error "No such sparse tree command \"%c\"" ans)))))
10116 (defvar org-occur-highlights nil
10117 "List of overlays used for occur matches.")
10118 (make-variable-buffer-local 'org-occur-highlights)
10119 (defvar org-occur-parameters nil
10120 "Parameters of the active org-occur calls.
10121 This is a list, each call to org-occur pushes as cons cell,
10122 containing the regular expression and the callback, onto the list.
10123 The list can contain several entries if `org-occur' has been called
10124 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10125 will only contain one set of parameters. When the highlights are
10126 removed (for example with `C-c C-c', or with the next edit (depending
10127 on `org-remove-highlights-with-change'), this variable is emptied
10128 as well.")
10129 (make-variable-buffer-local 'org-occur-parameters)
10131 (defun org-occur (regexp &optional keep-previous callback)
10132 "Make a compact tree which shows all matches of REGEXP.
10133 The tree will show the lines where the regexp matches, and all higher
10134 headlines above the match. It will also show the heading after the match,
10135 to make sure editing the matching entry is easy.
10136 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10137 call to `org-occur' will be kept, to allow stacking of calls to this
10138 command.
10139 If CALLBACK is non-nil, it is a function which is called to confirm
10140 that the match should indeed be shown."
10141 (interactive "sRegexp: \nP")
10142 (unless keep-previous
10143 (org-remove-occur-highlights nil nil t))
10144 (push (cons regexp callback) org-occur-parameters)
10145 (let ((cnt 0))
10146 (save-excursion
10147 (goto-char (point-min))
10148 (if (or (not keep-previous) ; do not want to keep
10149 (not org-occur-highlights)) ; no previous matches
10150 ;; hide everything
10151 (org-overview))
10152 (while (re-search-forward regexp nil t)
10153 (when (or (not callback)
10154 (save-match-data (funcall callback)))
10155 (setq cnt (1+ cnt))
10156 (when org-highlight-sparse-tree-matches
10157 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10158 (org-show-context 'occur-tree))))
10159 (when org-remove-highlights-with-change
10160 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10161 nil 'local))
10162 (unless org-sparse-tree-open-archived-trees
10163 (org-hide-archived-subtrees (point-min) (point-max)))
10164 (run-hooks 'org-occur-hook)
10165 (if (interactive-p)
10166 (message "%d match(es) for regexp %s" cnt regexp))
10167 cnt))
10169 (defun org-show-context (&optional key)
10170 "Make sure point and context and visible.
10171 How much context is shown depends upon the variables
10172 `org-show-hierarchy-above', `org-show-following-heading'. and
10173 `org-show-siblings'."
10174 (let ((heading-p (org-on-heading-p t))
10175 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10176 (following-p (org-get-alist-option org-show-following-heading key))
10177 (entry-p (org-get-alist-option org-show-entry-below key))
10178 (siblings-p (org-get-alist-option org-show-siblings key)))
10179 (catch 'exit
10180 ;; Show heading or entry text
10181 (if (and heading-p (not entry-p))
10182 (org-flag-heading nil) ; only show the heading
10183 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10184 (org-show-hidden-entry))) ; show entire entry
10185 (when following-p
10186 ;; Show next sibling, or heading below text
10187 (save-excursion
10188 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10189 (org-flag-heading nil))))
10190 (when siblings-p (org-show-siblings))
10191 (when hierarchy-p
10192 ;; show all higher headings, possibly with siblings
10193 (save-excursion
10194 (while (and (condition-case nil
10195 (progn (org-up-heading-all 1) t)
10196 (error nil))
10197 (not (bobp)))
10198 (org-flag-heading nil)
10199 (when siblings-p (org-show-siblings))))))))
10201 (defun org-reveal (&optional siblings)
10202 "Show current entry, hierarchy above it, and the following headline.
10203 This can be used to show a consistent set of context around locations
10204 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10205 not t for the search context.
10207 With optional argument SIBLINGS, on each level of the hierarchy all
10208 siblings are shown. This repairs the tree structure to what it would
10209 look like when opened with hierarchical calls to `org-cycle'."
10210 (interactive "P")
10211 (let ((org-show-hierarchy-above t)
10212 (org-show-following-heading t)
10213 (org-show-siblings (if siblings t org-show-siblings)))
10214 (org-show-context nil)))
10216 (defun org-highlight-new-match (beg end)
10217 "Highlight from BEG to END and mark the highlight is an occur headline."
10218 (let ((ov (org-make-overlay beg end)))
10219 (org-overlay-put ov 'face 'secondary-selection)
10220 (push ov org-occur-highlights)))
10222 (defun org-remove-occur-highlights (&optional beg end noremove)
10223 "Remove the occur highlights from the buffer.
10224 BEG and END are ignored. If NOREMOVE is nil, remove this function
10225 from the `before-change-functions' in the current buffer."
10226 (interactive)
10227 (unless org-inhibit-highlight-removal
10228 (mapc 'org-delete-overlay org-occur-highlights)
10229 (setq org-occur-highlights nil)
10230 (setq org-occur-parameters nil)
10231 (unless noremove
10232 (remove-hook 'before-change-functions
10233 'org-remove-occur-highlights 'local))))
10235 ;;;; Priorities
10237 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10238 "Regular expression matching the priority indicator.")
10240 (defvar org-remove-priority-next-time nil)
10242 (defun org-priority-up ()
10243 "Increase the priority of the current item."
10244 (interactive)
10245 (org-priority 'up))
10247 (defun org-priority-down ()
10248 "Decrease the priority of the current item."
10249 (interactive)
10250 (org-priority 'down))
10252 (defun org-priority (&optional action)
10253 "Change the priority of an item by ARG.
10254 ACTION can be `set', `up', `down', or a character."
10255 (interactive)
10256 (unless org-enable-priority-commands
10257 (error "Priority commands are disabled"))
10258 (setq action (or action 'set))
10259 (let (current new news have remove)
10260 (save-excursion
10261 (org-back-to-heading t)
10262 (if (looking-at org-priority-regexp)
10263 (setq current (string-to-char (match-string 2))
10264 have t)
10265 (setq current org-default-priority))
10266 (cond
10267 ((or (eq action 'set)
10268 (if (featurep 'xemacs) (characterp action) (integerp action)))
10269 (if (not (eq action 'set))
10270 (setq new action)
10271 (message "Priority %c-%c, SPC to remove: "
10272 org-highest-priority org-lowest-priority)
10273 (setq new (read-char-exclusive)))
10274 (if (and (= (upcase org-highest-priority) org-highest-priority)
10275 (= (upcase org-lowest-priority) org-lowest-priority))
10276 (setq new (upcase new)))
10277 (cond ((equal new ?\ ) (setq remove t))
10278 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10279 (error "Priority must be between `%c' and `%c'"
10280 org-highest-priority org-lowest-priority))))
10281 ((eq action 'up)
10282 (if (and (not have) (eq last-command this-command))
10283 (setq new org-lowest-priority)
10284 (setq new (if (and org-priority-start-cycle-with-default (not have))
10285 org-default-priority (1- current)))))
10286 ((eq action 'down)
10287 (if (and (not have) (eq last-command this-command))
10288 (setq new org-highest-priority)
10289 (setq new (if (and org-priority-start-cycle-with-default (not have))
10290 org-default-priority (1+ current)))))
10291 (t (error "Invalid action")))
10292 (if (or (< (upcase new) org-highest-priority)
10293 (> (upcase new) org-lowest-priority))
10294 (setq remove t))
10295 (setq news (format "%c" new))
10296 (if have
10297 (if remove
10298 (replace-match "" t t nil 1)
10299 (replace-match news t t nil 2))
10300 (if remove
10301 (error "No priority cookie found in line")
10302 (let ((case-fold-search nil))
10303 (looking-at org-todo-line-regexp))
10304 (if (match-end 2)
10305 (progn
10306 (goto-char (match-end 2))
10307 (insert " [#" news "]"))
10308 (goto-char (match-beginning 3))
10309 (insert "[#" news "] ")))))
10310 (org-preserve-lc (org-set-tags nil 'align))
10311 (if remove
10312 (message "Priority removed")
10313 (message "Priority of current item set to %s" news))))
10316 (defun org-get-priority (s)
10317 "Find priority cookie and return priority."
10318 (save-match-data
10319 (if (not (string-match org-priority-regexp s))
10320 (* 1000 (- org-lowest-priority org-default-priority))
10321 (* 1000 (- org-lowest-priority
10322 (string-to-char (match-string 2 s)))))))
10324 ;;;; Tags
10326 (defvar org-agenda-archives-mode)
10327 (defvar org-map-continue-from nil
10328 "Position from where mapping should continue.
10329 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10331 (defvar org-scanner-tags nil
10332 "The current tag list while the tags scanner is running.")
10333 (defvar org-trust-scanner-tags nil
10334 "Should `org-get-tags-at' use the tags fro the scanner.
10335 This is for internal dynamical scoping only.
10336 When this is non-nil, the function `org-get-tags-at' will return the value
10337 of `org-scanner-tags' instead of building the list by itself. This
10338 can lead to large speed-ups when the tags scanner is used in a file with
10339 many entries, and when the list of tags is retrieved, for example to
10340 obtain a list of properties. Building the tags list for each entry in such
10341 a file becomes an N^2 operation - but with this variable set, it scales
10342 as N.")
10344 (defun org-scan-tags (action matcher &optional todo-only)
10345 "Scan headline tags with inheritance and produce output ACTION.
10347 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10348 or `agenda' to produce an entry list for an agenda view. It can also be
10349 a Lisp form or a function that should be called at each matched headline, in
10350 this case the return value is a list of all return values from these calls.
10352 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10353 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10354 only lines with a TODO keyword are included in the output."
10355 (require 'org-agenda)
10356 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10357 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10358 (org-re
10359 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10360 (props (list 'face 'default
10361 'done-face 'org-agenda-done
10362 'undone-face 'default
10363 'mouse-face 'highlight
10364 'org-not-done-regexp org-not-done-regexp
10365 'org-todo-regexp org-todo-regexp
10366 'keymap org-agenda-keymap
10367 'help-echo
10368 (format "mouse-2 or RET jump to org file %s"
10369 (abbreviate-file-name
10370 (or (buffer-file-name (buffer-base-buffer))
10371 (buffer-name (buffer-base-buffer)))))))
10372 (case-fold-search nil)
10373 (org-map-continue-from nil)
10374 lspos tags tags-list
10375 (tags-alist (list (cons 0 org-file-tags)))
10376 (llast 0) rtn rtn1 level category i txt
10377 todo marker entry priority)
10378 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10379 (setq action (list 'lambda nil action)))
10380 (save-excursion
10381 (goto-char (point-min))
10382 (when (eq action 'sparse-tree)
10383 (org-overview)
10384 (org-remove-occur-highlights))
10385 (while (re-search-forward re nil t)
10386 (catch :skip
10387 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10388 tags (if (match-end 4) (org-match-string-no-properties 4)))
10389 (goto-char (setq lspos (match-beginning 0)))
10390 (setq level (org-reduced-level (funcall outline-level))
10391 category (org-get-category))
10392 (setq i llast llast level)
10393 ;; remove tag lists from same and sublevels
10394 (while (>= i level)
10395 (when (setq entry (assoc i tags-alist))
10396 (setq tags-alist (delete entry tags-alist)))
10397 (setq i (1- i)))
10398 ;; add the next tags
10399 (when tags
10400 (setq tags (org-split-string tags ":")
10401 tags-alist
10402 (cons (cons level tags) tags-alist)))
10403 ;; compile tags for current headline
10404 (setq tags-list
10405 (if org-use-tag-inheritance
10406 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10407 tags)
10408 org-scanner-tags tags-list)
10409 (when org-use-tag-inheritance
10410 (setcdr (car tags-alist)
10411 (mapcar (lambda (x)
10412 (setq x (copy-sequence x))
10413 (org-add-prop-inherited x))
10414 (cdar tags-alist))))
10415 (when (and tags org-use-tag-inheritance
10416 (or (not (eq t org-use-tag-inheritance))
10417 org-tags-exclude-from-inheritance))
10418 ;; selective inheritance, remove uninherited ones
10419 (setcdr (car tags-alist)
10420 (org-remove-uniherited-tags (cdar tags-alist))))
10421 (when (and (or (not todo-only)
10422 (and (member todo org-not-done-keywords)
10423 (or (not org-agenda-tags-todo-honor-ignore-options)
10424 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10425 (let ((case-fold-search t)) (eval matcher))
10427 (not (member org-archive-tag tags-list))
10428 ;; we have an archive tag, should we use this anyway?
10429 (or (not org-agenda-skip-archived-trees)
10430 (and (eq action 'agenda) org-agenda-archives-mode))))
10431 (unless (eq action 'sparse-tree) (org-agenda-skip))
10433 ;; select this headline
10435 (cond
10436 ((eq action 'sparse-tree)
10437 (and org-highlight-sparse-tree-matches
10438 (org-get-heading) (match-end 0)
10439 (org-highlight-new-match
10440 (match-beginning 0) (match-beginning 1)))
10441 (org-show-context 'tags-tree))
10442 ((eq action 'agenda)
10443 (setq txt (org-format-agenda-item
10445 (concat
10446 (if (eq org-tags-match-list-sublevels 'indented)
10447 (make-string (1- level) ?.) "")
10448 (org-get-heading))
10449 category
10450 tags-list
10452 priority (org-get-priority txt))
10453 (goto-char lspos)
10454 (setq marker (org-agenda-new-marker))
10455 (org-add-props txt props
10456 'org-marker marker 'org-hd-marker marker 'org-category category
10457 'todo-state todo
10458 'priority priority 'type "tagsmatch")
10459 (push txt rtn))
10460 ((functionp action)
10461 (setq org-map-continue-from nil)
10462 (save-excursion
10463 (setq rtn1 (funcall action))
10464 (push rtn1 rtn)))
10465 (t (error "Invalid action")))
10467 ;; if we are to skip sublevels, jump to end of subtree
10468 (unless org-tags-match-list-sublevels
10469 (org-end-of-subtree t)
10470 (backward-char 1))))
10471 ;; Get the correct position from where to continue
10472 (if org-map-continue-from
10473 (goto-char org-map-continue-from)
10474 (and (= (point) lspos) (end-of-line 1)))))
10475 (when (and (eq action 'sparse-tree)
10476 (not org-sparse-tree-open-archived-trees))
10477 (org-hide-archived-subtrees (point-min) (point-max)))
10478 (nreverse rtn)))
10480 (defun org-remove-uniherited-tags (tags)
10481 "Remove all tags that are not inherited from the list TAGS."
10482 (cond
10483 ((eq org-use-tag-inheritance t)
10484 (if org-tags-exclude-from-inheritance
10485 (org-delete-all org-tags-exclude-from-inheritance tags)
10486 tags))
10487 ((not org-use-tag-inheritance) nil)
10488 ((stringp org-use-tag-inheritance)
10489 (delq nil (mapcar
10490 (lambda (x)
10491 (if (and (string-match org-use-tag-inheritance x)
10492 (not (member x org-tags-exclude-from-inheritance)))
10493 x nil))
10494 tags)))
10495 ((listp org-use-tag-inheritance)
10496 (delq nil (mapcar
10497 (lambda (x)
10498 (if (member x org-use-tag-inheritance) x nil))
10499 tags)))))
10501 (defvar todo-only) ;; dynamically scoped
10503 (defun org-match-sparse-tree (&optional todo-only match)
10504 "Create a sparse tree according to tags string MATCH.
10505 MATCH can contain positive and negative selection of tags, like
10506 \"+WORK+URGENT-WITHBOSS\".
10507 If optional argument TODO-ONLY is non-nil, only select lines that are
10508 also TODO lines."
10509 (interactive "P")
10510 (org-prepare-agenda-buffers (list (current-buffer)))
10511 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10513 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10515 (defvar org-cached-props nil)
10516 (defun org-cached-entry-get (pom property)
10517 (if (or (eq t org-use-property-inheritance)
10518 (and (stringp org-use-property-inheritance)
10519 (string-match org-use-property-inheritance property))
10520 (and (listp org-use-property-inheritance)
10521 (member property org-use-property-inheritance)))
10522 ;; Caching is not possible, check it directly
10523 (org-entry-get pom property 'inherit)
10524 ;; Get all properties, so that we can do complicated checks easily
10525 (cdr (assoc property (or org-cached-props
10526 (setq org-cached-props
10527 (org-entry-properties pom)))))))
10529 (defun org-global-tags-completion-table (&optional files)
10530 "Return the list of all tags in all agenda buffer/files."
10531 (save-excursion
10532 (org-uniquify
10533 (delq nil
10534 (apply 'append
10535 (mapcar
10536 (lambda (file)
10537 (set-buffer (find-file-noselect file))
10538 (append (org-get-buffer-tags)
10539 (mapcar (lambda (x) (if (stringp (car-safe x))
10540 (list (car-safe x)) nil))
10541 org-tag-alist)))
10542 (if (and files (car files))
10543 files
10544 (org-agenda-files))))))))
10546 (defun org-make-tags-matcher (match)
10547 "Create the TAGS//TODO matcher form for the selection string MATCH."
10548 ;; todo-only is scoped dynamically into this function, and the function
10549 ;; may change it if the matcher asks for it.
10550 (unless match
10551 ;; Get a new match request, with completion
10552 (let ((org-last-tags-completion-table
10553 (org-global-tags-completion-table)))
10554 (setq match (org-completing-read-no-ido
10555 "Match: " 'org-tags-completion-function nil nil nil
10556 'org-tags-history))))
10558 ;; Parse the string and create a lisp form
10559 (let ((match0 match)
10560 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10561 minus tag mm
10562 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10563 orterms term orlist re-p str-p level-p level-op time-p
10564 prop-p pn pv po cat-p gv rest)
10565 (if (string-match "/+" match)
10566 ;; match contains also a todo-matching request
10567 (progn
10568 (setq tagsmatch (substring match 0 (match-beginning 0))
10569 todomatch (substring match (match-end 0)))
10570 (if (string-match "^!" todomatch)
10571 (setq todo-only t todomatch (substring todomatch 1)))
10572 (if (string-match "^\\s-*$" todomatch)
10573 (setq todomatch nil)))
10574 ;; only matching tags
10575 (setq tagsmatch match todomatch nil))
10577 ;; Make the tags matcher
10578 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10579 (setq tagsmatcher t)
10580 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10581 (while (setq term (pop orterms))
10582 (while (and (equal (substring term -1) "\\") orterms)
10583 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10584 (while (string-match re term)
10585 (setq rest (substring term (match-end 0))
10586 minus (and (match-end 1)
10587 (equal (match-string 1 term) "-"))
10588 tag (match-string 2 term)
10589 re-p (equal (string-to-char tag) ?{)
10590 level-p (match-end 4)
10591 prop-p (match-end 5)
10592 mm (cond
10593 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10594 (level-p
10595 (setq level-op (org-op-to-function (match-string 3 term)))
10596 `(,level-op level ,(string-to-number
10597 (match-string 4 term))))
10598 (prop-p
10599 (setq pn (match-string 5 term)
10600 po (match-string 6 term)
10601 pv (match-string 7 term)
10602 cat-p (equal pn "CATEGORY")
10603 re-p (equal (string-to-char pv) ?{)
10604 str-p (equal (string-to-char pv) ?\")
10605 time-p (save-match-data
10606 (string-match "^\"[[<].*[]>]\"$" pv))
10607 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10608 (if time-p (setq pv (org-matcher-time pv)))
10609 (setq po (org-op-to-function po (if time-p 'time str-p)))
10610 (cond
10611 ((equal pn "CATEGORY")
10612 (setq gv '(get-text-property (point) 'org-category)))
10613 ((equal pn "TODO")
10614 (setq gv 'todo))
10616 (setq gv `(org-cached-entry-get nil ,pn))))
10617 (if re-p
10618 (if (eq po 'org<>)
10619 `(not (string-match ,pv (or ,gv "")))
10620 `(string-match ,pv (or ,gv "")))
10621 (if str-p
10622 `(,po (or ,gv "") ,pv)
10623 `(,po (string-to-number (or ,gv ""))
10624 ,(string-to-number pv) ))))
10625 (t `(member ,tag tags-list)))
10626 mm (if minus (list 'not mm) mm)
10627 term rest)
10628 (push mm tagsmatcher))
10629 (push (if (> (length tagsmatcher) 1)
10630 (cons 'and tagsmatcher)
10631 (car tagsmatcher))
10632 orlist)
10633 (setq tagsmatcher nil))
10634 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10635 (setq tagsmatcher
10636 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10637 ;; Make the todo matcher
10638 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10639 (setq todomatcher t)
10640 (setq orterms (org-split-string todomatch "|") orlist nil)
10641 (while (setq term (pop orterms))
10642 (while (string-match re term)
10643 (setq minus (and (match-end 1)
10644 (equal (match-string 1 term) "-"))
10645 kwd (match-string 2 term)
10646 re-p (equal (string-to-char kwd) ?{)
10647 term (substring term (match-end 0))
10648 mm (if re-p
10649 `(string-match ,(substring kwd 1 -1) todo)
10650 (list 'equal 'todo kwd))
10651 mm (if minus (list 'not mm) mm))
10652 (push mm todomatcher))
10653 (push (if (> (length todomatcher) 1)
10654 (cons 'and todomatcher)
10655 (car todomatcher))
10656 orlist)
10657 (setq todomatcher nil))
10658 (setq todomatcher (if (> (length orlist) 1)
10659 (cons 'or orlist) (car orlist))))
10661 ;; Return the string and lisp forms of the matcher
10662 (setq matcher (if todomatcher
10663 (list 'and tagsmatcher todomatcher)
10664 tagsmatcher))
10665 (cons match0 matcher)))
10667 (defun org-op-to-function (op &optional stringp)
10668 "Turn an operator into the appropriate function."
10669 (setq op
10670 (cond
10671 ((equal op "<" ) '(< string< org-time<))
10672 ((equal op ">" ) '(> org-string> org-time>))
10673 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10674 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10675 ((member op '("=" "==")) '(= string= org-time=))
10676 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10677 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10679 (defun org<> (a b) (not (= a b)))
10680 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10681 (defun org-string>= (a b) (not (string< a b)))
10682 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10683 (defun org-string<> (a b) (not (string= a b)))
10684 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10685 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10686 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10687 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10688 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10689 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10690 (defun org-2ft (s)
10691 "Convert S to a floating point time.
10692 If S is already a number, just return it. If it is a string, parse
10693 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10694 (cond
10695 ((numberp s) s)
10696 ((stringp s)
10697 (condition-case nil
10698 (float-time (apply 'encode-time (org-parse-time-string s)))
10699 (error 0.)))
10700 (t 0.)))
10702 (defun org-time-today ()
10703 "Time in seconds today at 0:00.
10704 Returns the float number of seconds since the beginning of the
10705 epoch to the beginning of today (00:00)."
10706 (float-time (apply 'encode-time
10707 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10709 (defun org-matcher-time (s)
10710 "Interpret a time comparison value."
10711 (save-match-data
10712 (cond
10713 ((string= s "<now>") (float-time))
10714 ((string= s "<today>") (org-time-today))
10715 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10716 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10717 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10718 (+ (org-time-today)
10719 (* (string-to-number (match-string 1 s))
10720 (cdr (assoc (match-string 2 s)
10721 '(("d" . 86400.0) ("w" . 604800.0)
10722 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10723 (t (org-2ft s)))))
10725 (defun org-match-any-p (re list)
10726 "Does re match any element of list?"
10727 (setq list (mapcar (lambda (x) (string-match re x)) list))
10728 (delq nil list))
10730 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10731 (defvar org-tags-overlay (org-make-overlay 1 1))
10732 (org-detach-overlay org-tags-overlay)
10734 (defun org-get-local-tags-at (&optional pos)
10735 "Get a list of tags defined in the current headline."
10736 (org-get-tags-at pos 'local))
10738 (defun org-get-local-tags ()
10739 "Get a list of tags defined in the current headline."
10740 (org-get-tags-at nil 'local))
10742 (defun org-get-tags-at (&optional pos local)
10743 "Get a list of all headline tags applicable at POS.
10744 POS defaults to point. If tags are inherited, the list contains
10745 the targets in the same sequence as the headlines appear, i.e.
10746 the tags of the current headline come last.
10747 When LOCAL is non-nil, only return tags from the current headline,
10748 ignore inherited ones."
10749 (interactive)
10750 (if (and org-trust-scanner-tags
10751 (or (not pos) (equal pos (point)))
10752 (not local))
10753 org-scanner-tags
10754 (let (tags ltags lastpos parent)
10755 (save-excursion
10756 (save-restriction
10757 (widen)
10758 (goto-char (or pos (point)))
10759 (save-match-data
10760 (catch 'done
10761 (condition-case nil
10762 (progn
10763 (org-back-to-heading t)
10764 (while (not (equal lastpos (point)))
10765 (setq lastpos (point))
10766 (when (looking-at
10767 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10768 (setq ltags (org-split-string
10769 (org-match-string-no-properties 1) ":"))
10770 (when parent
10771 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10772 (setq tags (append
10773 (if parent
10774 (org-remove-uniherited-tags ltags)
10775 ltags)
10776 tags)))
10777 (or org-use-tag-inheritance (throw 'done t))
10778 (if local (throw 'done t))
10779 (or (org-up-heading-safe) (error nil))
10780 (setq parent t)))
10781 (error nil)))))
10782 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10784 (defun org-add-prop-inherited (s)
10785 (add-text-properties 0 (length s) '(inherited t) s)
10788 (defun org-toggle-tag (tag &optional onoff)
10789 "Toggle the tag TAG for the current line.
10790 If ONOFF is `on' or `off', don't toggle but set to this state."
10791 (let (res current)
10792 (save-excursion
10793 (org-back-to-heading t)
10794 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10795 (point-at-eol) t)
10796 (progn
10797 (setq current (match-string 1))
10798 (replace-match ""))
10799 (setq current ""))
10800 (setq current (nreverse (org-split-string current ":")))
10801 (cond
10802 ((eq onoff 'on)
10803 (setq res t)
10804 (or (member tag current) (push tag current)))
10805 ((eq onoff 'off)
10806 (or (not (member tag current)) (setq current (delete tag current))))
10807 (t (if (member tag current)
10808 (setq current (delete tag current))
10809 (setq res t)
10810 (push tag current))))
10811 (end-of-line 1)
10812 (if current
10813 (progn
10814 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10815 (org-set-tags nil t))
10816 (delete-horizontal-space))
10817 (run-hooks 'org-after-tags-change-hook))
10818 res))
10820 (defun org-align-tags-here (to-col)
10821 ;; Assumes that this is a headline
10822 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10823 (beginning-of-line 1)
10824 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10825 (< pos (match-beginning 2)))
10826 (progn
10827 (setq tags-l (- (match-end 2) (match-beginning 2)))
10828 (goto-char (match-beginning 1))
10829 (insert " ")
10830 (delete-region (point) (1+ (match-beginning 2)))
10831 (setq ncol (max (1+ (current-column))
10832 (1+ col)
10833 (if (> to-col 0)
10834 to-col
10835 (- (abs to-col) tags-l))))
10836 (setq p (point))
10837 (insert (make-string (- ncol (current-column)) ?\ ))
10838 (setq ncol (current-column))
10839 (when indent-tabs-mode (tabify p (point-at-eol)))
10840 (org-move-to-column (min ncol col) t))
10841 (goto-char pos))))
10843 (defun org-set-tags-command (&optional arg just-align)
10844 "Call the set-tags command for the current entry."
10845 (interactive "P")
10846 (if (org-on-heading-p)
10847 (org-set-tags arg just-align)
10848 (save-excursion
10849 (org-back-to-heading t)
10850 (org-set-tags arg just-align))))
10852 (defun org-set-tags (&optional arg just-align)
10853 "Set the tags for the current headline.
10854 With prefix ARG, realign all tags in headings in the current buffer."
10855 (interactive "P")
10856 (let* ((re (concat "^" outline-regexp))
10857 (current (org-get-tags-string))
10858 (col (current-column))
10859 (org-setting-tags t)
10860 table current-tags inherited-tags ; computed below when needed
10861 tags p0 c0 c1 rpl)
10862 (if arg
10863 (save-excursion
10864 (goto-char (point-min))
10865 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10866 (while (re-search-forward re nil t)
10867 (org-set-tags nil t)
10868 (end-of-line 1)))
10869 (message "All tags realigned to column %d" org-tags-column))
10870 (if just-align
10871 (setq tags current)
10872 ;; Get a new set of tags from the user
10873 (save-excursion
10874 (setq table (append org-tag-persistent-alist
10875 (or org-tag-alist (org-get-buffer-tags)))
10876 org-last-tags-completion-table table
10877 current-tags (org-split-string current ":")
10878 inherited-tags (nreverse
10879 (nthcdr (length current-tags)
10880 (nreverse (org-get-tags-at))))
10881 tags
10882 (if (or (eq t org-use-fast-tag-selection)
10883 (and org-use-fast-tag-selection
10884 (delq nil (mapcar 'cdr table))))
10885 (org-fast-tag-selection
10886 current-tags inherited-tags table
10887 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10888 (let ((org-add-colon-after-tag-completion t))
10889 (org-trim
10890 (org-without-partial-completion
10891 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10892 nil nil current 'org-tags-history)))))))
10893 (while (string-match "[-+&]+" tags)
10894 ;; No boolean logic, just a list
10895 (setq tags (replace-match ":" t t tags))))
10897 (if (string-match "\\`[\t ]*\\'" tags)
10898 (setq tags "")
10899 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10900 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10902 ;; Insert new tags at the correct column
10903 (beginning-of-line 1)
10904 (cond
10905 ((and (equal current "") (equal tags "")))
10906 ((re-search-forward
10907 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10908 (point-at-eol) t)
10909 (if (equal tags "")
10910 (setq rpl "")
10911 (goto-char (match-beginning 0))
10912 (setq c0 (current-column) p0 (point)
10913 c1 (max (1+ c0) (if (> org-tags-column 0)
10914 org-tags-column
10915 (- (- org-tags-column) (length tags))))
10916 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10917 (replace-match rpl t t)
10918 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10919 tags)
10920 (t (error "Tags alignment failed")))
10921 (org-move-to-column col)
10922 (unless just-align
10923 (run-hooks 'org-after-tags-change-hook)))))
10925 (defun org-change-tag-in-region (beg end tag off)
10926 "Add or remove TAG for each entry in the region.
10927 This works in the agenda, and also in an org-mode buffer."
10928 (interactive
10929 (list (region-beginning) (region-end)
10930 (let ((org-last-tags-completion-table
10931 (if (org-mode-p)
10932 (org-get-buffer-tags)
10933 (org-global-tags-completion-table))))
10934 (org-ido-completing-read
10935 "Tag: " 'org-tags-completion-function nil nil nil
10936 'org-tags-history))
10937 (progn
10938 (message "[s]et or [r]emove? ")
10939 (equal (read-char-exclusive) ?r))))
10940 (if (fboundp 'deactivate-mark) (deactivate-mark))
10941 (let ((agendap (equal major-mode 'org-agenda-mode))
10942 l1 l2 m buf pos newhead (cnt 0))
10943 (goto-char end)
10944 (setq l2 (1- (org-current-line)))
10945 (goto-char beg)
10946 (setq l1 (org-current-line))
10947 (loop for l from l1 to l2 do
10948 (goto-line l)
10949 (setq m (get-text-property (point) 'org-hd-marker))
10950 (when (or (and (org-mode-p) (org-on-heading-p))
10951 (and agendap m))
10952 (setq buf (if agendap (marker-buffer m) (current-buffer))
10953 pos (if agendap m (point)))
10954 (with-current-buffer buf
10955 (save-excursion
10956 (save-restriction
10957 (goto-char pos)
10958 (setq cnt (1+ cnt))
10959 (org-toggle-tag tag (if off 'off 'on))
10960 (setq newhead (org-get-heading)))))
10961 (and agendap (org-agenda-change-all-lines newhead m))))
10962 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10964 (defun org-tags-completion-function (string predicate &optional flag)
10965 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10966 (confirm (lambda (x) (stringp (car x)))))
10967 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10968 (setq s1 (match-string 1 string)
10969 s2 (match-string 2 string))
10970 (setq s1 "" s2 string))
10971 (cond
10972 ((eq flag nil)
10973 ;; try completion
10974 (setq rtn (try-completion s2 ctable confirm))
10975 (if (stringp rtn)
10976 (setq rtn
10977 (concat s1 s2 (substring rtn (length s2))
10978 (if (and org-add-colon-after-tag-completion
10979 (assoc rtn ctable))
10980 ":" ""))))
10981 rtn)
10982 ((eq flag t)
10983 ;; all-completions
10984 (all-completions s2 ctable confirm)
10986 ((eq flag 'lambda)
10987 ;; exact match?
10988 (assoc s2 ctable)))
10991 (defun org-fast-tag-insert (kwd tags face &optional end)
10992 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10993 (insert (format "%-12s" (concat kwd ":"))
10994 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10995 (or end "")))
10997 (defun org-fast-tag-show-exit (flag)
10998 (save-excursion
10999 (goto-line 3)
11000 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11001 (replace-match ""))
11002 (when flag
11003 (end-of-line 1)
11004 (org-move-to-column (- (window-width) 19) t)
11005 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11007 (defun org-set-current-tags-overlay (current prefix)
11008 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11009 (if (featurep 'xemacs)
11010 (org-overlay-display org-tags-overlay (concat prefix s)
11011 'secondary-selection)
11012 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11013 (org-overlay-display org-tags-overlay (concat prefix s)))))
11015 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11016 "Fast tag selection with single keys.
11017 CURRENT is the current list of tags in the headline, INHERITED is the
11018 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11019 possibly with grouping information. TODO-TABLE is a similar table with
11020 TODO keywords, should these have keys assigned to them.
11021 If the keys are nil, a-z are automatically assigned.
11022 Returns the new tags string, or nil to not change the current settings."
11023 (let* ((fulltable (append table todo-table))
11024 (maxlen (apply 'max (mapcar
11025 (lambda (x)
11026 (if (stringp (car x)) (string-width (car x)) 0))
11027 fulltable)))
11028 (buf (current-buffer))
11029 (expert (eq org-fast-tag-selection-single-key 'expert))
11030 (buffer-tags nil)
11031 (fwidth (+ maxlen 3 1 3))
11032 (ncol (/ (- (window-width) 4) fwidth))
11033 (i-face 'org-done)
11034 (c-face 'org-todo)
11035 tg cnt e c char c1 c2 ntable tbl rtn
11036 ov-start ov-end ov-prefix
11037 (exit-after-next org-fast-tag-selection-single-key)
11038 (done-keywords org-done-keywords)
11039 groups ingroup)
11040 (save-excursion
11041 (beginning-of-line 1)
11042 (if (looking-at
11043 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11044 (setq ov-start (match-beginning 1)
11045 ov-end (match-end 1)
11046 ov-prefix "")
11047 (setq ov-start (1- (point-at-eol))
11048 ov-end (1+ ov-start))
11049 (skip-chars-forward "^\n\r")
11050 (setq ov-prefix
11051 (concat
11052 (buffer-substring (1- (point)) (point))
11053 (if (> (current-column) org-tags-column)
11055 (make-string (- org-tags-column (current-column)) ?\ ))))))
11056 (org-move-overlay org-tags-overlay ov-start ov-end)
11057 (save-window-excursion
11058 (if expert
11059 (set-buffer (get-buffer-create " *Org tags*"))
11060 (delete-other-windows)
11061 (split-window-vertically)
11062 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11063 (erase-buffer)
11064 (org-set-local 'org-done-keywords done-keywords)
11065 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11066 (org-fast-tag-insert "Current" current c-face "\n\n")
11067 (org-fast-tag-show-exit exit-after-next)
11068 (org-set-current-tags-overlay current ov-prefix)
11069 (setq tbl fulltable char ?a cnt 0)
11070 (while (setq e (pop tbl))
11071 (cond
11072 ((equal e '(:startgroup))
11073 (push '() groups) (setq ingroup t)
11074 (when (not (= cnt 0))
11075 (setq cnt 0)
11076 (insert "\n"))
11077 (insert "{ "))
11078 ((equal e '(:endgroup))
11079 (setq ingroup nil cnt 0)
11080 (insert "}\n"))
11081 ((equal e '(:newline))
11082 (when (not (= cnt 0))
11083 (setq cnt 0)
11084 (insert "\n")
11085 (setq e (car tbl))
11086 (while (equal (car tbl) '(:newline))
11087 (insert "\n")
11088 (setq tbl (cdr tbl)))))
11090 (setq tg (car e) c2 nil)
11091 (if (cdr e)
11092 (setq c (cdr e))
11093 ;; automatically assign a character.
11094 (setq c1 (string-to-char
11095 (downcase (substring
11096 tg (if (= (string-to-char tg) ?@) 1 0)))))
11097 (if (or (rassoc c1 ntable) (rassoc c1 table))
11098 (while (or (rassoc char ntable) (rassoc char table))
11099 (setq char (1+ char)))
11100 (setq c2 c1))
11101 (setq c (or c2 char)))
11102 (if ingroup (push tg (car groups)))
11103 (setq tg (org-add-props tg nil 'face
11104 (cond
11105 ((not (assoc tg table))
11106 (org-get-todo-face tg))
11107 ((member tg current) c-face)
11108 ((member tg inherited) i-face)
11109 (t nil))))
11110 (if (and (= cnt 0) (not ingroup)) (insert " "))
11111 (insert "[" c "] " tg (make-string
11112 (- fwidth 4 (length tg)) ?\ ))
11113 (push (cons tg c) ntable)
11114 (when (= (setq cnt (1+ cnt)) ncol)
11115 (insert "\n")
11116 (if ingroup (insert " "))
11117 (setq cnt 0)))))
11118 (setq ntable (nreverse ntable))
11119 (insert "\n")
11120 (goto-char (point-min))
11121 (if (not expert) (org-fit-window-to-buffer))
11122 (setq rtn
11123 (catch 'exit
11124 (while t
11125 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11126 (if groups " [!] no groups" " [!]groups")
11127 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11128 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11129 (cond
11130 ((= c ?\r) (throw 'exit t))
11131 ((= c ?!)
11132 (setq groups (not groups))
11133 (goto-char (point-min))
11134 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11135 ((= c ?\C-c)
11136 (if (not expert)
11137 (org-fast-tag-show-exit
11138 (setq exit-after-next (not exit-after-next)))
11139 (setq expert nil)
11140 (delete-other-windows)
11141 (split-window-vertically)
11142 (org-switch-to-buffer-other-window " *Org tags*")
11143 (org-fit-window-to-buffer)))
11144 ((or (= c ?\C-g)
11145 (and (= c ?q) (not (rassoc c ntable))))
11146 (org-detach-overlay org-tags-overlay)
11147 (setq quit-flag t))
11148 ((= c ?\ )
11149 (setq current nil)
11150 (if exit-after-next (setq exit-after-next 'now)))
11151 ((= c ?\t)
11152 (condition-case nil
11153 (setq tg (org-ido-completing-read
11154 "Tag: "
11155 (or buffer-tags
11156 (with-current-buffer buf
11157 (org-get-buffer-tags)))))
11158 (quit (setq tg "")))
11159 (when (string-match "\\S-" tg)
11160 (add-to-list 'buffer-tags (list tg))
11161 (if (member tg current)
11162 (setq current (delete tg current))
11163 (push tg current)))
11164 (if exit-after-next (setq exit-after-next 'now)))
11165 ((setq e (rassoc c todo-table) tg (car e))
11166 (with-current-buffer buf
11167 (save-excursion (org-todo tg)))
11168 (if exit-after-next (setq exit-after-next 'now)))
11169 ((setq e (rassoc c ntable) tg (car e))
11170 (if (member tg current)
11171 (setq current (delete tg current))
11172 (loop for g in groups do
11173 (if (member tg g)
11174 (mapc (lambda (x)
11175 (setq current (delete x current)))
11176 g)))
11177 (push tg current))
11178 (if exit-after-next (setq exit-after-next 'now))))
11180 ;; Create a sorted list
11181 (setq current
11182 (sort current
11183 (lambda (a b)
11184 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11185 (if (eq exit-after-next 'now) (throw 'exit t))
11186 (goto-char (point-min))
11187 (beginning-of-line 2)
11188 (delete-region (point) (point-at-eol))
11189 (org-fast-tag-insert "Current" current c-face)
11190 (org-set-current-tags-overlay current ov-prefix)
11191 (while (re-search-forward
11192 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11193 (setq tg (match-string 1))
11194 (add-text-properties
11195 (match-beginning 1) (match-end 1)
11196 (list 'face
11197 (cond
11198 ((member tg current) c-face)
11199 ((member tg inherited) i-face)
11200 (t (get-text-property (match-beginning 1) 'face))))))
11201 (goto-char (point-min)))))
11202 (org-detach-overlay org-tags-overlay)
11203 (if rtn
11204 (mapconcat 'identity current ":")
11205 nil))))
11207 (defun org-get-tags-string ()
11208 "Get the TAGS string in the current headline."
11209 (unless (org-on-heading-p t)
11210 (error "Not on a heading"))
11211 (save-excursion
11212 (beginning-of-line 1)
11213 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11214 (org-match-string-no-properties 1)
11215 "")))
11217 (defun org-get-tags ()
11218 "Get the list of tags specified in the current headline."
11219 (org-split-string (org-get-tags-string) ":"))
11221 (defun org-get-buffer-tags ()
11222 "Get a table of all tags used in the buffer, for completion."
11223 (let (tags)
11224 (save-excursion
11225 (goto-char (point-min))
11226 (while (re-search-forward
11227 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11228 (when (equal (char-after (point-at-bol 0)) ?*)
11229 (mapc (lambda (x) (add-to-list 'tags x))
11230 (org-split-string (org-match-string-no-properties 1) ":")))))
11231 (mapcar 'list tags)))
11233 ;;;; The mapping API
11235 ;;;###autoload
11236 (defun org-map-entries (func &optional match scope &rest skip)
11237 "Call FUNC at each headline selected by MATCH in SCOPE.
11239 FUNC is a function or a lisp form. The function will be called without
11240 arguments, with the cursor positioned at the beginning of the headline.
11241 The return values of all calls to the function will be collected and
11242 returned as a list.
11244 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11245 does not need to preserve point. After evaluaton, the cursor will be
11246 moved to the end of the line (presumably of the headline of the
11247 processed entry) and search continues from there. Under some
11248 circumstances, this may not produce the wanted results. For example,
11249 if you have removed (e.g. archived) the current (sub)tree it could
11250 mean that the next entry will be skipped entirely. In such cases, you
11251 can specify the position from where search should continue by making
11252 FUNC set the variable `org-map-continue-from' to the desired buffer
11253 position.
11255 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11256 Only headlines that are matched by this query will be considered during
11257 the iteration. When MATCH is nil or t, all headlines will be
11258 visited by the iteration.
11260 SCOPE determines the scope of this command. It can be any of:
11262 nil The current buffer, respecting the restriction if any
11263 tree The subtree started with the entry at point
11264 file The current buffer, without restriction
11265 file-with-archives
11266 The current buffer, and any archives associated with it
11267 agenda All agenda files
11268 agenda-with-archives
11269 All agenda files with any archive files associated with them
11270 \(file1 file2 ...)
11271 If this is a list, all files in the list will be scanned
11273 The remaining args are treated as settings for the skipping facilities of
11274 the scanner. The following items can be given here:
11276 archive skip trees with the archive tag.
11277 comment skip trees with the COMMENT keyword
11278 function or Emacs Lisp form:
11279 will be used as value for `org-agenda-skip-function', so whenever
11280 the the function returns t, FUNC will not be called for that
11281 entry and search will continue from the point where the
11282 function leaves it.
11284 If your function needs to retrieve the tags including inherited tags
11285 at the *current* entry, you can use the value of the variable
11286 `org-scanner-tags' which will be much faster than getting the value
11287 with `org-get-tags-at'. If your function gets properties with
11288 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11289 to t around the call to `org-entry-properties' to get the same speedup.
11290 Note that if your function moves around to retrieve tags and properties at
11291 a *different* entry, you cannot use these techniques."
11292 (let* ((org-agenda-archives-mode nil) ; just to make sure
11293 (org-agenda-skip-archived-trees (memq 'archive skip))
11294 (org-agenda-skip-comment-trees (memq 'comment skip))
11295 (org-agenda-skip-function
11296 (car (org-delete-all '(comment archive) skip)))
11297 (org-tags-match-list-sublevels t)
11298 matcher file res
11299 org-todo-keywords-for-agenda
11300 org-done-keywords-for-agenda
11301 org-todo-keyword-alist-for-agenda
11302 org-tag-alist-for-agenda)
11304 (cond
11305 ((eq match t) (setq matcher t))
11306 ((eq match nil) (setq matcher t))
11307 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11309 (save-excursion
11310 (save-restriction
11311 (when (eq scope 'tree)
11312 (org-back-to-heading t)
11313 (org-narrow-to-subtree)
11314 (setq scope nil))
11316 (if (not scope)
11317 (progn
11318 (org-prepare-agenda-buffers
11319 (list (buffer-file-name (current-buffer))))
11320 (setq res (org-scan-tags func matcher)))
11321 ;; Get the right scope
11322 (cond
11323 ((and scope (listp scope) (symbolp (car scope)))
11324 (setq scope (eval scope)))
11325 ((eq scope 'agenda)
11326 (setq scope (org-agenda-files t)))
11327 ((eq scope 'agenda-with-archives)
11328 (setq scope (org-agenda-files t))
11329 (setq scope (org-add-archive-files scope)))
11330 ((eq scope 'file)
11331 (setq scope (list (buffer-file-name))))
11332 ((eq scope 'file-with-archives)
11333 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11334 (org-prepare-agenda-buffers scope)
11335 (while (setq file (pop scope))
11336 (with-current-buffer (org-find-base-buffer-visiting file)
11337 (save-excursion
11338 (save-restriction
11339 (widen)
11340 (goto-char (point-min))
11341 (setq res (append res (org-scan-tags func matcher))))))))))
11342 res))
11344 ;;;; Properties
11346 ;;; Setting and retrieving properties
11348 (defconst org-special-properties
11349 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11350 "TIMESTAMP" "TIMESTAMP_IA")
11351 "The special properties valid in Org-mode.
11353 These are properties that are not defined in the property drawer,
11354 but in some other way.")
11356 (defconst org-default-properties
11357 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11358 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11359 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11360 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11361 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11362 "CLOCK_MODELINE_TOTAL")
11363 "Some properties that are used by Org-mode for various purposes.
11364 Being in this list makes sure that they are offered for completion.")
11366 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11367 "Regular expression matching the first line of a property drawer.")
11369 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11370 "Regular expression matching the first line of a property drawer.")
11372 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11373 "Regular expression matching the first line of a property drawer.")
11375 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11376 "Regular expression matching the first line of a property drawer.")
11378 (defconst org-property-drawer-re
11379 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11380 org-property-end-re "\\)\n?")
11381 "Matches an entire property drawer.")
11383 (defconst org-clock-drawer-re
11384 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11385 org-property-end-re "\\)\n?")
11386 "Matches an entire clock drawer.")
11388 (defun org-property-action ()
11389 "Do an action on properties."
11390 (interactive)
11391 (let (c)
11392 (org-at-property-p)
11393 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11394 (setq c (read-char-exclusive))
11395 (cond
11396 ((equal c ?s)
11397 (call-interactively 'org-set-property))
11398 ((equal c ?d)
11399 (call-interactively 'org-delete-property))
11400 ((equal c ?D)
11401 (call-interactively 'org-delete-property-globally))
11402 ((equal c ?c)
11403 (call-interactively 'org-compute-property-at-point))
11404 (t (error "No such property action %c" c)))))
11406 (defun org-at-property-p ()
11407 "Is the cursor in a property line?"
11408 ;; FIXME: Does not check if we are actually in the drawer.
11409 ;; FIXME: also returns true on any drawers.....
11410 ;; This is used by C-c C-c for property action.
11411 (save-excursion
11412 (beginning-of-line 1)
11413 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11415 (defun org-get-property-block (&optional beg end force)
11416 "Return the (beg . end) range of the body of the property drawer.
11417 BEG and END can be beginning and end of subtree, if not given
11418 they will be found.
11419 If the drawer does not exist and FORCE is non-nil, create the drawer."
11420 (catch 'exit
11421 (save-excursion
11422 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11423 (end (or end (progn (outline-next-heading) (point)))))
11424 (goto-char beg)
11425 (if (re-search-forward org-property-start-re end t)
11426 (setq beg (1+ (match-end 0)))
11427 (if force
11428 (save-excursion
11429 (org-insert-property-drawer)
11430 (setq end (progn (outline-next-heading) (point))))
11431 (throw 'exit nil))
11432 (goto-char beg)
11433 (if (re-search-forward org-property-start-re end t)
11434 (setq beg (1+ (match-end 0)))))
11435 (if (re-search-forward org-property-end-re end t)
11436 (setq end (match-beginning 0))
11437 (or force (throw 'exit nil))
11438 (goto-char beg)
11439 (setq end beg)
11440 (org-indent-line-function)
11441 (insert ":END:\n"))
11442 (cons beg end)))))
11444 (defun org-entry-properties (&optional pom which)
11445 "Get all properties of the entry at point-or-marker POM.
11446 This includes the TODO keyword, the tags, time strings for deadline,
11447 scheduled, and clocking, and any additional properties defined in the
11448 entry. The return value is an alist, keys may occur multiple times
11449 if the property key was used several times.
11450 POM may also be nil, in which case the current entry is used.
11451 If WHICH is nil or `all', get all properties. If WHICH is
11452 `special' or `standard', only get that subclass."
11453 (setq which (or which 'all))
11454 (org-with-point-at pom
11455 (let ((clockstr (substring org-clock-string 0 -1))
11456 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11457 beg end range props sum-props key value string clocksum)
11458 (save-excursion
11459 (when (condition-case nil
11460 (and (org-mode-p) (org-back-to-heading t))
11461 (error nil))
11462 (setq beg (point))
11463 (setq sum-props (get-text-property (point) 'org-summaries))
11464 (setq clocksum (get-text-property (point) :org-clock-minutes))
11465 (outline-next-heading)
11466 (setq end (point))
11467 (when (memq which '(all special))
11468 ;; Get the special properties, like TODO and tags
11469 (goto-char beg)
11470 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11471 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11472 (when (looking-at org-priority-regexp)
11473 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11474 (when (and (setq value (org-get-tags-string))
11475 (string-match "\\S-" value))
11476 (push (cons "TAGS" value) props))
11477 (when (setq value (org-get-tags-at))
11478 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11479 props))
11480 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11481 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11482 string (if (equal key clockstr)
11483 (org-no-properties
11484 (org-trim
11485 (buffer-substring
11486 (match-beginning 3) (goto-char (point-at-eol)))))
11487 (substring (org-match-string-no-properties 3) 1 -1)))
11488 (unless key
11489 (if (= (char-after (match-beginning 3)) ?\[)
11490 (setq key "TIMESTAMP_IA")
11491 (setq key "TIMESTAMP")))
11492 (when (or (equal key clockstr) (not (assoc key props)))
11493 (push (cons key string) props)))
11497 (when (memq which '(all standard))
11498 ;; Get the standard properties, like :PROP: ...
11499 (setq range (org-get-property-block beg end))
11500 (when range
11501 (goto-char (car range))
11502 (while (re-search-forward
11503 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11504 (cdr range) t)
11505 (setq key (org-match-string-no-properties 1)
11506 value (org-trim (or (org-match-string-no-properties 2) "")))
11507 (unless (member key excluded)
11508 (push (cons key (or value "")) props)))))
11509 (if clocksum
11510 (push (cons "CLOCKSUM"
11511 (org-columns-number-to-string (/ (float clocksum) 60.)
11512 'add_times))
11513 props))
11514 (unless (assoc "CATEGORY" props)
11515 (setq value (or (org-get-category)
11516 (progn (org-refresh-category-properties)
11517 (org-get-category))))
11518 (push (cons "CATEGORY" value) props))
11519 (append sum-props (nreverse props)))))))
11521 (defun org-entry-get (pom property &optional inherit)
11522 "Get value of PROPERTY for entry at point-or-marker POM.
11523 If INHERIT is non-nil and the entry does not have the property,
11524 then also check higher levels of the hierarchy.
11525 If INHERIT is the symbol `selective', use inheritance only if the setting
11526 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11527 If the property is present but empty, the return value is the empty string.
11528 If the property is not present at all, nil is returned."
11529 (org-with-point-at pom
11530 (if (and inherit (if (eq inherit 'selective)
11531 (org-property-inherit-p property)
11533 (org-entry-get-with-inheritance property)
11534 (if (member property org-special-properties)
11535 ;; We need a special property. Use brute force, get all properties.
11536 (cdr (assoc property (org-entry-properties nil 'special)))
11537 (let ((range (org-get-property-block)))
11538 (if (and range
11539 (goto-char (car range))
11540 (re-search-forward
11541 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11542 (cdr range) t))
11543 ;; Found the property, return it.
11544 (if (match-end 1)
11545 (org-match-string-no-properties 1)
11546 "")))))))
11548 (defun org-property-or-variable-value (var &optional inherit)
11549 "Check if there is a property fixing the value of VAR.
11550 If yes, return this value. If not, return the current value of the variable."
11551 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11552 (if (and prop (stringp prop) (string-match "\\S-" prop))
11553 (read prop)
11554 (symbol-value var))))
11556 (defun org-entry-delete (pom property)
11557 "Delete the property PROPERTY from entry at point-or-marker POM."
11558 (org-with-point-at pom
11559 (if (member property org-special-properties)
11560 nil ; cannot delete these properties.
11561 (let ((range (org-get-property-block)))
11562 (if (and range
11563 (goto-char (car range))
11564 (re-search-forward
11565 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11566 (cdr range) t))
11567 (progn
11568 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11570 nil)))))
11572 ;; Multi-values properties are properties that contain multiple values
11573 ;; These values are assumed to be single words, separated by whitespace.
11574 (defun org-entry-add-to-multivalued-property (pom property value)
11575 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11576 (let* ((old (org-entry-get pom property))
11577 (values (and old (org-split-string old "[ \t]"))))
11578 (setq value (org-entry-protect-space value))
11579 (unless (member value values)
11580 (setq values (cons value values))
11581 (org-entry-put pom property
11582 (mapconcat 'identity values " ")))))
11584 (defun org-entry-remove-from-multivalued-property (pom property value)
11585 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11586 (let* ((old (org-entry-get pom property))
11587 (values (and old (org-split-string old "[ \t]"))))
11588 (setq value (org-entry-protect-space value))
11589 (when (member value values)
11590 (setq values (delete value values))
11591 (org-entry-put pom property
11592 (mapconcat 'identity values " ")))))
11594 (defun org-entry-member-in-multivalued-property (pom property value)
11595 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11596 (let* ((old (org-entry-get pom property))
11597 (values (and old (org-split-string old "[ \t]"))))
11598 (setq value (org-entry-protect-space value))
11599 (member value values)))
11601 (defun org-entry-get-multivalued-property (pom property)
11602 "Return a list of values in a multivalued property."
11603 (let* ((value (org-entry-get pom property))
11604 (values (and value (org-split-string value "[ \t]"))))
11605 (mapcar 'org-entry-restore-space values)))
11607 (defun org-entry-put-multivalued-property (pom property &rest values)
11608 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11609 VALUES should be a list of strings. Spaces will be protected."
11610 (org-entry-put pom property
11611 (mapconcat 'org-entry-protect-space values " "))
11612 (let* ((value (org-entry-get pom property))
11613 (values (and value (org-split-string value "[ \t]"))))
11614 (mapcar 'org-entry-restore-space values)))
11616 (defun org-entry-protect-space (s)
11617 "Protect spaces and newline in string S."
11618 (while (string-match " " s)
11619 (setq s (replace-match "%20" t t s)))
11620 (while (string-match "\n" s)
11621 (setq s (replace-match "%0A" t t s)))
11624 (defun org-entry-restore-space (s)
11625 "Restore spaces and newline in string S."
11626 (while (string-match "%20" s)
11627 (setq s (replace-match " " t t s)))
11628 (while (string-match "%0A" s)
11629 (setq s (replace-match "\n" t t s)))
11632 (defvar org-entry-property-inherited-from (make-marker)
11633 "Marker pointing to the entry from where a property was inherited.
11634 Each call to `org-entry-get-with-inheritance' will set this marker to the
11635 location of the entry where the inheritance search matched. If there was
11636 no match, the marker will point nowhere.
11637 Note that also `org-entry-get' calls this function, if the INHERIT flag
11638 is set.")
11640 (defun org-entry-get-with-inheritance (property)
11641 "Get entry property, and search higher levels if not present."
11642 (move-marker org-entry-property-inherited-from nil)
11643 (let (tmp)
11644 (save-excursion
11645 (save-restriction
11646 (widen)
11647 (catch 'ex
11648 (while t
11649 (when (setq tmp (org-entry-get nil property))
11650 (org-back-to-heading t)
11651 (move-marker org-entry-property-inherited-from (point))
11652 (throw 'ex tmp))
11653 (or (org-up-heading-safe) (throw 'ex nil)))))
11654 (or tmp
11655 (cdr (assoc property org-file-properties))
11656 (cdr (assoc property org-global-properties))
11657 (cdr (assoc property org-global-properties-fixed))))))
11659 (defun org-entry-put (pom property value)
11660 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11661 (org-with-point-at pom
11662 (org-back-to-heading t)
11663 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11664 range)
11665 (cond
11666 ((equal property "TODO")
11667 (when (and (stringp value) (string-match "\\S-" value)
11668 (not (member value org-todo-keywords-1)))
11669 (error "\"%s\" is not a valid TODO state" value))
11670 (if (or (not value)
11671 (not (string-match "\\S-" value)))
11672 (setq value 'none))
11673 (org-todo value)
11674 (org-set-tags nil 'align))
11675 ((equal property "PRIORITY")
11676 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11677 (string-to-char value) ?\ ))
11678 (org-set-tags nil 'align))
11679 ((equal property "SCHEDULED")
11680 (if (re-search-forward org-scheduled-time-regexp end t)
11681 (cond
11682 ((eq value 'earlier) (org-timestamp-change -1 'day))
11683 ((eq value 'later) (org-timestamp-change 1 'day))
11684 (t (call-interactively 'org-schedule)))
11685 (call-interactively 'org-schedule)))
11686 ((equal property "DEADLINE")
11687 (if (re-search-forward org-deadline-time-regexp end t)
11688 (cond
11689 ((eq value 'earlier) (org-timestamp-change -1 'day))
11690 ((eq value 'later) (org-timestamp-change 1 'day))
11691 (t (call-interactively 'org-deadline)))
11692 (call-interactively 'org-deadline)))
11693 ((member property org-special-properties)
11694 (error "The %s property can not yet be set with `org-entry-put'"
11695 property))
11696 (t ; a non-special property
11697 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11698 (setq range (org-get-property-block beg end 'force))
11699 (goto-char (car range))
11700 (if (re-search-forward
11701 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11702 (progn
11703 (delete-region (match-beginning 1) (match-end 1))
11704 (goto-char (match-beginning 1)))
11705 (goto-char (cdr range))
11706 (insert "\n")
11707 (backward-char 1)
11708 (org-indent-line-function)
11709 (insert ":" property ":"))
11710 (and value (insert " " value))
11711 (org-indent-line-function)))))))
11713 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11714 "Get all property keys in the current buffer.
11715 With INCLUDE-SPECIALS, also list the special properties that reflect things
11716 like tags and TODO state.
11717 With INCLUDE-DEFAULTS, also include properties that has special meaning
11718 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11719 With INCLUDE-COLUMNS, also include property names given in COLUMN
11720 formats in the current buffer."
11721 (let (rtn range cfmt s p)
11722 (save-excursion
11723 (save-restriction
11724 (widen)
11725 (goto-char (point-min))
11726 (while (re-search-forward org-property-start-re nil t)
11727 (setq range (org-get-property-block))
11728 (goto-char (car range))
11729 (while (re-search-forward
11730 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11731 (cdr range) t)
11732 (add-to-list 'rtn (org-match-string-no-properties 1)))
11733 (outline-next-heading))))
11735 (when include-specials
11736 (setq rtn (append org-special-properties rtn)))
11738 (when include-defaults
11739 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
11740 (add-to-list 'rtn org-effort-property))
11742 (when include-columns
11743 (save-excursion
11744 (save-restriction
11745 (widen)
11746 (goto-char (point-min))
11747 (while (re-search-forward
11748 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11749 nil t)
11750 (setq cfmt (match-string 2) s 0)
11751 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11752 cfmt s)
11753 (setq s (match-end 0)
11754 p (match-string 1 cfmt))
11755 (unless (or (equal p "ITEM")
11756 (member p org-special-properties))
11757 (add-to-list 'rtn (match-string 1 cfmt))))))))
11759 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11761 (defun org-property-values (key)
11762 "Return a list of all values of property KEY."
11763 (save-excursion
11764 (save-restriction
11765 (widen)
11766 (goto-char (point-min))
11767 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11768 values)
11769 (while (re-search-forward re nil t)
11770 (add-to-list 'values (org-trim (match-string 1))))
11771 (delete "" values)))))
11773 (defun org-insert-property-drawer ()
11774 "Insert a property drawer into the current entry."
11775 (interactive)
11776 (org-back-to-heading t)
11777 (looking-at outline-regexp)
11778 (let ((indent (if org-adapt-indentation
11779 (- (match-end 0)(match-beginning 0))
11781 (beg (point))
11782 (re (concat "^[ \t]*" org-keyword-time-regexp))
11783 end hiddenp)
11784 (outline-next-heading)
11785 (setq end (point))
11786 (goto-char beg)
11787 (while (re-search-forward re end t))
11788 (setq hiddenp (org-invisible-p))
11789 (end-of-line 1)
11790 (and (equal (char-after) ?\n) (forward-char 1))
11791 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11792 (if (member (match-string 1) '("CLOCK:" ":END:"))
11793 ;; just skip this line
11794 (beginning-of-line 2)
11795 ;; Drawer start, find the end
11796 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11797 (beginning-of-line 1)))
11798 (org-skip-over-state-notes)
11799 (skip-chars-backward " \t\n\r")
11800 (if (eq (char-before) ?*) (forward-char 1))
11801 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11802 (beginning-of-line 0)
11803 (org-indent-to-column indent)
11804 (beginning-of-line 2)
11805 (org-indent-to-column indent)
11806 (beginning-of-line 0)
11807 (if hiddenp
11808 (save-excursion
11809 (org-back-to-heading t)
11810 (hide-entry))
11811 (org-flag-drawer t))))
11813 (defun org-set-property (property value)
11814 "In the current entry, set PROPERTY to VALUE.
11815 When called interactively, this will prompt for a property name, offering
11816 completion on existing and default properties. And then it will prompt
11817 for a value, offering completion either on allowed values (via an inherited
11818 xxx_ALL property) or on existing values in other instances of this property
11819 in the current file."
11820 (interactive
11821 (let* ((completion-ignore-case t)
11822 (keys (org-buffer-property-keys nil t t))
11823 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11824 (prop (if (member prop0 keys)
11825 prop0
11826 (or (cdr (assoc (downcase prop0)
11827 (mapcar (lambda (x) (cons (downcase x) x))
11828 keys)))
11829 prop0)))
11830 (cur (org-entry-get nil prop))
11831 (allowed (org-property-get-allowed-values nil prop 'table))
11832 (existing (mapcar 'list (org-property-values prop)))
11833 (val (if allowed
11834 (org-completing-read "Value: " allowed nil 'req-match)
11835 (let (org-completion-use-ido)
11836 (org-completing-read
11837 (concat "Value" (if (and cur (string-match "\\S-" cur))
11838 (concat "[" cur "]") "")
11839 ": ")
11840 existing nil nil "" nil cur)))))
11841 (list prop (if (equal val "") cur val))))
11842 (unless (equal (org-entry-get nil property) value)
11843 (org-entry-put nil property value)))
11845 (defun org-delete-property (property)
11846 "In the current entry, delete PROPERTY."
11847 (interactive
11848 (let* ((completion-ignore-case t)
11849 (prop (org-ido-completing-read
11850 "Property: " (org-entry-properties nil 'standard))))
11851 (list prop)))
11852 (message "Property %s %s" property
11853 (if (org-entry-delete nil property)
11854 "deleted"
11855 "was not present in the entry")))
11857 (defun org-delete-property-globally (property)
11858 "Remove PROPERTY globally, from all entries."
11859 (interactive
11860 (let* ((completion-ignore-case t)
11861 (prop (org-ido-completing-read
11862 "Globally remove property: "
11863 (mapcar 'list (org-buffer-property-keys)))))
11864 (list prop)))
11865 (save-excursion
11866 (save-restriction
11867 (widen)
11868 (goto-char (point-min))
11869 (let ((cnt 0))
11870 (while (re-search-forward
11871 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11872 nil t)
11873 (setq cnt (1+ cnt))
11874 (replace-match ""))
11875 (message "Property \"%s\" removed from %d entries" property cnt)))))
11877 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11879 (defun org-compute-property-at-point ()
11880 "Compute the property at point.
11881 This looks for an enclosing column format, extracts the operator and
11882 then applies it to the property in the column format's scope."
11883 (interactive)
11884 (unless (org-at-property-p)
11885 (error "Not at a property"))
11886 (let ((prop (org-match-string-no-properties 2)))
11887 (org-columns-get-format-and-top-level)
11888 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11889 (error "No operator defined for property %s" prop))
11890 (org-columns-compute prop)))
11892 (defun org-property-get-allowed-values (pom property &optional table)
11893 "Get allowed values for the property PROPERTY.
11894 When TABLE is non-nil, return an alist that can directly be used for
11895 completion."
11896 (let (vals)
11897 (cond
11898 ((equal property "TODO")
11899 (setq vals (org-with-point-at pom
11900 (append org-todo-keywords-1 '("")))))
11901 ((equal property "PRIORITY")
11902 (let ((n org-lowest-priority))
11903 (while (>= n org-highest-priority)
11904 (push (char-to-string n) vals)
11905 (setq n (1- n)))))
11906 ((member property org-special-properties))
11908 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11910 (when (and vals (string-match "\\S-" vals))
11911 (setq vals (car (read-from-string (concat "(" vals ")"))))
11912 (setq vals (mapcar (lambda (x)
11913 (cond ((stringp x) x)
11914 ((numberp x) (number-to-string x))
11915 ((symbolp x) (symbol-name x))
11916 (t "???")))
11917 vals)))))
11918 (if table (mapcar 'list vals) vals)))
11920 (defun org-property-previous-allowed-value (&optional previous)
11921 "Switch to the next allowed value for this property."
11922 (interactive)
11923 (org-property-next-allowed-value t))
11925 (defun org-property-next-allowed-value (&optional previous)
11926 "Switch to the next allowed value for this property."
11927 (interactive)
11928 (unless (org-at-property-p)
11929 (error "Not at a property"))
11930 (let* ((key (match-string 2))
11931 (value (match-string 3))
11932 (allowed (or (org-property-get-allowed-values (point) key)
11933 (and (member value '("[ ]" "[-]" "[X]"))
11934 '("[ ]" "[X]"))))
11935 nval)
11936 (unless allowed
11937 (error "Allowed values for this property have not been defined"))
11938 (if previous (setq allowed (reverse allowed)))
11939 (if (member value allowed)
11940 (setq nval (car (cdr (member value allowed)))))
11941 (setq nval (or nval (car allowed)))
11942 (if (equal nval value)
11943 (error "Only one allowed value for this property"))
11944 (org-at-property-p)
11945 (replace-match (concat " :" key ": " nval) t t)
11946 (org-indent-line-function)
11947 (beginning-of-line 1)
11948 (skip-chars-forward " \t")))
11950 (defun org-find-entry-with-id (ident)
11951 "Locate the entry that contains the ID property with exact value IDENT.
11952 IDENT can be a string, a symbol or a number, this function will search for
11953 the string representation of it.
11954 Return the position where this entry starts, or nil if there is no such entry."
11955 (interactive "sID: ")
11956 (let ((id (cond
11957 ((stringp ident) ident)
11958 ((symbol-name ident) (symbol-name ident))
11959 ((numberp ident) (number-to-string ident))
11960 (t (error "IDENT %s must be a string, symbol or number" ident))))
11961 (case-fold-search nil))
11962 (save-excursion
11963 (save-restriction
11964 (widen)
11965 (goto-char (point-min))
11966 (when (re-search-forward
11967 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11968 nil t)
11969 (org-back-to-heading t)
11970 (point))))))
11972 ;;;; Timestamps
11974 (defvar org-last-changed-timestamp nil)
11975 (defvar org-last-inserted-timestamp nil
11976 "The last time stamp inserted with `org-insert-time-stamp'.")
11977 (defvar org-time-was-given) ; dynamically scoped parameter
11978 (defvar org-end-time-was-given) ; dynamically scoped parameter
11979 (defvar org-ts-what) ; dynamically scoped parameter
11981 (defun org-time-stamp (arg &optional inactive)
11982 "Prompt for a date/time and insert a time stamp.
11983 If the user specifies a time like HH:MM, or if this command is called
11984 with a prefix argument, the time stamp will contain date and time.
11985 Otherwise, only the date will be included. All parts of a date not
11986 specified by the user will be filled in from the current date/time.
11987 So if you press just return without typing anything, the time stamp
11988 will represent the current date/time. If there is already a timestamp
11989 at the cursor, it will be modified."
11990 (interactive "P")
11991 (let* ((ts nil)
11992 (default-time
11993 ;; Default time is either today, or, when entering a range,
11994 ;; the range start.
11995 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11996 (save-excursion
11997 (re-search-backward
11998 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11999 (- (point) 20) t)))
12000 (apply 'encode-time (org-parse-time-string (match-string 1)))
12001 (current-time)))
12002 (default-input (and ts (org-get-compact-tod ts)))
12003 org-time-was-given org-end-time-was-given time)
12004 (cond
12005 ((and (org-at-timestamp-p t)
12006 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12007 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12008 (insert "--")
12009 (setq time (let ((this-command this-command))
12010 (org-read-date arg 'totime nil nil
12011 default-time default-input)))
12012 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12013 ((org-at-timestamp-p t)
12014 (setq time (let ((this-command this-command))
12015 (org-read-date arg 'totime nil nil default-time default-input)))
12016 (when (org-at-timestamp-p t) ; just to get the match data
12017 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12018 (replace-match "")
12019 (setq org-last-changed-timestamp
12020 (org-insert-time-stamp
12021 time (or org-time-was-given arg)
12022 inactive nil nil (list org-end-time-was-given))))
12023 (message "Timestamp updated"))
12025 (setq time (let ((this-command this-command))
12026 (org-read-date arg 'totime nil nil default-time default-input)))
12027 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12028 nil nil (list org-end-time-was-given))))))
12030 ;; FIXME: can we use this for something else, like computing time differences?
12031 (defun org-get-compact-tod (s)
12032 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12033 (let* ((t1 (match-string 1 s))
12034 (h1 (string-to-number (match-string 2 s)))
12035 (m1 (string-to-number (match-string 3 s)))
12036 (t2 (and (match-end 4) (match-string 5 s)))
12037 (h2 (and t2 (string-to-number (match-string 6 s))))
12038 (m2 (and t2 (string-to-number (match-string 7 s))))
12039 dh dm)
12040 (if (not t2)
12042 (setq dh (- h2 h1) dm (- m2 m1))
12043 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12044 (concat t1 "+" (number-to-string dh)
12045 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12047 (defun org-time-stamp-inactive (&optional arg)
12048 "Insert an inactive time stamp.
12049 An inactive time stamp is enclosed in square brackets instead of angle
12050 brackets. It is inactive in the sense that it does not trigger agenda entries,
12051 does not link to the calendar and cannot be changed with the S-cursor keys.
12052 So these are more for recording a certain time/date."
12053 (interactive "P")
12054 (org-time-stamp arg 'inactive))
12056 (defvar org-date-ovl (org-make-overlay 1 1))
12057 (org-overlay-put org-date-ovl 'face 'org-warning)
12058 (org-detach-overlay org-date-ovl)
12060 (defvar org-ans1) ; dynamically scoped parameter
12061 (defvar org-ans2) ; dynamically scoped parameter
12063 (defvar org-plain-time-of-day-regexp) ; defined below
12065 (defvar org-overriding-default-time nil) ; dynamically scoped
12066 (defvar org-read-date-overlay nil)
12067 (defvar org-dcst nil) ; dynamically scoped
12068 (defvar org-read-date-history nil)
12069 (defvar org-read-date-final-answer nil)
12071 (defun org-read-date (&optional with-time to-time from-string prompt
12072 default-time default-input)
12073 "Read a date, possibly a time, and make things smooth for the user.
12074 The prompt will suggest to enter an ISO date, but you can also enter anything
12075 which will at least partially be understood by `parse-time-string'.
12076 Unrecognized parts of the date will default to the current day, month, year,
12077 hour and minute. If this command is called to replace a timestamp at point,
12078 of to enter the second timestamp of a range, the default time is taken from the
12079 existing stamp. For example,
12080 3-2-5 --> 2003-02-05
12081 feb 15 --> currentyear-02-15
12082 sep 12 9 --> 2009-09-12
12083 12:45 --> today 12:45
12084 22 sept 0:34 --> currentyear-09-22 0:34
12085 12 --> currentyear-currentmonth-12
12086 Fri --> nearest Friday (today or later)
12087 etc.
12089 Furthermore you can specify a relative date by giving, as the *first* thing
12090 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12091 change in days weeks, months, years.
12092 With a single plus or minus, the date is relative to today. With a double
12093 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12094 +4d --> four days from today
12095 +4 --> same as above
12096 +2w --> two weeks from today
12097 ++5 --> five days from default date
12099 The function understands only English month and weekday abbreviations,
12100 but this can be configured with the variables `parse-time-months' and
12101 `parse-time-weekdays'.
12103 While prompting, a calendar is popped up - you can also select the
12104 date with the mouse (button 1). The calendar shows a period of three
12105 months. To scroll it to other months, use the keys `>' and `<'.
12106 If you don't like the calendar, turn it off with
12107 \(setq org-read-date-popup-calendar nil)
12109 With optional argument TO-TIME, the date will immediately be converted
12110 to an internal time.
12111 With an optional argument WITH-TIME, the prompt will suggest to also
12112 insert a time. Note that when WITH-TIME is not set, you can still
12113 enter a time, and this function will inform the calling routine about
12114 this change. The calling routine may then choose to change the format
12115 used to insert the time stamp into the buffer to include the time.
12116 With optional argument FROM-STRING, read from this string instead from
12117 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12118 the time/date that is used for everything that is not specified by the
12119 user."
12120 (require 'parse-time)
12121 (let* ((org-time-stamp-rounding-minutes
12122 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12123 (org-dcst org-display-custom-times)
12124 (ct (org-current-time))
12125 (def (or org-overriding-default-time default-time ct))
12126 (defdecode (decode-time def))
12127 (dummy (progn
12128 (when (< (nth 2 defdecode) org-extend-today-until)
12129 (setcar (nthcdr 2 defdecode) -1)
12130 (setcar (nthcdr 1 defdecode) 59)
12131 (setq def (apply 'encode-time defdecode)
12132 defdecode (decode-time def)))))
12133 (calendar-move-hook nil)
12134 (calendar-view-diary-initially-flag nil)
12135 (view-diary-entries-initially nil)
12136 (calendar-view-holidays-initially-flag nil)
12137 (view-calendar-holidays-initially nil)
12138 (timestr (format-time-string
12139 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12140 (prompt (concat (if prompt (concat prompt " ") "")
12141 (format "Date+time [%s]: " timestr)))
12142 ans (org-ans0 "") org-ans1 org-ans2 final)
12144 (cond
12145 (from-string (setq ans from-string))
12146 (org-read-date-popup-calendar
12147 (save-excursion
12148 (save-window-excursion
12149 (calendar)
12150 (calendar-forward-day (- (time-to-days def)
12151 (calendar-absolute-from-gregorian
12152 (calendar-current-date))))
12153 (org-eval-in-calendar nil t)
12154 (let* ((old-map (current-local-map))
12155 (map (copy-keymap calendar-mode-map))
12156 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12157 (org-defkey map (kbd "RET") 'org-calendar-select)
12158 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12159 'org-calendar-select-mouse)
12160 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12161 'org-calendar-select-mouse)
12162 (org-defkey minibuffer-local-map [(meta shift left)]
12163 (lambda () (interactive)
12164 (org-eval-in-calendar '(calendar-backward-month 1))))
12165 (org-defkey minibuffer-local-map [(meta shift right)]
12166 (lambda () (interactive)
12167 (org-eval-in-calendar '(calendar-forward-month 1))))
12168 (org-defkey minibuffer-local-map [(meta shift up)]
12169 (lambda () (interactive)
12170 (org-eval-in-calendar '(calendar-backward-year 1))))
12171 (org-defkey minibuffer-local-map [(meta shift down)]
12172 (lambda () (interactive)
12173 (org-eval-in-calendar '(calendar-forward-year 1))))
12174 (org-defkey minibuffer-local-map [?\e (shift left)]
12175 (lambda () (interactive)
12176 (org-eval-in-calendar '(calendar-backward-month 1))))
12177 (org-defkey minibuffer-local-map [?\e (shift right)]
12178 (lambda () (interactive)
12179 (org-eval-in-calendar '(calendar-forward-month 1))))
12180 (org-defkey minibuffer-local-map [?\e (shift up)]
12181 (lambda () (interactive)
12182 (org-eval-in-calendar '(calendar-backward-year 1))))
12183 (org-defkey minibuffer-local-map [?\e (shift down)]
12184 (lambda () (interactive)
12185 (org-eval-in-calendar '(calendar-forward-year 1))))
12186 (org-defkey minibuffer-local-map [(shift up)]
12187 (lambda () (interactive)
12188 (org-eval-in-calendar '(calendar-backward-week 1))))
12189 (org-defkey minibuffer-local-map [(shift down)]
12190 (lambda () (interactive)
12191 (org-eval-in-calendar '(calendar-forward-week 1))))
12192 (org-defkey minibuffer-local-map [(shift left)]
12193 (lambda () (interactive)
12194 (org-eval-in-calendar '(calendar-backward-day 1))))
12195 (org-defkey minibuffer-local-map [(shift right)]
12196 (lambda () (interactive)
12197 (org-eval-in-calendar '(calendar-forward-day 1))))
12198 (org-defkey minibuffer-local-map ">"
12199 (lambda () (interactive)
12200 (org-eval-in-calendar '(scroll-calendar-left 1))))
12201 (org-defkey minibuffer-local-map "<"
12202 (lambda () (interactive)
12203 (org-eval-in-calendar '(scroll-calendar-right 1))))
12204 (run-hooks 'org-read-date-minibuffer-setup-hook)
12205 (unwind-protect
12206 (progn
12207 (use-local-map map)
12208 (add-hook 'post-command-hook 'org-read-date-display)
12209 (setq org-ans0 (read-string prompt default-input
12210 'org-read-date-history nil))
12211 ;; org-ans0: from prompt
12212 ;; org-ans1: from mouse click
12213 ;; org-ans2: from calendar motion
12214 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12215 (remove-hook 'post-command-hook 'org-read-date-display)
12216 (use-local-map old-map)
12217 (when org-read-date-overlay
12218 (org-delete-overlay org-read-date-overlay)
12219 (setq org-read-date-overlay nil)))))))
12221 (t ; Naked prompt only
12222 (unwind-protect
12223 (setq ans (read-string prompt default-input
12224 'org-read-date-history timestr))
12225 (when org-read-date-overlay
12226 (org-delete-overlay org-read-date-overlay)
12227 (setq org-read-date-overlay nil)))))
12229 (setq final (org-read-date-analyze ans def defdecode))
12230 (setq org-read-date-final-answer ans)
12232 (if to-time
12233 (apply 'encode-time final)
12234 (if (and (boundp 'org-time-was-given) org-time-was-given)
12235 (format "%04d-%02d-%02d %02d:%02d"
12236 (nth 5 final) (nth 4 final) (nth 3 final)
12237 (nth 2 final) (nth 1 final))
12238 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12239 (defvar def)
12240 (defvar defdecode)
12241 (defvar with-time)
12242 (defun org-read-date-display ()
12243 "Display the current date prompt interpretation in the minibuffer."
12244 (when org-read-date-display-live
12245 (when org-read-date-overlay
12246 (org-delete-overlay org-read-date-overlay))
12247 (let ((p (point)))
12248 (end-of-line 1)
12249 (while (not (equal (buffer-substring
12250 (max (point-min) (- (point) 4)) (point))
12251 " "))
12252 (insert " "))
12253 (goto-char p))
12254 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12255 " " (or org-ans1 org-ans2)))
12256 (org-end-time-was-given nil)
12257 (f (org-read-date-analyze ans def defdecode))
12258 (fmts (if org-dcst
12259 org-time-stamp-custom-formats
12260 org-time-stamp-formats))
12261 (fmt (if (or with-time
12262 (and (boundp 'org-time-was-given) org-time-was-given))
12263 (cdr fmts)
12264 (car fmts)))
12265 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12266 (when (and org-end-time-was-given
12267 (string-match org-plain-time-of-day-regexp txt))
12268 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12269 org-end-time-was-given
12270 (substring txt (match-end 0)))))
12271 (setq org-read-date-overlay
12272 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12273 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12275 (defun org-read-date-analyze (ans def defdecode)
12276 "Analyse the combined answer of the date prompt."
12277 ;; FIXME: cleanup and comment
12278 (let (delta deltan deltaw deltadef year month day
12279 hour minute second wday pm h2 m2 tl wday1
12280 iso-year iso-weekday iso-week iso-year iso-date)
12282 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12283 (setq ans "+0"))
12285 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12286 (setq ans (replace-match "" t t ans)
12287 deltan (car delta)
12288 deltaw (nth 1 delta)
12289 deltadef (nth 2 delta)))
12291 ;; Check if there is an iso week date in there
12292 ;; If yes, sore the info and postpone interpreting it until the rest
12293 ;; of the parsing is done
12294 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12295 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12296 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12297 iso-week (string-to-number (match-string 2 ans)))
12298 (setq ans (replace-match "" t t ans)))
12300 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12301 (when (string-match
12302 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12303 (setq year (if (match-end 2)
12304 (string-to-number (match-string 2 ans))
12305 (string-to-number (format-time-string "%Y")))
12306 month (string-to-number (match-string 3 ans))
12307 day (string-to-number (match-string 4 ans)))
12308 (if (< year 100) (setq year (+ 2000 year)))
12309 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12310 t nil ans)))
12311 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12312 ;; If there is a time with am/pm, and *no* time without it, we convert
12313 ;; so that matching will be successful.
12314 (loop for i from 1 to 2 do ; twice, for end time as well
12315 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12316 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12317 (setq hour (string-to-number (match-string 1 ans))
12318 minute (if (match-end 3)
12319 (string-to-number (match-string 3 ans))
12321 pm (equal ?p
12322 (string-to-char (downcase (match-string 4 ans)))))
12323 (if (and (= hour 12) (not pm))
12324 (setq hour 0)
12325 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12326 (setq ans (replace-match (format "%02d:%02d" hour minute)
12327 t t ans))))
12329 ;; Check if a time range is given as a duration
12330 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12331 (setq hour (string-to-number (match-string 1 ans))
12332 h2 (+ hour (string-to-number (match-string 3 ans)))
12333 minute (string-to-number (match-string 2 ans))
12334 m2 (+ minute (if (match-end 5) (string-to-number
12335 (match-string 5 ans))0)))
12336 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12337 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12338 t t ans)))
12340 ;; Check if there is a time range
12341 (when (boundp 'org-end-time-was-given)
12342 (setq org-time-was-given nil)
12343 (when (and (string-match org-plain-time-of-day-regexp ans)
12344 (match-end 8))
12345 (setq org-end-time-was-given (match-string 8 ans))
12346 (setq ans (concat (substring ans 0 (match-beginning 7))
12347 (substring ans (match-end 7))))))
12349 (setq tl (parse-time-string ans)
12350 day (or (nth 3 tl) (nth 3 defdecode))
12351 month (or (nth 4 tl)
12352 (if (and org-read-date-prefer-future
12353 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12354 (1+ (nth 4 defdecode))
12355 (nth 4 defdecode)))
12356 year (or (nth 5 tl)
12357 (if (and org-read-date-prefer-future
12358 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12359 (1+ (nth 5 defdecode))
12360 (nth 5 defdecode)))
12361 hour (or (nth 2 tl) (nth 2 defdecode))
12362 minute (or (nth 1 tl) (nth 1 defdecode))
12363 second (or (nth 0 tl) 0)
12364 wday (nth 6 tl))
12366 ;; Special date definitions below
12367 (cond
12368 (iso-week
12369 ;; There was an iso week
12370 (setq year (or iso-year year)
12371 day (or iso-weekday wday 1)
12372 wday nil ; to make sure that the trigger below does not match
12373 iso-date (calendar-gregorian-from-absolute
12374 (calendar-absolute-from-iso
12375 (list iso-week day year))))
12376 ; FIXME: Should we also push ISO weeks into the future?
12377 ; (when (and org-read-date-prefer-future
12378 ; (not iso-year)
12379 ; (< (calendar-absolute-from-gregorian iso-date)
12380 ; (time-to-days (current-time))))
12381 ; (setq year (1+ year)
12382 ; iso-date (calendar-gregorian-from-absolute
12383 ; (calendar-absolute-from-iso
12384 ; (list iso-week day year)))))
12385 (setq month (car iso-date)
12386 year (nth 2 iso-date)
12387 day (nth 1 iso-date)))
12388 (deltan
12389 (unless deltadef
12390 (let ((now (decode-time (current-time))))
12391 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12392 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12393 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12394 ((equal deltaw "m") (setq month (+ month deltan)))
12395 ((equal deltaw "y") (setq year (+ year deltan)))))
12396 ((and wday (not (nth 3 tl)))
12397 ;; Weekday was given, but no day, so pick that day in the week
12398 ;; on or after the derived date.
12399 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12400 (unless (equal wday wday1)
12401 (setq day (+ day (% (- wday wday1 -7) 7))))))
12402 (if (and (boundp 'org-time-was-given)
12403 (nth 2 tl))
12404 (setq org-time-was-given t))
12405 (if (< year 100) (setq year (+ 2000 year)))
12406 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12407 (list second minute hour day month year)))
12409 (defvar parse-time-weekdays)
12411 (defun org-read-date-get-relative (s today default)
12412 "Check string S for special relative date string.
12413 TODAY and DEFAULT are internal times, for today and for a default.
12414 Return shift list (N what def-flag)
12415 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12416 N is the number of WHATs to shift.
12417 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12418 the DEFAULT date rather than TODAY."
12419 (when (and
12420 (string-match
12421 (concat
12422 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12423 "\\([0-9]+\\)?"
12424 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12425 "\\([ \t]\\|$\\)") s)
12426 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12427 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12428 (string-to-char (substring (match-string 1 s) -1))
12429 ?+))
12430 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12431 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12432 (what (if (match-end 3) (match-string 3 s) "d"))
12433 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12434 (date (if rel default today))
12435 (wday (nth 6 (decode-time date)))
12436 delta)
12437 (if wday1
12438 (progn
12439 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12440 (if (= dir ?-) (setq delta (- delta 7)))
12441 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12442 (list delta "d" rel))
12443 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12445 (defun org-eval-in-calendar (form &optional keepdate)
12446 "Eval FORM in the calendar window and return to current window.
12447 Also, store the cursor date in variable org-ans2."
12448 (let ((sw (selected-window)))
12449 (select-window (get-buffer-window "*Calendar*"))
12450 (eval form)
12451 (when (and (not keepdate) (calendar-cursor-to-date))
12452 (let* ((date (calendar-cursor-to-date))
12453 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12454 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12455 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12456 (select-window sw)))
12458 (defun org-calendar-select ()
12459 "Return to `org-read-date' with the date currently selected.
12460 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12461 (interactive)
12462 (when (calendar-cursor-to-date)
12463 (let* ((date (calendar-cursor-to-date))
12464 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12465 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12466 (if (active-minibuffer-window) (exit-minibuffer))))
12468 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12469 "Insert a date stamp for the date given by the internal TIME.
12470 WITH-HM means, use the stamp format that includes the time of the day.
12471 INACTIVE means use square brackets instead of angular ones, so that the
12472 stamp will not contribute to the agenda.
12473 PRE and POST are optional strings to be inserted before and after the
12474 stamp.
12475 The command returns the inserted time stamp."
12476 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12477 stamp)
12478 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12479 (insert-before-markers (or pre ""))
12480 (insert-before-markers (setq stamp (format-time-string fmt time)))
12481 (when (listp extra)
12482 (setq extra (car extra))
12483 (if (and (stringp extra)
12484 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12485 (setq extra (format "-%02d:%02d"
12486 (string-to-number (match-string 1 extra))
12487 (string-to-number (match-string 2 extra))))
12488 (setq extra nil)))
12489 (when extra
12490 (backward-char 1)
12491 (insert-before-markers extra)
12492 (forward-char 1))
12493 (insert-before-markers (or post ""))
12494 (setq org-last-inserted-timestamp stamp)))
12496 (defun org-toggle-time-stamp-overlays ()
12497 "Toggle the use of custom time stamp formats."
12498 (interactive)
12499 (setq org-display-custom-times (not org-display-custom-times))
12500 (unless org-display-custom-times
12501 (let ((p (point-min)) (bmp (buffer-modified-p)))
12502 (while (setq p (next-single-property-change p 'display))
12503 (if (and (get-text-property p 'display)
12504 (eq (get-text-property p 'face) 'org-date))
12505 (remove-text-properties
12506 p (setq p (next-single-property-change p 'display))
12507 '(display t))))
12508 (set-buffer-modified-p bmp)))
12509 (if (featurep 'xemacs)
12510 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12511 (org-restart-font-lock)
12512 (setq org-table-may-need-update t)
12513 (if org-display-custom-times
12514 (message "Time stamps are overlayed with custom format")
12515 (message "Time stamp overlays removed")))
12517 (defun org-display-custom-time (beg end)
12518 "Overlay modified time stamp format over timestamp between BEG and END."
12519 (let* ((ts (buffer-substring beg end))
12520 t1 w1 with-hm tf time str w2 (off 0))
12521 (save-match-data
12522 (setq t1 (org-parse-time-string ts t))
12523 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12524 (setq off (- (match-end 0) (match-beginning 0)))))
12525 (setq end (- end off))
12526 (setq w1 (- end beg)
12527 with-hm (and (nth 1 t1) (nth 2 t1))
12528 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12529 time (org-fix-decoded-time t1)
12530 str (org-add-props
12531 (format-time-string
12532 (substring tf 1 -1) (apply 'encode-time time))
12533 nil 'mouse-face 'highlight)
12534 w2 (length str))
12535 (if (not (= w2 w1))
12536 (add-text-properties (1+ beg) (+ 2 beg)
12537 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12538 (if (featurep 'xemacs)
12539 (progn
12540 (put-text-property beg end 'invisible t)
12541 (put-text-property beg end 'end-glyph (make-glyph str)))
12542 (put-text-property beg end 'display str))))
12544 (defun org-translate-time (string)
12545 "Translate all timestamps in STRING to custom format.
12546 But do this only if the variable `org-display-custom-times' is set."
12547 (when org-display-custom-times
12548 (save-match-data
12549 (let* ((start 0)
12550 (re org-ts-regexp-both)
12551 t1 with-hm inactive tf time str beg end)
12552 (while (setq start (string-match re string start))
12553 (setq beg (match-beginning 0)
12554 end (match-end 0)
12555 t1 (save-match-data
12556 (org-parse-time-string (substring string beg end) t))
12557 with-hm (and (nth 1 t1) (nth 2 t1))
12558 inactive (equal (substring string beg (1+ beg)) "[")
12559 tf (funcall (if with-hm 'cdr 'car)
12560 org-time-stamp-custom-formats)
12561 time (org-fix-decoded-time t1)
12562 str (format-time-string
12563 (concat
12564 (if inactive "[" "<") (substring tf 1 -1)
12565 (if inactive "]" ">"))
12566 (apply 'encode-time time))
12567 string (replace-match str t t string)
12568 start (+ start (length str)))))))
12569 string)
12571 (defun org-fix-decoded-time (time)
12572 "Set 0 instead of nil for the first 6 elements of time.
12573 Don't touch the rest."
12574 (let ((n 0))
12575 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12577 (defun org-days-to-time (timestamp-string)
12578 "Difference between TIMESTAMP-STRING and now in days."
12579 (- (time-to-days (org-time-string-to-time timestamp-string))
12580 (time-to-days (current-time))))
12582 (defun org-deadline-close (timestamp-string &optional ndays)
12583 "Is the time in TIMESTAMP-STRING close to the current date?"
12584 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12585 (and (< (org-days-to-time timestamp-string) ndays)
12586 (not (org-entry-is-done-p))))
12588 (defun org-get-wdays (ts)
12589 "Get the deadline lead time appropriate for timestring TS."
12590 (cond
12591 ((<= org-deadline-warning-days 0)
12592 ;; 0 or negative, enforce this value no matter what
12593 (- org-deadline-warning-days))
12594 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12595 ;; lead time is specified.
12596 (floor (* (string-to-number (match-string 1 ts))
12597 (cdr (assoc (match-string 2 ts)
12598 '(("d" . 1) ("w" . 7)
12599 ("m" . 30.4) ("y" . 365.25)))))))
12600 ;; go for the default.
12601 (t org-deadline-warning-days)))
12603 (defun org-calendar-select-mouse (ev)
12604 "Return to `org-read-date' with the date currently selected.
12605 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12606 (interactive "e")
12607 (mouse-set-point ev)
12608 (when (calendar-cursor-to-date)
12609 (let* ((date (calendar-cursor-to-date))
12610 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12611 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12612 (if (active-minibuffer-window) (exit-minibuffer))))
12614 (defun org-check-deadlines (ndays)
12615 "Check if there are any deadlines due or past due.
12616 A deadline is considered due if it happens within `org-deadline-warning-days'
12617 days from today's date. If the deadline appears in an entry marked DONE,
12618 it is not shown. The prefix arg NDAYS can be used to test that many
12619 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12620 (interactive "P")
12621 (let* ((org-warn-days
12622 (cond
12623 ((equal ndays '(4)) 100000)
12624 (ndays (prefix-numeric-value ndays))
12625 (t (abs org-deadline-warning-days))))
12626 (case-fold-search nil)
12627 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12628 (callback
12629 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12631 (message "%d deadlines past-due or due within %d days"
12632 (org-occur regexp nil callback)
12633 org-warn-days)))
12635 (defun org-check-before-date (date)
12636 "Check if there are deadlines or scheduled entries before DATE."
12637 (interactive (list (org-read-date)))
12638 (let ((case-fold-search nil)
12639 (regexp (concat "\\<\\(" org-deadline-string
12640 "\\|" org-scheduled-string
12641 "\\) *<\\([^>]+\\)>"))
12642 (callback
12643 (lambda () (time-less-p
12644 (org-time-string-to-time (match-string 2))
12645 (org-time-string-to-time date)))))
12646 (message "%d entries before %s"
12647 (org-occur regexp nil callback) date)))
12649 (defun org-check-after-date (date)
12650 "Check if there are deadlines or scheduled entries after DATE."
12651 (interactive (list (org-read-date)))
12652 (let ((case-fold-search nil)
12653 (regexp (concat "\\<\\(" org-deadline-string
12654 "\\|" org-scheduled-string
12655 "\\) *<\\([^>]+\\)>"))
12656 (callback
12657 (lambda () (not
12658 (time-less-p
12659 (org-time-string-to-time (match-string 2))
12660 (org-time-string-to-time date))))))
12661 (message "%d entries after %s"
12662 (org-occur regexp nil callback) date)))
12664 (defun org-evaluate-time-range (&optional to-buffer)
12665 "Evaluate a time range by computing the difference between start and end.
12666 Normally the result is just printed in the echo area, but with prefix arg
12667 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12668 If the time range is actually in a table, the result is inserted into the
12669 next column.
12670 For time difference computation, a year is assumed to be exactly 365
12671 days in order to avoid rounding problems."
12672 (interactive "P")
12674 (org-clock-update-time-maybe)
12675 (save-excursion
12676 (unless (org-at-date-range-p t)
12677 (goto-char (point-at-bol))
12678 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12679 (if (not (org-at-date-range-p t))
12680 (error "Not at a time-stamp range, and none found in current line")))
12681 (let* ((ts1 (match-string 1))
12682 (ts2 (match-string 2))
12683 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12684 (match-end (match-end 0))
12685 (time1 (org-time-string-to-time ts1))
12686 (time2 (org-time-string-to-time ts2))
12687 (t1 (time-to-seconds time1))
12688 (t2 (time-to-seconds time2))
12689 (diff (abs (- t2 t1)))
12690 (negative (< (- t2 t1) 0))
12691 ;; (ys (floor (* 365 24 60 60)))
12692 (ds (* 24 60 60))
12693 (hs (* 60 60))
12694 (fy "%dy %dd %02d:%02d")
12695 (fy1 "%dy %dd")
12696 (fd "%dd %02d:%02d")
12697 (fd1 "%dd")
12698 (fh "%02d:%02d")
12699 y d h m align)
12700 (if havetime
12701 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12703 d (floor (/ diff ds)) diff (mod diff ds)
12704 h (floor (/ diff hs)) diff (mod diff hs)
12705 m (floor (/ diff 60)))
12706 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12708 d (floor (+ (/ diff ds) 0.5))
12709 h 0 m 0))
12710 (if (not to-buffer)
12711 (message "%s" (org-make-tdiff-string y d h m))
12712 (if (org-at-table-p)
12713 (progn
12714 (goto-char match-end)
12715 (setq align t)
12716 (and (looking-at " *|") (goto-char (match-end 0))))
12717 (goto-char match-end))
12718 (if (looking-at
12719 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12720 (replace-match ""))
12721 (if negative (insert " -"))
12722 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12723 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12724 (insert " " (format fh h m))))
12725 (if align (org-table-align))
12726 (message "Time difference inserted")))))
12728 (defun org-make-tdiff-string (y d h m)
12729 (let ((fmt "")
12730 (l nil))
12731 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12732 l (push y l)))
12733 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12734 l (push d l)))
12735 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12736 l (push h l)))
12737 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12738 l (push m l)))
12739 (apply 'format fmt (nreverse l))))
12741 (defun org-time-string-to-time (s)
12742 (apply 'encode-time (org-parse-time-string s)))
12743 (defun org-time-string-to-seconds (s)
12744 (time-to-seconds (org-time-string-to-time s)))
12746 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12747 "Convert a time stamp to an absolute day number.
12748 If there is a specifyer for a cyclic time stamp, get the closest date to
12749 DAYNR.
12750 PREFER and SHOW-ALL are passed through to `org-closest-date'.
12751 the variable date is bound by the calendar when this is called."
12752 (cond
12753 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12754 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12755 daynr
12756 (+ daynr 1000)))
12757 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12758 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12759 (time-to-days (current-time))) (match-string 0 s)
12760 prefer show-all))
12761 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12763 (defun org-days-to-iso-week (days)
12764 "Return the iso week number."
12765 (require 'cal-iso)
12766 (car (calendar-iso-from-absolute days)))
12768 (defun org-small-year-to-year (year)
12769 "Convert 2-digit years into 4-digit years.
12770 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12771 The year 2000 cannot be abbreviated. Any year larger than 99
12772 is returned unchanged."
12773 (if (< year 38)
12774 (setq year (+ 2000 year))
12775 (if (< year 100)
12776 (setq year (+ 1900 year))))
12777 year)
12779 (defun org-time-from-absolute (d)
12780 "Return the time corresponding to date D.
12781 D may be an absolute day number, or a calendar-type list (month day year)."
12782 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12783 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12785 (defun org-calendar-holiday ()
12786 "List of holidays, for Diary display in Org-mode."
12787 (require 'holidays)
12788 (let ((hl (funcall
12789 (if (fboundp 'calendar-check-holidays)
12790 'calendar-check-holidays 'check-calendar-holidays) date)))
12791 (if hl (mapconcat 'identity hl "; "))))
12793 (defun org-diary-sexp-entry (sexp entry date)
12794 "Process a SEXP diary ENTRY for DATE."
12795 (require 'diary-lib)
12796 (let ((result (if calendar-debug-sexp
12797 (let ((stack-trace-on-error t))
12798 (eval (car (read-from-string sexp))))
12799 (condition-case nil
12800 (eval (car (read-from-string sexp)))
12801 (error
12802 (beep)
12803 (message "Bad sexp at line %d in %s: %s"
12804 (org-current-line)
12805 (buffer-file-name) sexp)
12806 (sleep-for 2))))))
12807 (cond ((stringp result) result)
12808 ((and (consp result)
12809 (stringp (cdr result))) (cdr result))
12810 (result entry)
12811 (t nil))))
12813 (defun org-diary-to-ical-string (frombuf)
12814 "Get iCalendar entries from diary entries in buffer FROMBUF.
12815 This uses the icalendar.el library."
12816 (let* ((tmpdir (if (featurep 'xemacs)
12817 (temp-directory)
12818 temporary-file-directory))
12819 (tmpfile (make-temp-name
12820 (expand-file-name "orgics" tmpdir)))
12821 buf rtn b e)
12822 (save-excursion
12823 (set-buffer frombuf)
12824 (icalendar-export-region (point-min) (point-max) tmpfile)
12825 (setq buf (find-buffer-visiting tmpfile))
12826 (set-buffer buf)
12827 (goto-char (point-min))
12828 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12829 (setq b (match-beginning 0)))
12830 (goto-char (point-max))
12831 (if (re-search-backward "^END:VEVENT" nil t)
12832 (setq e (match-end 0)))
12833 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12834 (kill-buffer buf)
12835 (delete-file tmpfile)
12836 rtn))
12838 (defun org-closest-date (start current change prefer show-all)
12839 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12840 When PREFER is `past' return a date that is either CURRENT or past.
12841 When PREFER is `future', return a date that is either CURRENT or future.
12842 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12843 ;; Make the proper lists from the dates
12844 (catch 'exit
12845 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12846 dn dw sday cday n1 n2 n0
12847 d m y y1 y2 date1 date2 nmonths nm ny m2)
12849 (setq start (org-date-to-gregorian start)
12850 current (org-date-to-gregorian
12851 (if show-all
12852 current
12853 (time-to-days (current-time))))
12854 sday (calendar-absolute-from-gregorian start)
12855 cday (calendar-absolute-from-gregorian current))
12857 (if (<= cday sday) (throw 'exit sday))
12859 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12860 (setq dn (string-to-number (match-string 1 change))
12861 dw (cdr (assoc (match-string 2 change) a1)))
12862 (error "Invalid change specifyer: %s" change))
12863 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12864 (cond
12865 ((eq dw 'day)
12866 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12867 n2 (+ n1 dn)))
12868 ((eq dw 'year)
12869 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12870 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12871 (setq date1 (list m d y1)
12872 n1 (calendar-absolute-from-gregorian date1)
12873 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12874 n2 (calendar-absolute-from-gregorian date2)))
12875 ((eq dw 'month)
12876 ;; approx number of month between the two dates
12877 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12878 ;; How often does dn fit in there?
12879 (setq d (nth 1 start) m (car start) y (nth 2 start)
12880 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12881 m (+ m nm)
12882 ny (floor (/ m 12))
12883 y (+ y ny)
12884 m (- m (* ny 12)))
12885 (while (> m 12) (setq m (- m 12) y (1+ y)))
12886 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12887 (setq m2 (+ m dn) y2 y)
12888 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12889 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12890 (while (<= n2 cday)
12891 (setq n1 n2 m m2 y y2)
12892 (setq m2 (+ m dn) y2 y)
12893 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12894 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12895 ;; Make sure n1 is the earlier date
12896 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12897 (if show-all
12898 (cond
12899 ((eq prefer 'past) n1)
12900 ((eq prefer 'future) (if (= cday n1) n1 n2))
12901 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12902 (cond
12903 ((eq prefer 'past) n1)
12904 ((eq prefer 'future) (if (= cday n1) n1 n2))
12905 (t (if (= cday n1) n1 n2)))))))
12907 (defun org-date-to-gregorian (date)
12908 "Turn any specification of DATE into a gregorian date for the calendar."
12909 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12910 ((and (listp date) (= (length date) 3)) date)
12911 ((stringp date)
12912 (setq date (org-parse-time-string date))
12913 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12914 ((listp date)
12915 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12917 (defun org-parse-time-string (s &optional nodefault)
12918 "Parse the standard Org-mode time string.
12919 This should be a lot faster than the normal `parse-time-string'.
12920 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12921 hour and minute fields will be nil if not given."
12922 (if (string-match org-ts-regexp0 s)
12923 (list 0
12924 (if (or (match-beginning 8) (not nodefault))
12925 (string-to-number (or (match-string 8 s) "0")))
12926 (if (or (match-beginning 7) (not nodefault))
12927 (string-to-number (or (match-string 7 s) "0")))
12928 (string-to-number (match-string 4 s))
12929 (string-to-number (match-string 3 s))
12930 (string-to-number (match-string 2 s))
12931 nil nil nil)
12932 (make-list 9 0)))
12934 (defun org-timestamp-up (&optional arg)
12935 "Increase the date item at the cursor by one.
12936 If the cursor is on the year, change the year. If it is on the month or
12937 the day, change that.
12938 With prefix ARG, change by that many units."
12939 (interactive "p")
12940 (org-timestamp-change (prefix-numeric-value arg)))
12942 (defun org-timestamp-down (&optional arg)
12943 "Decrease the date item at the cursor by one.
12944 If the cursor is on the year, change the year. If it is on the month or
12945 the day, change that.
12946 With prefix ARG, change by that many units."
12947 (interactive "p")
12948 (org-timestamp-change (- (prefix-numeric-value arg))))
12950 (defun org-timestamp-up-day (&optional arg)
12951 "Increase the date in the time stamp by one day.
12952 With prefix ARG, change that many days."
12953 (interactive "p")
12954 (if (and (not (org-at-timestamp-p t))
12955 (org-on-heading-p))
12956 (org-todo 'up)
12957 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12959 (defun org-timestamp-down-day (&optional arg)
12960 "Decrease the date in the time stamp by one day.
12961 With prefix ARG, change that many days."
12962 (interactive "p")
12963 (if (and (not (org-at-timestamp-p t))
12964 (org-on-heading-p))
12965 (org-todo 'down)
12966 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12968 (defun org-at-timestamp-p (&optional inactive-ok)
12969 "Determine if the cursor is in or at a timestamp."
12970 (interactive)
12971 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12972 (pos (point))
12973 (ans (or (looking-at tsr)
12974 (save-excursion
12975 (skip-chars-backward "^[<\n\r\t")
12976 (if (> (point) (point-min)) (backward-char 1))
12977 (and (looking-at tsr)
12978 (> (- (match-end 0) pos) -1))))))
12979 (and ans
12980 (boundp 'org-ts-what)
12981 (setq org-ts-what
12982 (cond
12983 ((= pos (match-beginning 0)) 'bracket)
12984 ((= pos (1- (match-end 0))) 'bracket)
12985 ((org-pos-in-match-range pos 2) 'year)
12986 ((org-pos-in-match-range pos 3) 'month)
12987 ((org-pos-in-match-range pos 7) 'hour)
12988 ((org-pos-in-match-range pos 8) 'minute)
12989 ((or (org-pos-in-match-range pos 4)
12990 (org-pos-in-match-range pos 5)) 'day)
12991 ((and (> pos (or (match-end 8) (match-end 5)))
12992 (< pos (match-end 0)))
12993 (- pos (or (match-end 8) (match-end 5))))
12994 (t 'day))))
12995 ans))
12997 (defun org-toggle-timestamp-type ()
12998 "Toggle the type (<active> or [inactive]) of a time stamp."
12999 (interactive)
13000 (when (org-at-timestamp-p t)
13001 (let ((beg (match-beginning 0)) (end (match-end 0))
13002 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13003 (save-excursion
13004 (goto-char beg)
13005 (while (re-search-forward "[][<>]" end t)
13006 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13007 t t)))
13008 (message "Timestamp is now %sactive"
13009 (if (equal (char-after beg) ?<) "" "in")))))
13011 (defun org-timestamp-change (n &optional what)
13012 "Change the date in the time stamp at point.
13013 The date will be changed by N times WHAT. WHAT can be `day', `month',
13014 `year', `minute', `second'. If WHAT is not given, the cursor position
13015 in the timestamp determines what will be changed."
13016 (let ((pos (point))
13017 with-hm inactive
13018 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13019 org-ts-what
13020 extra rem
13021 ts time time0)
13022 (if (not (org-at-timestamp-p t))
13023 (error "Not at a timestamp"))
13024 (if (and (not what) (eq org-ts-what 'bracket))
13025 (org-toggle-timestamp-type)
13026 (if (and (not what) (not (eq org-ts-what 'day))
13027 org-display-custom-times
13028 (get-text-property (point) 'display)
13029 (not (get-text-property (1- (point)) 'display)))
13030 (setq org-ts-what 'day))
13031 (setq org-ts-what (or what org-ts-what)
13032 inactive (= (char-after (match-beginning 0)) ?\[)
13033 ts (match-string 0))
13034 (replace-match "")
13035 (if (string-match
13036 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
13038 (setq extra (match-string 1 ts)))
13039 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13040 (setq with-hm t))
13041 (setq time0 (org-parse-time-string ts))
13042 (when (and (eq org-ts-what 'minute)
13043 (eq current-prefix-arg nil))
13044 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13045 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13046 (setcar (cdr time0) (+ (nth 1 time0)
13047 (if (> n 0) (- rem) (- dm rem))))))
13048 (setq time
13049 (encode-time (or (car time0) 0)
13050 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13051 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13052 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13053 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13054 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13055 (nthcdr 6 time0)))
13056 (when (and (member org-ts-what '(hour minute))
13057 extra
13058 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13059 (setq extra (org-modify-ts-extra
13060 extra
13061 (if (eq org-ts-what 'hour) 2 5)
13062 n dm)))
13063 (when (integerp org-ts-what)
13064 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13065 (if (eq what 'calendar)
13066 (let ((cal-date (org-get-date-from-calendar)))
13067 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13068 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13069 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13070 (setcar time0 (or (car time0) 0))
13071 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13072 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13073 (setq time (apply 'encode-time time0))))
13074 (setq org-last-changed-timestamp
13075 (org-insert-time-stamp time with-hm inactive nil nil extra))
13076 (org-clock-update-time-maybe)
13077 (goto-char pos)
13078 ;; Try to recenter the calendar window, if any
13079 (if (and org-calendar-follow-timestamp-change
13080 (get-buffer-window "*Calendar*" t)
13081 (memq org-ts-what '(day month year)))
13082 (org-recenter-calendar (time-to-days time))))))
13084 (defun org-modify-ts-extra (s pos n dm)
13085 "Change the different parts of the lead-time and repeat fields in timestamp."
13086 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13087 ng h m new rem)
13088 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13089 (cond
13090 ((or (org-pos-in-match-range pos 2)
13091 (org-pos-in-match-range pos 3))
13092 (setq m (string-to-number (match-string 3 s))
13093 h (string-to-number (match-string 2 s)))
13094 (if (org-pos-in-match-range pos 2)
13095 (setq h (+ h n))
13096 (setq n (* dm (org-no-warnings (signum n))))
13097 (when (not (= 0 (setq rem (% m dm))))
13098 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13099 (setq m (+ m n)))
13100 (if (< m 0) (setq m (+ m 60) h (1- h)))
13101 (if (> m 59) (setq m (- m 60) h (1+ h)))
13102 (setq h (min 24 (max 0 h)))
13103 (setq ng 1 new (format "-%02d:%02d" h m)))
13104 ((org-pos-in-match-range pos 6)
13105 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13106 ((org-pos-in-match-range pos 5)
13107 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13109 ((org-pos-in-match-range pos 9)
13110 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13111 ((org-pos-in-match-range pos 8)
13112 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13114 (when ng
13115 (setq s (concat
13116 (substring s 0 (match-beginning ng))
13118 (substring s (match-end ng))))))
13121 (defun org-recenter-calendar (date)
13122 "If the calendar is visible, recenter it to DATE."
13123 (let* ((win (selected-window))
13124 (cwin (get-buffer-window "*Calendar*" t))
13125 (calendar-move-hook nil))
13126 (when cwin
13127 (select-window cwin)
13128 (calendar-goto-date (if (listp date) date
13129 (calendar-gregorian-from-absolute date)))
13130 (select-window win))))
13132 (defun org-goto-calendar (&optional arg)
13133 "Go to the Emacs calendar at the current date.
13134 If there is a time stamp in the current line, go to that date.
13135 A prefix ARG can be used to force the current date."
13136 (interactive "P")
13137 (let ((tsr org-ts-regexp) diff
13138 (calendar-move-hook nil)
13139 (calendar-view-holidays-initially-flag nil)
13140 (view-calendar-holidays-initially nil)
13141 (calendar-view-diary-initially-flag nil)
13142 (view-diary-entries-initially nil))
13143 (if (or (org-at-timestamp-p)
13144 (save-excursion
13145 (beginning-of-line 1)
13146 (looking-at (concat ".*" tsr))))
13147 (let ((d1 (time-to-days (current-time)))
13148 (d2 (time-to-days
13149 (org-time-string-to-time (match-string 1)))))
13150 (setq diff (- d2 d1))))
13151 (calendar)
13152 (calendar-goto-today)
13153 (if (and diff (not arg)) (calendar-forward-day diff))))
13155 (defun org-get-date-from-calendar ()
13156 "Return a list (month day year) of date at point in calendar."
13157 (with-current-buffer "*Calendar*"
13158 (save-match-data
13159 (calendar-cursor-to-date))))
13161 (defun org-date-from-calendar ()
13162 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13163 If there is already a time stamp at the cursor position, update it."
13164 (interactive)
13165 (if (org-at-timestamp-p t)
13166 (org-timestamp-change 0 'calendar)
13167 (let ((cal-date (org-get-date-from-calendar)))
13168 (org-insert-time-stamp
13169 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13171 (defun org-minutes-to-hh:mm-string (m)
13172 "Compute H:MM from a number of minutes."
13173 (let ((h (/ m 60)))
13174 (setq m (- m (* 60 h)))
13175 (format org-time-clocksum-format h m)))
13177 (defun org-hh:mm-string-to-minutes (s)
13178 "Convert a string H:MM to a number of minutes.
13179 If the string is just a number, interprete it as minutes.
13180 In fact, the first hh:mm or number in the string will be taken,
13181 there can be extra stuff in the string.
13182 If no number is found, the return value is 0."
13183 (cond
13184 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13185 (+ (* (string-to-number (match-string 1 s)) 60)
13186 (string-to-number (match-string 2 s))))
13187 ((string-match "\\([0-9]+\\)" s)
13188 (string-to-number (match-string 1 s)))
13189 (t 0)))
13191 ;;;; Files
13193 (defun org-save-all-org-buffers ()
13194 "Save all Org-mode buffers without user confirmation."
13195 (interactive)
13196 (message "Saving all Org-mode buffers...")
13197 (save-some-buffers t 'org-mode-p)
13198 (when (featurep 'org-id) (org-id-locations-save))
13199 (message "Saving all Org-mode buffers... done"))
13201 (defun org-revert-all-org-buffers ()
13202 "Revert all Org-mode buffers.
13203 Prompt for confirmation when there are unsaved changes.
13204 Be sure you know what you are doing before letting this function
13205 overwrite your changes.
13207 This function is useful in a setup where one tracks org files
13208 with a version control system, to revert on one machine after pulling
13209 changes from another. I believe the procedure must be like this:
13211 1. M-x org-save-all-org-buffers
13212 2. Pull changes from the other machine, resolve conflicts
13213 3. M-x org-revert-all-org-buffers"
13214 (interactive)
13215 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13216 (error "Abort"))
13217 (save-excursion
13218 (save-window-excursion
13219 (mapc
13220 (lambda (b)
13221 (when (and (with-current-buffer b (org-mode-p))
13222 (with-current-buffer b buffer-file-name))
13223 (switch-to-buffer b)
13224 (revert-buffer t 'no-confirm)))
13225 (buffer-list))
13226 (when (and (featurep 'org-id) org-id-track-globally)
13227 (org-id-locations-load)))))
13229 ;;;; Agenda files
13231 ;;;###autoload
13232 (defun org-iswitchb (&optional arg)
13233 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13234 With a prefix argument, restrict available to files.
13235 With two prefix arguments, restrict available buffers to agenda files.
13237 Due to some yet unresolved reason, the global function
13238 `iswitchb-mode' needs to be active for this function to work."
13239 (interactive "P")
13240 (require 'iswitchb)
13241 (let ((enabled iswitchb-mode) blist)
13242 (or enabled (iswitchb-mode 1))
13243 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13244 ((equal arg '(16)) (org-buffer-list 'agenda))
13245 (t (org-buffer-list))))
13246 (unwind-protect
13247 (let ((iswitchb-make-buflist-hook
13248 (lambda ()
13249 (setq iswitchb-temp-buflist
13250 (mapcar 'buffer-name blist)))))
13251 (switch-to-buffer
13252 (iswitchb-read-buffer
13253 "Switch-to: " nil t))
13254 (or enabled (iswitchb-mode -1))))))
13256 ;;;###autoload
13257 (defun org-ido-switchb (&optional arg)
13258 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
13259 With a prefix argument, restrict available to files.
13260 With two prefix arguments, restrict available buffers to agenda files."
13261 (interactive "P")
13262 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13263 ((equal arg '(16)) (org-buffer-list 'agenda))
13264 (t (org-buffer-list)))))
13265 (switch-to-buffer
13266 (org-ido-completing-read "Org buffer: "
13267 (mapcar 'list (mapcar 'buffer-name blist))
13268 nil t))))
13270 (defun org-buffer-list (&optional predicate exclude-tmp)
13271 "Return a list of Org buffers.
13272 PREDICATE can be `export', `files' or `agenda'.
13274 export restrict the list to Export buffers.
13275 files restrict the list to buffers visiting Org files.
13276 agenda restrict the list to buffers visiting agenda files.
13278 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13279 (let* ((bfn nil)
13280 (agenda-files (and (eq predicate 'agenda)
13281 (mapcar 'file-truename (org-agenda-files t))))
13282 (filter
13283 (cond
13284 ((eq predicate 'files)
13285 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13286 ((eq predicate 'export)
13287 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13288 ((eq predicate 'agenda)
13289 (lambda (b)
13290 (with-current-buffer b
13291 (and (eq major-mode 'org-mode)
13292 (setq bfn (buffer-file-name b))
13293 (member (file-truename bfn) agenda-files)))))
13294 (t (lambda (b) (with-current-buffer b
13295 (or (eq major-mode 'org-mode)
13296 (string-match "\*Org .*Export"
13297 (buffer-name b)))))))))
13298 (delq nil
13299 (mapcar
13300 (lambda(b)
13301 (if (and (funcall filter b)
13302 (or (not exclude-tmp)
13303 (not (string-match "tmp" (buffer-name b)))))
13305 nil))
13306 (buffer-list)))))
13308 (defun org-agenda-files (&optional unrestricted archives)
13309 "Get the list of agenda files.
13310 Optional UNRESTRICTED means return the full list even if a restriction
13311 is currently in place.
13312 When ARCHIVES is t, include all archive files hat are really being
13313 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13314 `org-agenda-archives-mode' is t."
13315 (let ((files
13316 (cond
13317 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13318 ((stringp org-agenda-files) (org-read-agenda-file-list))
13319 ((listp org-agenda-files) org-agenda-files)
13320 (t (error "Invalid value of `org-agenda-files'")))))
13321 (setq files (apply 'append
13322 (mapcar (lambda (f)
13323 (if (file-directory-p f)
13324 (directory-files
13325 f t org-agenda-file-regexp)
13326 (list f)))
13327 files)))
13328 (when org-agenda-skip-unavailable-files
13329 (setq files (delq nil
13330 (mapcar (function
13331 (lambda (file)
13332 (and (file-readable-p file) file)))
13333 files))))
13334 (when (or (eq archives t)
13335 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13336 (setq files (org-add-archive-files files)))
13337 files))
13339 (defun org-edit-agenda-file-list ()
13340 "Edit the list of agenda files.
13341 Depending on setup, this either uses customize to edit the variable
13342 `org-agenda-files', or it visits the file that is holding the list. In the
13343 latter case, the buffer is set up in a way that saving it automatically kills
13344 the buffer and restores the previous window configuration."
13345 (interactive)
13346 (if (stringp org-agenda-files)
13347 (let ((cw (current-window-configuration)))
13348 (find-file org-agenda-files)
13349 (org-set-local 'org-window-configuration cw)
13350 (org-add-hook 'after-save-hook
13351 (lambda ()
13352 (set-window-configuration
13353 (prog1 org-window-configuration
13354 (kill-buffer (current-buffer))))
13355 (org-install-agenda-files-menu)
13356 (message "New agenda file list installed"))
13357 nil 'local)
13358 (message "%s" (substitute-command-keys
13359 "Edit list and finish with \\[save-buffer]")))
13360 (customize-variable 'org-agenda-files)))
13362 (defun org-store-new-agenda-file-list (list)
13363 "Set new value for the agenda file list and save it correctly."
13364 (if (stringp org-agenda-files)
13365 (let ((f org-agenda-files) b)
13366 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13367 (with-temp-file f
13368 (insert (mapconcat 'identity list "\n") "\n")))
13369 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13370 (setq org-agenda-files list)
13371 (customize-save-variable 'org-agenda-files org-agenda-files))))
13373 (defun org-read-agenda-file-list ()
13374 "Read the list of agenda files from a file."
13375 (when (file-directory-p org-agenda-files)
13376 (error "`org-agenda-files' cannot be a single directory"))
13377 (when (stringp org-agenda-files)
13378 (with-temp-buffer
13379 (insert-file-contents org-agenda-files)
13380 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13383 ;;;###autoload
13384 (defun org-cycle-agenda-files ()
13385 "Cycle through the files in `org-agenda-files'.
13386 If the current buffer visits an agenda file, find the next one in the list.
13387 If the current buffer does not, find the first agenda file."
13388 (interactive)
13389 (let* ((fs (org-agenda-files t))
13390 (files (append fs (list (car fs))))
13391 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13392 file)
13393 (unless files (error "No agenda files"))
13394 (catch 'exit
13395 (while (setq file (pop files))
13396 (if (equal (file-truename file) tcf)
13397 (when (car files)
13398 (find-file (car files))
13399 (throw 'exit t))))
13400 (find-file (car fs)))
13401 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13403 (defun org-agenda-file-to-front (&optional to-end)
13404 "Move/add the current file to the top of the agenda file list.
13405 If the file is not present in the list, it is added to the front. If it is
13406 present, it is moved there. With optional argument TO-END, add/move to the
13407 end of the list."
13408 (interactive "P")
13409 (let ((org-agenda-skip-unavailable-files nil)
13410 (file-alist (mapcar (lambda (x)
13411 (cons (file-truename x) x))
13412 (org-agenda-files t)))
13413 (ctf (file-truename buffer-file-name))
13414 x had)
13415 (setq x (assoc ctf file-alist) had x)
13417 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13418 (if to-end
13419 (setq file-alist (append (delq x file-alist) (list x)))
13420 (setq file-alist (cons x (delq x file-alist))))
13421 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13422 (org-install-agenda-files-menu)
13423 (message "File %s to %s of agenda file list"
13424 (if had "moved" "added") (if to-end "end" "front"))))
13426 (defun org-remove-file (&optional file)
13427 "Remove current file from the list of files in variable `org-agenda-files'.
13428 These are the files which are being checked for agenda entries.
13429 Optional argument FILE means, use this file instead of the current."
13430 (interactive)
13431 (let* ((org-agenda-skip-unavailable-files nil)
13432 (file (or file buffer-file-name))
13433 (true-file (file-truename file))
13434 (afile (abbreviate-file-name file))
13435 (files (delq nil (mapcar
13436 (lambda (x)
13437 (if (equal true-file
13438 (file-truename x))
13439 nil x))
13440 (org-agenda-files t)))))
13441 (if (not (= (length files) (length (org-agenda-files t))))
13442 (progn
13443 (org-store-new-agenda-file-list files)
13444 (org-install-agenda-files-menu)
13445 (message "Removed file: %s" afile))
13446 (message "File was not in list: %s (not removed)" afile))))
13448 (defun org-file-menu-entry (file)
13449 (vector file (list 'find-file file) t))
13451 (defun org-check-agenda-file (file)
13452 "Make sure FILE exists. If not, ask user what to do."
13453 (when (not (file-exists-p file))
13454 (message "non-existent file %s. [R]emove from list or [A]bort?"
13455 (abbreviate-file-name file))
13456 (let ((r (downcase (read-char-exclusive))))
13457 (cond
13458 ((equal r ?r)
13459 (org-remove-file file)
13460 (throw 'nextfile t))
13461 (t (error "Abort"))))))
13463 (defun org-get-agenda-file-buffer (file)
13464 "Get a buffer visiting FILE. If the buffer needs to be created, add
13465 it to the list of buffers which might be released later."
13466 (let ((buf (org-find-base-buffer-visiting file)))
13467 (if buf
13468 buf ; just return it
13469 ;; Make a new buffer and remember it
13470 (setq buf (find-file-noselect file))
13471 (if buf (push buf org-agenda-new-buffers))
13472 buf)))
13474 (defun org-release-buffers (blist)
13475 "Release all buffers in list, asking the user for confirmation when needed.
13476 When a buffer is unmodified, it is just killed. When modified, it is saved
13477 \(if the user agrees) and then killed."
13478 (let (buf file)
13479 (while (setq buf (pop blist))
13480 (setq file (buffer-file-name buf))
13481 (when (and (buffer-modified-p buf)
13482 file
13483 (y-or-n-p (format "Save file %s? " file)))
13484 (with-current-buffer buf (save-buffer)))
13485 (kill-buffer buf))))
13487 (defun org-prepare-agenda-buffers (files)
13488 "Create buffers for all agenda files, protect archived trees and comments."
13489 (interactive)
13490 (let ((pa '(:org-archived t))
13491 (pc '(:org-comment t))
13492 (pall '(:org-archived t :org-comment t))
13493 (inhibit-read-only t)
13494 (rea (concat ":" org-archive-tag ":"))
13495 bmp file re)
13496 (save-excursion
13497 (save-restriction
13498 (while (setq file (pop files))
13499 (catch 'nextfile
13500 (if (bufferp file)
13501 (set-buffer file)
13502 (org-check-agenda-file file)
13503 (set-buffer (org-get-agenda-file-buffer file)))
13504 (widen)
13505 (setq bmp (buffer-modified-p))
13506 (org-refresh-category-properties)
13507 (setq org-todo-keywords-for-agenda
13508 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13509 (setq org-done-keywords-for-agenda
13510 (append org-done-keywords-for-agenda org-done-keywords))
13511 (setq org-todo-keyword-alist-for-agenda
13512 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13513 (setq org-tag-alist-for-agenda
13514 (append org-tag-alist-for-agenda org-tag-alist))
13516 (save-excursion
13517 (remove-text-properties (point-min) (point-max) pall)
13518 (when org-agenda-skip-archived-trees
13519 (goto-char (point-min))
13520 (while (re-search-forward rea nil t)
13521 (if (org-on-heading-p t)
13522 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13523 (goto-char (point-min))
13524 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13525 (while (re-search-forward re nil t)
13526 (add-text-properties
13527 (match-beginning 0) (org-end-of-subtree t) pc)))
13528 (set-buffer-modified-p bmp)))))
13529 (setq org-todo-keyword-alist-for-agenda
13530 (org-uniquify org-todo-keyword-alist-for-agenda)
13531 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13533 ;;;; Embedded LaTeX
13535 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13536 "Keymap for the minor `org-cdlatex-mode'.")
13538 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13539 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13540 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13541 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13542 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13544 (defvar org-cdlatex-texmathp-advice-is-done nil
13545 "Flag remembering if we have applied the advice to texmathp already.")
13547 (define-minor-mode org-cdlatex-mode
13548 "Toggle the minor `org-cdlatex-mode'.
13549 This mode supports entering LaTeX environment and math in LaTeX fragments
13550 in Org-mode.
13551 \\{org-cdlatex-mode-map}"
13552 nil " OCDL" nil
13553 (when org-cdlatex-mode (require 'cdlatex))
13554 (unless org-cdlatex-texmathp-advice-is-done
13555 (setq org-cdlatex-texmathp-advice-is-done t)
13556 (defadvice texmathp (around org-math-always-on activate)
13557 "Always return t in org-mode buffers.
13558 This is because we want to insert math symbols without dollars even outside
13559 the LaTeX math segments. If Orgmode thinks that point is actually inside
13560 an embedded LaTeX fragment, let texmathp do its job.
13561 \\[org-cdlatex-mode-map]"
13562 (interactive)
13563 (let (p)
13564 (cond
13565 ((not (org-mode-p)) ad-do-it)
13566 ((eq this-command 'cdlatex-math-symbol)
13567 (setq ad-return-value t
13568 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13570 (let ((p (org-inside-LaTeX-fragment-p)))
13571 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13572 (setq ad-return-value t
13573 texmathp-why '("Org-mode embedded math" . 0))
13574 (if p ad-do-it)))))))))
13576 (defun turn-on-org-cdlatex ()
13577 "Unconditionally turn on `org-cdlatex-mode'."
13578 (org-cdlatex-mode 1))
13580 (defun org-inside-LaTeX-fragment-p ()
13581 "Test if point is inside a LaTeX fragment.
13582 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13583 sequence appearing also before point.
13584 Even though the matchers for math are configurable, this function assumes
13585 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13586 delimiters are skipped when they have been removed by customization.
13587 The return value is nil, or a cons cell with the delimiter and
13588 and the position of this delimiter.
13590 This function does a reasonably good job, but can locally be fooled by
13591 for example currency specifications. For example it will assume being in
13592 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13593 fragments that are properly closed, but during editing, we have to live
13594 with the uncertainty caused by missing closing delimiters. This function
13595 looks only before point, not after."
13596 (catch 'exit
13597 (let ((pos (point))
13598 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13599 (lim (progn
13600 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13601 (point)))
13602 dd-on str (start 0) m re)
13603 (goto-char pos)
13604 (when dodollar
13605 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13606 re (nth 1 (assoc "$" org-latex-regexps)))
13607 (while (string-match re str start)
13608 (cond
13609 ((= (match-end 0) (length str))
13610 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13611 ((= (match-end 0) (- (length str) 5))
13612 (throw 'exit nil))
13613 (t (setq start (match-end 0))))))
13614 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13615 (goto-char pos)
13616 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13617 (and (match-beginning 2) (throw 'exit nil))
13618 ;; count $$
13619 (while (re-search-backward "\\$\\$" lim t)
13620 (setq dd-on (not dd-on)))
13621 (goto-char pos)
13622 (if dd-on (cons "$$" m))))))
13625 (defun org-try-cdlatex-tab ()
13626 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13627 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13628 - inside a LaTeX fragment, or
13629 - after the first word in a line, where an abbreviation expansion could
13630 insert a LaTeX environment."
13631 (when org-cdlatex-mode
13632 (cond
13633 ((save-excursion
13634 (skip-chars-backward "a-zA-Z0-9*")
13635 (skip-chars-backward " \t")
13636 (bolp))
13637 (cdlatex-tab) t)
13638 ((org-inside-LaTeX-fragment-p)
13639 (cdlatex-tab) t)
13640 (t nil))))
13642 (defun org-cdlatex-underscore-caret (&optional arg)
13643 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13644 Revert to the normal definition outside of these fragments."
13645 (interactive "P")
13646 (if (org-inside-LaTeX-fragment-p)
13647 (call-interactively 'cdlatex-sub-superscript)
13648 (let (org-cdlatex-mode)
13649 (call-interactively (key-binding (vector last-input-event))))))
13651 (defun org-cdlatex-math-modify (&optional arg)
13652 "Execute `cdlatex-math-modify' in LaTeX fragments.
13653 Revert to the normal definition outside of these fragments."
13654 (interactive "P")
13655 (if (org-inside-LaTeX-fragment-p)
13656 (call-interactively 'cdlatex-math-modify)
13657 (let (org-cdlatex-mode)
13658 (call-interactively (key-binding (vector last-input-event))))))
13660 (defvar org-latex-fragment-image-overlays nil
13661 "List of overlays carrying the images of latex fragments.")
13662 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13664 (defun org-remove-latex-fragment-image-overlays ()
13665 "Remove all overlays with LaTeX fragment images in current buffer."
13666 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13667 (setq org-latex-fragment-image-overlays nil))
13669 (defun org-preview-latex-fragment (&optional subtree)
13670 "Preview the LaTeX fragment at point, or all locally or globally.
13671 If the cursor is in a LaTeX fragment, create the image and overlay
13672 it over the source code. If there is no fragment at point, display
13673 all fragments in the current text, from one headline to the next. With
13674 prefix SUBTREE, display all fragments in the current subtree. With a
13675 double prefix `C-u C-u', or when the cursor is before the first headline,
13676 display all fragments in the buffer.
13677 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13678 (interactive "P")
13679 (org-remove-latex-fragment-image-overlays)
13680 (save-excursion
13681 (save-restriction
13682 (let (beg end at msg)
13683 (cond
13684 ((or (equal subtree '(16))
13685 (not (save-excursion
13686 (re-search-backward (concat "^" outline-regexp) nil t))))
13687 (setq beg (point-min) end (point-max)
13688 msg "Creating images for buffer...%s"))
13689 ((equal subtree '(4))
13690 (org-back-to-heading)
13691 (setq beg (point) end (org-end-of-subtree t)
13692 msg "Creating images for subtree...%s"))
13694 (if (setq at (org-inside-LaTeX-fragment-p))
13695 (goto-char (max (point-min) (- (cdr at) 2)))
13696 (org-back-to-heading))
13697 (setq beg (point) end (progn (outline-next-heading) (point))
13698 msg (if at "Creating image...%s"
13699 "Creating images for entry...%s"))))
13700 (message msg "")
13701 (narrow-to-region beg end)
13702 (goto-char beg)
13703 (org-format-latex
13704 (concat "ltxpng/" (file-name-sans-extension
13705 (file-name-nondirectory
13706 buffer-file-name)))
13707 default-directory 'overlays msg at 'forbuffer)
13708 (message msg "done. Use `C-c C-c' to remove images.")))))
13710 (defvar org-latex-regexps
13711 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13712 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13713 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13714 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13715 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13716 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13717 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13718 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13719 "Regular expressions for matching embedded LaTeX.")
13721 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13722 "Replace LaTeX fragments with links to an image, and produce images."
13723 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13724 (let* ((prefixnodir (file-name-nondirectory prefix))
13725 (absprefix (expand-file-name prefix dir))
13726 (todir (file-name-directory absprefix))
13727 (opt org-format-latex-options)
13728 (matchers (plist-get opt :matchers))
13729 (re-list org-latex-regexps)
13730 (cnt 0) txt link beg end re e checkdir
13731 executables-checked
13732 m n block linkfile movefile ov)
13733 ;; Check if there are old images files with this prefix, and remove them
13734 (when (file-directory-p todir)
13735 (mapc 'delete-file
13736 (directory-files
13737 todir 'full
13738 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13739 ;; Check the different regular expressions
13740 (while (setq e (pop re-list))
13741 (setq m (car e) re (nth 1 e) n (nth 2 e)
13742 block (if (nth 3 e) "\n\n" ""))
13743 (when (member m matchers)
13744 (goto-char (point-min))
13745 (while (re-search-forward re nil t)
13746 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13747 (not (get-text-property (match-beginning n)
13748 'org-protected)))
13749 (setq txt (match-string n)
13750 beg (match-beginning n) end (match-end n)
13751 cnt (1+ cnt)
13752 linkfile (format "%s_%04d.png" prefix cnt)
13753 movefile (format "%s_%04d.png" absprefix cnt)
13754 link (concat block "[[file:" linkfile "]]" block))
13755 (if msg (message msg cnt))
13756 (goto-char beg)
13757 (unless checkdir ; make sure the directory exists
13758 (setq checkdir t)
13759 (or (file-directory-p todir) (make-directory todir)))
13761 (unless executables-checked
13762 (org-check-external-command
13763 "latex" "needed to convert LaTeX fragments to images")
13764 (org-check-external-command
13765 "dvipng" "needed to convert LaTeX fragments to images")
13766 (setq executables-checked t))
13768 (org-create-formula-image
13769 txt movefile opt forbuffer)
13770 (if overlays
13771 (progn
13772 (setq ov (org-make-overlay beg end))
13773 (if (featurep 'xemacs)
13774 (progn
13775 (org-overlay-put ov 'invisible t)
13776 (org-overlay-put
13777 ov 'end-glyph
13778 (make-glyph (vector 'png :file movefile))))
13779 (org-overlay-put
13780 ov 'display
13781 (list 'image :type 'png :file movefile :ascent 'center)))
13782 (push ov org-latex-fragment-image-overlays)
13783 (goto-char end))
13784 (delete-region beg end)
13785 (insert link))))))))
13787 ;; This function borrows from Ganesh Swami's latex2png.el
13788 (defun org-create-formula-image (string tofile options buffer)
13789 (let* ((tmpdir (if (featurep 'xemacs)
13790 (temp-directory)
13791 temporary-file-directory))
13792 (texfilebase (make-temp-name
13793 (expand-file-name "orgtex" tmpdir)))
13794 (texfile (concat texfilebase ".tex"))
13795 (dvifile (concat texfilebase ".dvi"))
13796 (pngfile (concat texfilebase ".png"))
13797 (fnh (if (featurep 'xemacs)
13798 (font-height (get-face-font 'default))
13799 (face-attribute 'default :height nil)))
13800 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13801 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13802 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13803 "Black"))
13804 (bg (or (plist-get options (if buffer :background :html-background))
13805 "Transparent")))
13806 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13807 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13808 (with-temp-file texfile
13809 (insert org-format-latex-header
13810 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13811 (let ((dir default-directory))
13812 (condition-case nil
13813 (progn
13814 (cd tmpdir)
13815 (call-process "latex" nil nil nil texfile))
13816 (error nil))
13817 (cd dir))
13818 (if (not (file-exists-p dvifile))
13819 (progn (message "Failed to create dvi file from %s" texfile) nil)
13820 (condition-case nil
13821 (call-process "dvipng" nil nil nil
13822 "-E" "-fg" fg "-bg" bg
13823 "-D" dpi
13824 ;;"-x" scale "-y" scale
13825 "-T" "tight"
13826 "-o" pngfile
13827 dvifile)
13828 (error nil))
13829 (if (not (file-exists-p pngfile))
13830 (progn (message "Failed to create png file from %s" texfile) nil)
13831 ;; Use the requested file name and clean up
13832 (copy-file pngfile tofile 'replace)
13833 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13834 (delete-file (concat texfilebase e)))
13835 pngfile))))
13837 (defun org-dvipng-color (attr)
13838 "Return an rgb color specification for dvipng."
13839 (apply 'format "rgb %s %s %s"
13840 (mapcar 'org-normalize-color
13841 (color-values (face-attribute 'default attr nil)))))
13843 (defun org-normalize-color (value)
13844 "Return string to be used as color value for an RGB component."
13845 (format "%g" (/ value 65535.0)))
13847 ;;;; Key bindings
13849 ;; Make `C-c C-x' a prefix key
13850 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13852 ;; TAB key with modifiers
13853 (org-defkey org-mode-map "\C-i" 'org-cycle)
13854 (org-defkey org-mode-map [(tab)] 'org-cycle)
13855 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13856 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13857 (org-defkey org-mode-map "\M-\t" 'org-complete)
13858 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13859 ;; The following line is necessary under Suse GNU/Linux
13860 (unless (featurep 'xemacs)
13861 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13862 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13863 (define-key org-mode-map [backtab] 'org-shifttab)
13865 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13866 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13867 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13869 ;; Cursor keys with modifiers
13870 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13871 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13872 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13873 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13875 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13876 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13877 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13878 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13880 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13881 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13882 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13883 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13885 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13886 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13888 ;;; Extra keys for tty access.
13889 ;; We only set them when really needed because otherwise the
13890 ;; menus don't show the simple keys
13892 (when (or org-use-extra-keys
13893 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13894 (not window-system))
13895 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13896 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13897 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13898 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13899 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13900 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13901 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13902 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13903 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13904 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13905 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13906 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13907 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13908 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13909 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13910 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13911 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13912 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13913 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13914 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13915 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13916 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
13917 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
13918 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
13919 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
13920 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
13921 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
13922 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
13924 ;; All the other keys
13926 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13927 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13928 (if (boundp 'narrow-map)
13929 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13930 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13931 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13932 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13933 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13934 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13935 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13936 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13937 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13938 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13939 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13940 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13941 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13942 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13943 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13944 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13945 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13946 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13947 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13948 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13949 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13950 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13951 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13952 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13953 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13954 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13955 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13956 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13957 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13958 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13959 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13960 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13961 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13962 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13963 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13964 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13965 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13966 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13967 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13968 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13969 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13970 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13971 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13972 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13973 (org-defkey org-mode-map "\C-c^" 'org-sort)
13974 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13975 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13976 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13977 (org-defkey org-mode-map "\C-m" 'org-return)
13978 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13979 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13980 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13981 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13982 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13983 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13984 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13985 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13986 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13987 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13988 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13989 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13990 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13991 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13992 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13993 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13994 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13996 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13997 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13998 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13999 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14001 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14002 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14003 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14004 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14005 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14006 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14007 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14008 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14009 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14010 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14011 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14012 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14013 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14015 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14016 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14017 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14018 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14020 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14022 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14024 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14025 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14027 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14030 (when (featurep 'xemacs)
14031 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14034 (defvar org-self-insert-command-undo-counter 0)
14036 (defvar org-table-auto-blank-field) ; defined in org-table.el
14037 (defun org-self-insert-command (N)
14038 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14039 If the cursor is in a table looking at whitespace, the whitespace is
14040 overwritten, and the table is not marked as requiring realignment."
14041 (interactive "p")
14042 (if (and
14043 (org-table-p)
14044 (progn
14045 ;; check if we blank the field, and if that triggers align
14046 (and (featurep 'org-table) org-table-auto-blank-field
14047 (member last-command
14048 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14049 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14050 ;; got extra space, this field does not determine column width
14051 (let (org-table-may-need-update) (org-table-blank-field))
14052 ;; no extra space, this field may determine column width
14053 (org-table-blank-field)))
14055 (eq N 1)
14056 (looking-at "[^|\n]* |"))
14057 (let (org-table-may-need-update)
14058 (goto-char (1- (match-end 0)))
14059 (delete-backward-char 1)
14060 (goto-char (match-beginning 0))
14061 (self-insert-command N))
14062 (setq org-table-may-need-update t)
14063 (self-insert-command N)
14064 (org-fix-tags-on-the-fly)
14065 (if org-self-insert-cluster-for-undo
14066 (if (not (eq last-command 'org-self-insert-command))
14067 (setq org-self-insert-command-undo-counter 1)
14068 (if (>= org-self-insert-command-undo-counter 20)
14069 (setq org-self-insert-command-undo-counter 1)
14070 (and (> org-self-insert-command-undo-counter 0)
14071 buffer-undo-list
14072 (not (cadr buffer-undo-list)) ; remove nil entry
14073 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14074 (setq org-self-insert-command-undo-counter
14075 (1+ org-self-insert-command-undo-counter)))))))
14077 (defun org-fix-tags-on-the-fly ()
14078 (when (and (equal (char-after (point-at-bol)) ?*)
14079 (org-on-heading-p))
14080 (org-align-tags-here org-tags-column)))
14082 (defun org-delete-backward-char (N)
14083 "Like `delete-backward-char', insert whitespace at field end in tables.
14084 When deleting backwards, in tables this function will insert whitespace in
14085 front of the next \"|\" separator, to keep the table aligned. The table will
14086 still be marked for re-alignment if the field did fill the entire column,
14087 because, in this case the deletion might narrow the column."
14088 (interactive "p")
14089 (if (and (org-table-p)
14090 (eq N 1)
14091 (string-match "|" (buffer-substring (point-at-bol) (point)))
14092 (looking-at ".*?|"))
14093 (let ((pos (point))
14094 (noalign (looking-at "[^|\n\r]* |"))
14095 (c org-table-may-need-update))
14096 (backward-delete-char N)
14097 (skip-chars-forward "^|")
14098 (insert " ")
14099 (goto-char (1- pos))
14100 ;; noalign: if there were two spaces at the end, this field
14101 ;; does not determine the width of the column.
14102 (if noalign (setq org-table-may-need-update c)))
14103 (backward-delete-char N)
14104 (org-fix-tags-on-the-fly)))
14106 (defun org-delete-char (N)
14107 "Like `delete-char', but insert whitespace at field end in tables.
14108 When deleting characters, in tables this function will insert whitespace in
14109 front of the next \"|\" separator, to keep the table aligned. The table will
14110 still be marked for re-alignment if the field did fill the entire column,
14111 because, in this case the deletion might narrow the column."
14112 (interactive "p")
14113 (if (and (org-table-p)
14114 (not (bolp))
14115 (not (= (char-after) ?|))
14116 (eq N 1))
14117 (if (looking-at ".*?|")
14118 (let ((pos (point))
14119 (noalign (looking-at "[^|\n\r]* |"))
14120 (c org-table-may-need-update))
14121 (replace-match (concat
14122 (substring (match-string 0) 1 -1)
14123 " |"))
14124 (goto-char pos)
14125 ;; noalign: if there were two spaces at the end, this field
14126 ;; does not determine the width of the column.
14127 (if noalign (setq org-table-may-need-update c)))
14128 (delete-char N))
14129 (delete-char N)
14130 (org-fix-tags-on-the-fly)))
14132 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14133 (put 'org-self-insert-command 'delete-selection t)
14134 (put 'orgtbl-self-insert-command 'delete-selection t)
14135 (put 'org-delete-char 'delete-selection 'supersede)
14136 (put 'org-delete-backward-char 'delete-selection 'supersede)
14137 (put 'org-yank 'delete-selection 'yank)
14139 ;; Make `flyspell-mode' delay after some commands
14140 (put 'org-self-insert-command 'flyspell-delayed t)
14141 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14142 (put 'org-delete-char 'flyspell-delayed t)
14143 (put 'org-delete-backward-char 'flyspell-delayed t)
14145 ;; Make pabbrev-mode expand after org-mode commands
14146 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14147 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14149 ;; How to do this: Measure non-white length of current string
14150 ;; If equal to column width, we should realign.
14152 (defun org-remap (map &rest commands)
14153 "In MAP, remap the functions given in COMMANDS.
14154 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14155 (let (new old)
14156 (while commands
14157 (setq old (pop commands) new (pop commands))
14158 (if (fboundp 'command-remapping)
14159 (org-defkey map (vector 'remap old) new)
14160 (substitute-key-definition old new map global-map)))))
14162 (when (eq org-enable-table-editor 'optimized)
14163 ;; If the user wants maximum table support, we need to hijack
14164 ;; some standard editing functions
14165 (org-remap org-mode-map
14166 'self-insert-command 'org-self-insert-command
14167 'delete-char 'org-delete-char
14168 'delete-backward-char 'org-delete-backward-char)
14169 (org-defkey org-mode-map "|" 'org-force-self-insert))
14171 (defvar org-ctrl-c-ctrl-c-hook nil
14172 "Hook for functions attaching themselves to `C-c C-c'.
14173 This can be used to add additional functionality to the C-c C-c key which
14174 executes context-dependent commands.
14175 Each function will be called with no arguments. The function must check
14176 if the context is appropriate for it to act. If yes, it should do its
14177 thing and then return a non-nil value. If the context is wrong,
14178 just do nothing and return nil.")
14180 (defvar org-tab-first-hook nil
14181 "Hook for functions to attach themselves to TAB.
14182 See `org-ctrl-c-ctrl-c-hook' for more information.
14183 This hook runs as the first action when TAB is pressed, even before
14184 `org-cycle' messes around with the `outline-regexp' to cater for
14185 inline tasks and plain list item folding.
14186 If any function in this hook returns t, not other actions like table
14187 field motion visibility cycling will be done.")
14189 (defvar org-tab-after-check-for-table-hook nil
14190 "Hook for functions to attach themselves to TAB.
14191 See `org-ctrl-c-ctrl-c-hook' for more information.
14192 This hook runs after it has been established that the cursor is not in a
14193 table, but before checking if the cursor is in a headline or if global cycling
14194 should be done.
14195 If any function in this hook returns t, not other actions like visibility
14196 cycling will be done.")
14198 (defvar org-tab-after-check-for-cycling-hook nil
14199 "Hook for functions to attach themselves to TAB.
14200 See `org-ctrl-c-ctrl-c-hook' for more information.
14201 This hook runs after it has been established that not table field motion and
14202 not visibility should be done because of current context. This is probably
14203 the place where a package like yasnippets can hook in.")
14205 (defvar org-metaleft-hook nil
14206 "Hook for functions attaching themselves to `M-left'.
14207 See `org-ctrl-c-ctrl-c-hook' for more information.")
14208 (defvar org-metaright-hook nil
14209 "Hook for functions attaching themselves to `M-right'.
14210 See `org-ctrl-c-ctrl-c-hook' for more information.")
14211 (defvar org-metaup-hook nil
14212 "Hook for functions attaching themselves to `M-up'.
14213 See `org-ctrl-c-ctrl-c-hook' for more information.")
14214 (defvar org-metadown-hook nil
14215 "Hook for functions attaching themselves to `M-down'.
14216 See `org-ctrl-c-ctrl-c-hook' for more information.")
14217 (defvar org-shiftmetaleft-hook nil
14218 "Hook for functions attaching themselves to `M-S-left'.
14219 See `org-ctrl-c-ctrl-c-hook' for more information.")
14220 (defvar org-shiftmetaright-hook nil
14221 "Hook for functions attaching themselves to `M-S-right'.
14222 See `org-ctrl-c-ctrl-c-hook' for more information.")
14223 (defvar org-shiftmetaup-hook nil
14224 "Hook for functions attaching themselves to `M-S-up'.
14225 See `org-ctrl-c-ctrl-c-hook' for more information.")
14226 (defvar org-shiftmetadown-hook nil
14227 "Hook for functions attaching themselves to `M-S-down'.
14228 See `org-ctrl-c-ctrl-c-hook' for more information.")
14229 (defvar org-metareturn-hook nil
14230 "Hook for functions attaching themselves to `M-RET'.
14231 See `org-ctrl-c-ctrl-c-hook' for more information.")
14233 (defun org-modifier-cursor-error ()
14234 "Throw an error, a modified cursor command was applied in wrong context."
14235 (error "This command is active in special context like tables, headlines or items"))
14237 (defun org-shiftselect-error ()
14238 "Throw an error because Shift-Cursor command was applied in wrong context."
14239 (if (and (boundp 'shift-select-mode) shift-select-mode)
14240 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14241 (error "This command works only in special context like headlines or timestamps.")))
14243 (defun org-call-for-shift-select (cmd)
14244 (let ((this-command-keys-shift-translated t))
14245 (call-interactively cmd)))
14247 (defun org-shifttab (&optional arg)
14248 "Global visibility cycling or move to previous table field.
14249 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14250 on context.
14251 See the individual commands for more information."
14252 (interactive "P")
14253 (cond
14254 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14255 ((integerp arg)
14256 (message "Content view to level: %d" arg)
14257 (org-content (prefix-numeric-value arg))
14258 (setq org-cycle-global-status 'overview))
14259 (t (call-interactively 'org-global-cycle))))
14261 (defun org-shiftmetaleft ()
14262 "Promote subtree or delete table column.
14263 Calls `org-promote-subtree', `org-outdent-item',
14264 or `org-table-delete-column', depending on context.
14265 See the individual commands for more information."
14266 (interactive)
14267 (cond
14268 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14269 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14270 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14271 ((org-at-item-p) (call-interactively 'org-outdent-item))
14272 (t (org-modifier-cursor-error))))
14274 (defun org-shiftmetaright ()
14275 "Demote subtree or insert table column.
14276 Calls `org-demote-subtree', `org-indent-item',
14277 or `org-table-insert-column', depending on context.
14278 See the individual commands for more information."
14279 (interactive)
14280 (cond
14281 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14282 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14283 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14284 ((org-at-item-p) (call-interactively 'org-indent-item))
14285 (t (org-modifier-cursor-error))))
14287 (defun org-shiftmetaup (&optional arg)
14288 "Move subtree up or kill table row.
14289 Calls `org-move-subtree-up' or `org-table-kill-row' or
14290 `org-move-item-up' depending on context. See the individual commands
14291 for more information."
14292 (interactive "P")
14293 (cond
14294 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14295 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14296 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14297 ((org-at-item-p) (call-interactively 'org-move-item-up))
14298 (t (org-modifier-cursor-error))))
14300 (defun org-shiftmetadown (&optional arg)
14301 "Move subtree down or insert table row.
14302 Calls `org-move-subtree-down' or `org-table-insert-row' or
14303 `org-move-item-down', depending on context. See the individual
14304 commands for more information."
14305 (interactive "P")
14306 (cond
14307 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14308 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14309 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14310 ((org-at-item-p) (call-interactively 'org-move-item-down))
14311 (t (org-modifier-cursor-error))))
14313 (defun org-metaleft (&optional arg)
14314 "Promote heading or move table column to left.
14315 Calls `org-do-promote' or `org-table-move-column', depending on context.
14316 With no specific context, calls the Emacs default `backward-word'.
14317 See the individual commands for more information."
14318 (interactive "P")
14319 (cond
14320 ((run-hook-with-args-until-success 'org-metaleft-hook))
14321 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14322 ((or (org-on-heading-p)
14323 (and (org-region-active-p)
14324 (save-excursion
14325 (goto-char (region-beginning))
14326 (org-on-heading-p))))
14327 (call-interactively 'org-do-promote))
14328 ((or (org-at-item-p)
14329 (and (org-region-active-p)
14330 (save-excursion
14331 (goto-char (region-beginning))
14332 (org-at-item-p))))
14333 (call-interactively 'org-outdent-item))
14334 (t (call-interactively 'backward-word))))
14336 (defun org-metaright (&optional arg)
14337 "Demote subtree or move table column to right.
14338 Calls `org-do-demote' or `org-table-move-column', depending on context.
14339 With no specific context, calls the Emacs default `forward-word'.
14340 See the individual commands for more information."
14341 (interactive "P")
14342 (cond
14343 ((run-hook-with-args-until-success 'org-metaright-hook))
14344 ((org-at-table-p) (call-interactively 'org-table-move-column))
14345 ((or (org-on-heading-p)
14346 (and (org-region-active-p)
14347 (save-excursion
14348 (goto-char (region-beginning))
14349 (org-on-heading-p))))
14350 (call-interactively 'org-do-demote))
14351 ((or (org-at-item-p)
14352 (and (org-region-active-p)
14353 (save-excursion
14354 (goto-char (region-beginning))
14355 (org-at-item-p))))
14356 (call-interactively 'org-indent-item))
14357 (t (call-interactively 'forward-word))))
14359 (defun org-metaup (&optional arg)
14360 "Move subtree up or move table row up.
14361 Calls `org-move-subtree-up' or `org-table-move-row' or
14362 `org-move-item-up', depending on context. See the individual commands
14363 for more information."
14364 (interactive "P")
14365 (cond
14366 ((run-hook-with-args-until-success 'org-metaup-hook))
14367 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14368 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14369 ((org-at-item-p) (call-interactively 'org-move-item-up))
14370 (t (transpose-lines 1) (beginning-of-line -1))))
14372 (defun org-metadown (&optional arg)
14373 "Move subtree down or move table row down.
14374 Calls `org-move-subtree-down' or `org-table-move-row' or
14375 `org-move-item-down', depending on context. See the individual
14376 commands for more information."
14377 (interactive "P")
14378 (cond
14379 ((run-hook-with-args-until-success 'org-metadown-hook))
14380 ((org-at-table-p) (call-interactively 'org-table-move-row))
14381 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14382 ((org-at-item-p) (call-interactively 'org-move-item-down))
14383 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14385 (defun org-shiftup (&optional arg)
14386 "Increase item in timestamp or increase priority of current headline.
14387 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14388 depending on context. See the individual commands for more information."
14389 (interactive "P")
14390 (cond
14391 ((and org-support-shift-select (org-region-active-p))
14392 (org-call-for-shift-select 'previous-line))
14393 ((org-at-timestamp-p t)
14394 (call-interactively (if org-edit-timestamp-down-means-later
14395 'org-timestamp-down 'org-timestamp-up)))
14396 ((and (not (eq org-support-shift-select 'always))
14397 org-enable-priority-commands
14398 (org-on-heading-p))
14399 (call-interactively 'org-priority-up))
14400 ((and (not org-support-shift-select) (org-at-item-p))
14401 (call-interactively 'org-previous-item))
14402 ((org-clocktable-try-shift 'up arg))
14403 (org-support-shift-select
14404 (org-call-for-shift-select 'previous-line))
14405 (t (org-shiftselect-error))))
14407 (defun org-shiftdown (&optional arg)
14408 "Decrease item in timestamp or decrease priority of current headline.
14409 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14410 depending on context. See the individual commands for more information."
14411 (interactive "P")
14412 (cond
14413 ((and org-support-shift-select (org-region-active-p))
14414 (org-call-for-shift-select 'next-line))
14415 ((org-at-timestamp-p t)
14416 (call-interactively (if org-edit-timestamp-down-means-later
14417 'org-timestamp-up 'org-timestamp-down)))
14418 ((and (not (eq org-support-shift-select 'always))
14419 org-enable-priority-commands
14420 (org-on-heading-p))
14421 (call-interactively 'org-priority-down))
14422 ((and (not org-support-shift-select) (org-at-item-p))
14423 (call-interactively 'org-next-item))
14424 ((org-clocktable-try-shift 'down arg))
14425 (org-support-shift-select
14426 (org-call-for-shift-select 'next-line))
14427 (t (org-shiftselect-error))))
14429 (defun org-shiftright (&optional arg)
14430 "Cycle the thing at point or in the current line, depending on context.
14431 Depending on context, this does one of the following:
14433 - switch a timestamp at point one day into the future
14434 - on a headline, switch to the next TODO keyword.
14435 - on an item, switch entire list to the next bullet type
14436 - on a property line, switch to the next allowed value
14437 - on a clocktable definition line, move time block into the future"
14438 (interactive "P")
14439 (cond
14440 ((and org-support-shift-select (org-region-active-p))
14441 (org-call-for-shift-select 'forward-char))
14442 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14443 ((and (not (eq org-support-shift-select 'always))
14444 (org-on-heading-p))
14445 (let ((org-inhibit-logging
14446 (not org-treat-S-cursor-todo-selection-as-state-change))
14447 (org-inhibit-blocking
14448 (not org-treat-S-cursor-todo-selection-as-state-change)))
14449 (org-call-with-arg 'org-todo 'right)))
14450 ((or (and org-support-shift-select
14451 (not (eq org-support-shift-select 'always))
14452 (org-at-item-bullet-p))
14453 (and (not org-support-shift-select) (org-at-item-p)))
14454 (org-call-with-arg 'org-cycle-list-bullet nil))
14455 ((and (not (eq org-support-shift-select 'always))
14456 (org-at-property-p))
14457 (call-interactively 'org-property-next-allowed-value))
14458 ((org-clocktable-try-shift 'right arg))
14459 (org-support-shift-select
14460 (org-call-for-shift-select 'forward-char))
14461 (t (org-shiftselect-error))))
14463 (defun org-shiftleft (&optional arg)
14464 "Cycle the thing at point or in the current line, depending on context.
14465 Depending on context, this does one of the following:
14467 - switch a timestamp at point one day into the past
14468 - on a headline, switch to the previous TODO keyword.
14469 - on an item, switch entire list to the previous bullet type
14470 - on a property line, switch to the previous allowed value
14471 - on a clocktable definition line, move time block into the past"
14472 (interactive "P")
14473 (cond
14474 ((and org-support-shift-select (org-region-active-p))
14475 (org-call-for-shift-select 'backward-char))
14476 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14477 ((and (not (eq org-support-shift-select 'always))
14478 (org-on-heading-p))
14479 (let ((org-inhibit-logging
14480 (not org-treat-S-cursor-todo-selection-as-state-change))
14481 (org-inhibit-blocking
14482 (not org-treat-S-cursor-todo-selection-as-state-change)))
14483 (org-call-with-arg 'org-todo 'left)))
14484 ((or (and org-support-shift-select
14485 (not (eq org-support-shift-select 'always))
14486 (org-at-item-bullet-p))
14487 (and (not org-support-shift-select) (org-at-item-p)))
14488 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14489 ((and (not (eq org-support-shift-select 'always))
14490 (org-at-property-p))
14491 (call-interactively 'org-property-previous-allowed-value))
14492 ((org-clocktable-try-shift 'left arg))
14493 (org-support-shift-select
14494 (org-call-for-shift-select 'backward-char))
14495 (t (org-shiftselect-error))))
14497 (defun org-shiftcontrolright ()
14498 "Switch to next TODO set."
14499 (interactive)
14500 (cond
14501 ((and org-support-shift-select (org-region-active-p))
14502 (org-call-for-shift-select 'forward-word))
14503 ((and (not (eq org-support-shift-select 'always))
14504 (org-on-heading-p))
14505 (org-call-with-arg 'org-todo 'nextset))
14506 (org-support-shift-select
14507 (org-call-for-shift-select 'forward-word))
14508 (t (org-shiftselect-error))))
14510 (defun org-shiftcontrolleft ()
14511 "Switch to previous TODO set."
14512 (interactive)
14513 (cond
14514 ((and org-support-shift-select (org-region-active-p))
14515 (org-call-for-shift-select 'backward-word))
14516 ((and (not (eq org-support-shift-select 'always))
14517 (org-on-heading-p))
14518 (org-call-with-arg 'org-todo 'previousset))
14519 (org-support-shift-select
14520 (org-call-for-shift-select 'backward-word))
14521 (t (org-shiftselect-error))))
14523 (defun org-ctrl-c-ret ()
14524 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14525 (interactive)
14526 (cond
14527 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14528 (t (call-interactively 'org-insert-heading))))
14530 (defun org-copy-special ()
14531 "Copy region in table or copy current subtree.
14532 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14533 See the individual commands for more information."
14534 (interactive)
14535 (call-interactively
14536 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14538 (defun org-cut-special ()
14539 "Cut region in table or cut current subtree.
14540 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14541 See the individual commands for more information."
14542 (interactive)
14543 (call-interactively
14544 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14546 (defun org-paste-special (arg)
14547 "Paste rectangular region into table, or past subtree relative to level.
14548 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14549 See the individual commands for more information."
14550 (interactive "P")
14551 (if (org-at-table-p)
14552 (org-table-paste-rectangle)
14553 (org-paste-subtree arg)))
14555 (defun org-edit-special ()
14556 "Call a special editor for the stuff at point.
14557 When at a table, call the formula editor with `org-table-edit-formulas'.
14558 When at the first line of an src example, call `org-edit-src-code'.
14559 When in an #+include line, visit the include file. Otherwise call
14560 `ffap' to visit the file at point."
14561 (interactive)
14562 (cond
14563 ((org-at-table-p)
14564 (call-interactively 'org-table-edit-formulas))
14565 ((save-excursion
14566 (beginning-of-line 1)
14567 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14568 (find-file (org-trim (match-string 1))))
14569 ((org-edit-src-code))
14570 ((org-edit-fixed-width-region))
14571 (t (call-interactively 'ffap))))
14574 (defun org-ctrl-c-ctrl-c (&optional arg)
14575 "Set tags in headline, or update according to changed information at point.
14577 This command does many different things, depending on context:
14579 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14580 this is what we do.
14582 - If the cursor is in a headline, prompt for tags and insert them
14583 into the current line, aligned to `org-tags-column'. When called
14584 with prefix arg, realign all tags in the current buffer.
14586 - If the cursor is in one of the special #+KEYWORD lines, this
14587 triggers scanning the buffer for these lines and updating the
14588 information.
14590 - If the cursor is inside a table, realign the table. This command
14591 works even if the automatic table editor has been turned off.
14593 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14594 the entire table.
14596 - If the cursor is at a footnote reference or definition, jump to
14597 the corresponding definition or references, respectively.
14599 - If the cursor is a the beginning of a dynamic block, update it.
14601 - If the cursor is inside a table created by the table.el package,
14602 activate that table.
14604 - If the current buffer is a remember buffer, close note and file
14605 it. A prefix argument of 1 files to the default location
14606 without further interaction. A prefix argument of 2 files to
14607 the currently clocking task.
14609 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14610 links in this buffer.
14612 - If the cursor is on a numbered item in a plain list, renumber the
14613 ordered list.
14615 - If the cursor is on a checkbox, toggle it."
14616 (interactive "P")
14617 (let ((org-enable-table-editor t))
14618 (cond
14619 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14620 org-occur-highlights
14621 org-latex-fragment-image-overlays)
14622 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14623 (org-remove-occur-highlights)
14624 (org-remove-latex-fragment-image-overlays)
14625 (message "Temporary highlights/overlays removed from current buffer"))
14626 ((and (local-variable-p 'org-finish-function (current-buffer))
14627 (fboundp org-finish-function))
14628 (funcall org-finish-function))
14629 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14630 ((org-at-property-p)
14631 (call-interactively 'org-property-action))
14632 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14633 ((org-on-heading-p) (call-interactively 'org-set-tags))
14634 ((org-at-table.el-p)
14635 (require 'table)
14636 (beginning-of-line 1)
14637 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14638 (call-interactively 'table-recognize-table))
14639 ((org-at-table-p)
14640 (org-table-maybe-eval-formula)
14641 (if arg
14642 (call-interactively 'org-table-recalculate)
14643 (org-table-maybe-recalculate-line))
14644 (call-interactively 'org-table-align))
14645 ((or (org-footnote-at-reference-p)
14646 (org-footnote-at-definition-p))
14647 (call-interactively 'org-footnote-action))
14648 ((org-at-item-checkbox-p)
14649 (call-interactively 'org-toggle-checkbox))
14650 ((org-at-item-p)
14651 (if arg
14652 (call-interactively 'org-toggle-checkbox)
14653 (call-interactively 'org-maybe-renumber-ordered-list)))
14654 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14655 ;; Dynamic block
14656 (beginning-of-line 1)
14657 (save-excursion (org-update-dblock)))
14658 ((save-excursion
14659 (beginning-of-line 1)
14660 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
14661 (cond
14662 ((equal (match-string 1) "TBLFM")
14663 ;; Recalculate the table before this line
14664 (save-excursion
14665 (beginning-of-line 1)
14666 (skip-chars-backward " \r\n\t")
14667 (if (org-at-table-p)
14668 (org-call-with-arg 'org-table-recalculate t))))
14670 ; (org-set-regexps-and-options)
14671 ; (org-restart-font-lock)
14672 (let ((org-inhibit-startup t)) (org-mode-restart))
14673 (message "Local setup has been refreshed"))))
14674 ((org-clock-update-time-maybe))
14675 (t (error "C-c C-c can do nothing useful at this location.")))))
14677 (defun org-mode-restart ()
14678 "Restart Org-mode, to scan again for special lines.
14679 Also updates the keyword regular expressions."
14680 (interactive)
14681 (org-mode)
14682 (message "Org-mode restarted"))
14684 (defun org-kill-note-or-show-branches ()
14685 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14686 (interactive)
14687 (if (not org-finish-function)
14688 (call-interactively 'show-branches)
14689 (let ((org-note-abort t))
14690 (funcall org-finish-function))))
14692 (defun org-return (&optional indent)
14693 "Goto next table row or insert a newline.
14694 Calls `org-table-next-row' or `newline', depending on context.
14695 See the individual commands for more information."
14696 (interactive)
14697 (cond
14698 ((bobp) (if indent (newline-and-indent) (newline)))
14699 ((org-at-table-p)
14700 (org-table-justify-field-maybe)
14701 (call-interactively 'org-table-next-row))
14702 ((and org-return-follows-link
14703 (eq (get-text-property (point) 'face) 'org-link))
14704 (call-interactively 'org-open-at-point))
14705 ((and (org-at-heading-p)
14706 (looking-at
14707 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14708 (org-show-entry)
14709 (end-of-line 1)
14710 (newline))
14711 (t (if indent (newline-and-indent) (newline)))))
14713 (defun org-return-indent ()
14714 "Goto next table row or insert a newline and indent.
14715 Calls `org-table-next-row' or `newline-and-indent', depending on
14716 context. See the individual commands for more information."
14717 (interactive)
14718 (org-return t))
14720 (defun org-ctrl-c-star ()
14721 "Compute table, or change heading status of lines.
14722 Calls `org-table-recalculate' or `org-toggle-heading',
14723 depending on context."
14724 (interactive)
14725 (cond
14726 ((org-at-table-p)
14727 (call-interactively 'org-table-recalculate))
14729 ;; Convert all lines in region to list items
14730 (call-interactively 'org-toggle-heading))))
14732 (defun org-ctrl-c-minus ()
14733 "Insert separator line in table or modify bullet status of line.
14734 Also turns a plain line or a region of lines into list items.
14735 Calls `org-table-insert-hline', `org-toggle-item', or
14736 `org-cycle-list-bullet', depending on context."
14737 (interactive)
14738 (cond
14739 ((org-at-table-p)
14740 (call-interactively 'org-table-insert-hline))
14741 ((org-region-active-p)
14742 (call-interactively 'org-toggle-item))
14743 ((org-in-item-p)
14744 (call-interactively 'org-cycle-list-bullet))
14746 (call-interactively 'org-toggle-item))))
14748 (defun org-toggle-item ()
14749 "Convert headings or normal lines to items, items to normal lines.
14750 If there is no active region, only the current line is considered.
14752 If the first line in the region is a headline, convert all headlines to items.
14754 If the first line in the region is an item, convert all items to normal lines.
14756 If the first line is normal text, add an item bullet to each line."
14757 (interactive)
14758 (let (l2 l beg end)
14759 (if (org-region-active-p)
14760 (setq beg (region-beginning) end (region-end))
14761 (setq beg (point-at-bol)
14762 end (min (1+ (point-at-eol)) (point-max))))
14763 (save-excursion
14764 (goto-char end)
14765 (setq l2 (org-current-line))
14766 (goto-char beg)
14767 (beginning-of-line 1)
14768 (setq l (1- (org-current-line)))
14769 (if (org-at-item-p)
14770 ;; We already have items, de-itemize
14771 (while (< (setq l (1+ l)) l2)
14772 (when (org-at-item-p)
14773 (goto-char (match-beginning 2))
14774 (delete-region (match-beginning 2) (match-end 2))
14775 (and (looking-at "[ \t]+") (replace-match "")))
14776 (beginning-of-line 2))
14777 (if (org-on-heading-p)
14778 ;; Headings, convert to items
14779 (while (< (setq l (1+ l)) l2)
14780 (if (looking-at org-outline-regexp)
14781 (replace-match "- " t t))
14782 (beginning-of-line 2))
14783 ;; normal lines, turn them into items
14784 (while (< (setq l (1+ l)) l2)
14785 (unless (org-at-item-p)
14786 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14787 (replace-match "\\1- \\2")))
14788 (beginning-of-line 2)))))))
14790 (defun org-toggle-heading (&optional nstars)
14791 "Convert headings to normal text, or items or text to headings.
14792 If there is no active region, only the current line is considered.
14794 If the first line is a heading, remove the stars from all headlines
14795 in the region.
14797 If the first line is a plain list item, turn all plain list items into
14798 headings.
14800 If the first line is a normal line, turn each and every line in the region
14801 into a heading.
14803 When converting a line into a heading, the number of stars is chosen
14804 such that the lines become children of the current entry. However, when
14805 a prefix argument is given, its value determines the number of stars to add."
14806 (interactive "P")
14807 (let (l2 l itemp beg end)
14808 (if (org-region-active-p)
14809 (setq beg (region-beginning) end (region-end))
14810 (setq beg (point-at-bol)
14811 end (min (1+ (point-at-eol)) (point-max))))
14812 (save-excursion
14813 (goto-char end)
14814 (setq l2 (org-current-line))
14815 (goto-char beg)
14816 (beginning-of-line 1)
14817 (setq l (1- (org-current-line)))
14818 (if (org-on-heading-p)
14819 ;; We already have headlines, de-star them
14820 (while (< (setq l (1+ l)) l2)
14821 (when (org-on-heading-p t)
14822 (and (looking-at outline-regexp) (replace-match "")))
14823 (beginning-of-line 2))
14824 (setq itemp (org-at-item-p))
14825 (let* ((stars
14826 (if nstars
14827 (make-string (prefix-numeric-value current-prefix-arg)
14829 (save-excursion
14830 (re-search-backward org-complex-heading-regexp nil t)
14831 (or (match-string 1) ""))))
14832 (add-stars (cond (nstars "")
14833 ((equal stars "") "*")
14834 (org-odd-levels-only "**")
14835 (t "*")))
14836 (rpl (concat stars add-stars " ")))
14837 (while (< (setq l (1+ l)) l2)
14838 (if itemp
14839 (and (org-at-item-p) (replace-match rpl t t))
14840 (unless (org-on-heading-p)
14841 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14842 (replace-match (concat rpl (match-string 2))))))
14843 (beginning-of-line 2)))))))
14845 (defun org-meta-return (&optional arg)
14846 "Insert a new heading or wrap a region in a table.
14847 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14848 See the individual commands for more information."
14849 (interactive "P")
14850 (cond
14851 ((run-hook-with-args-until-success 'org-metareturn-hook))
14852 ((org-at-table-p)
14853 (call-interactively 'org-table-wrap-region))
14854 (t (call-interactively 'org-insert-heading))))
14856 ;;; Menu entries
14858 ;; Define the Org-mode menus
14859 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14860 '("Tbl"
14861 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14862 ["Next Field" org-cycle (org-at-table-p)]
14863 ["Previous Field" org-shifttab (org-at-table-p)]
14864 ["Next Row" org-return (org-at-table-p)]
14865 "--"
14866 ["Blank Field" org-table-blank-field (org-at-table-p)]
14867 ["Edit Field" org-table-edit-field (org-at-table-p)]
14868 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14869 "--"
14870 ("Column"
14871 ["Move Column Left" org-metaleft (org-at-table-p)]
14872 ["Move Column Right" org-metaright (org-at-table-p)]
14873 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14874 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14875 ("Row"
14876 ["Move Row Up" org-metaup (org-at-table-p)]
14877 ["Move Row Down" org-metadown (org-at-table-p)]
14878 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14879 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14880 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14881 "--"
14882 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14883 ("Rectangle"
14884 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14885 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14886 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14887 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14888 "--"
14889 ("Calculate"
14890 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14891 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14892 ["Edit Formulas" org-edit-special (org-at-table-p)]
14893 "--"
14894 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14895 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14896 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14897 "--"
14898 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14899 "--"
14900 ["Sum Column/Rectangle" org-table-sum
14901 (or (org-at-table-p) (org-region-active-p))]
14902 ["Which Column?" org-table-current-column (org-at-table-p)])
14903 ["Debug Formulas"
14904 org-table-toggle-formula-debugger
14905 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14906 ["Show Col/Row Numbers"
14907 org-table-toggle-coordinate-overlays
14908 :style toggle
14909 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14910 "--"
14911 ["Create" org-table-create (and (not (org-at-table-p))
14912 org-enable-table-editor)]
14913 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14914 ["Import from File" org-table-import (not (org-at-table-p))]
14915 ["Export to File" org-table-export (org-at-table-p)]
14916 "--"
14917 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14919 (easy-menu-define org-org-menu org-mode-map "Org menu"
14920 '("Org"
14921 ("Show/Hide"
14922 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14923 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14924 ["Sparse Tree..." org-sparse-tree t]
14925 ["Reveal Context" org-reveal t]
14926 ["Show All" show-all t]
14927 "--"
14928 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14929 "--"
14930 ["New Heading" org-insert-heading t]
14931 ("Navigate Headings"
14932 ["Up" outline-up-heading t]
14933 ["Next" outline-next-visible-heading t]
14934 ["Previous" outline-previous-visible-heading t]
14935 ["Next Same Level" outline-forward-same-level t]
14936 ["Previous Same Level" outline-backward-same-level t]
14937 "--"
14938 ["Jump" org-goto t])
14939 ("Edit Structure"
14940 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14941 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14942 "--"
14943 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14944 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14945 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14946 "--"
14947 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14948 "--"
14949 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14950 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14951 ["Demote Heading" org-metaright (not (org-at-table-p))]
14952 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14953 "--"
14954 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14955 "--"
14956 ["Convert to odd levels" org-convert-to-odd-levels t]
14957 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14958 ("Editing"
14959 ["Emphasis..." org-emphasize t]
14960 ["Edit Source Example" org-edit-special t]
14961 "--"
14962 ["Footnote new/jump" org-footnote-action t]
14963 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14964 ("Archive"
14965 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14966 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14967 ; :active t :keys "C-u C-c C-x C-a"]
14968 ["Sparse trees open ARCHIVE trees"
14969 (setq org-sparse-tree-open-archived-trees
14970 (not org-sparse-tree-open-archived-trees))
14971 :style toggle :selected org-sparse-tree-open-archived-trees]
14972 ["Cycling opens ARCHIVE trees"
14973 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14974 :style toggle :selected org-cycle-open-archived-trees]
14975 "--"
14976 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14977 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14978 ; ["Check and Move Children" (org-archive-subtree '(4))
14979 ; :active t :keys "C-u C-c C-x C-s"]
14981 "--"
14982 ("Hyperlinks"
14983 ["Store Link (Global)" org-store-link t]
14984 ["Insert Link" org-insert-link t]
14985 ["Follow Link" org-open-at-point t]
14986 "--"
14987 ["Next link" org-next-link t]
14988 ["Previous link" org-previous-link t]
14989 "--"
14990 ["Descriptive Links"
14991 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14992 :style radio
14993 :selected (member '(org-link) buffer-invisibility-spec)]
14994 ["Literal Links"
14995 (progn
14996 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14997 :style radio
14998 :selected (not (member '(org-link) buffer-invisibility-spec))])
14999 "--"
15000 ("TODO Lists"
15001 ["TODO/DONE/-" org-todo t]
15002 ("Select keyword"
15003 ["Next keyword" org-shiftright (org-on-heading-p)]
15004 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15005 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15006 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15007 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15008 ["Show TODO Tree" org-show-todo-tree t]
15009 ["Global TODO list" org-todo-list t]
15010 "--"
15011 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15012 :selected org-enforce-todo-dependencies :style toggle :active t]
15013 "Settings for tree at point"
15014 ["Do Children sequentially" org-toggle-ordered-property :style radio
15015 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15016 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15017 ["Do Children parallel" org-toggle-ordered-property :style radio
15018 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15019 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15020 "--"
15021 ["Set Priority" org-priority t]
15022 ["Priority Up" org-shiftup t]
15023 ["Priority Down" org-shiftdown t]
15024 "--"
15025 ["Get news from all feeds" org-feed-update-all t]
15026 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15027 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15028 ("TAGS and Properties"
15029 ["Set Tags" org-set-tags-command t]
15030 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15031 "--"
15032 ["Set property" org-set-property t]
15033 ["Column view of properties" org-columns t]
15034 ["Insert Column View DBlock" org-insert-columns-dblock t])
15035 ("Dates and Scheduling"
15036 ["Timestamp" org-time-stamp t]
15037 ["Timestamp (inactive)" org-time-stamp-inactive t]
15038 ("Change Date"
15039 ["1 Day Later" org-shiftright t]
15040 ["1 Day Earlier" org-shiftleft t]
15041 ["1 ... Later" org-shiftup t]
15042 ["1 ... Earlier" org-shiftdown t])
15043 ["Compute Time Range" org-evaluate-time-range t]
15044 ["Schedule Item" org-schedule t]
15045 ["Deadline" org-deadline t]
15046 "--"
15047 ["Custom time format" org-toggle-time-stamp-overlays
15048 :style radio :selected org-display-custom-times]
15049 "--"
15050 ["Goto Calendar" org-goto-calendar t]
15051 ["Date from Calendar" org-date-from-calendar t]
15052 "--"
15053 ["Start/Restart Timer" org-timer-start t]
15054 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15055 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15056 ["Insert Timer String" org-timer t]
15057 ["Insert Timer Item" org-timer-item t])
15058 ("Logging work"
15059 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15060 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15061 ["Clock out" org-clock-out t]
15062 ["Clock cancel" org-clock-cancel t]
15063 "--"
15064 ["Mark as default task" org-clock-mark-default-task t]
15065 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15066 ["Goto running clock" org-clock-goto t]
15067 "--"
15068 ["Display times" org-clock-display t]
15069 ["Create clock table" org-clock-report t]
15070 "--"
15071 ["Record DONE time"
15072 (progn (setq org-log-done (not org-log-done))
15073 (message "Switching to %s will %s record a timestamp"
15074 (car org-done-keywords)
15075 (if org-log-done "automatically" "not")))
15076 :style toggle :selected org-log-done])
15077 "--"
15078 ["Agenda Command..." org-agenda t]
15079 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15080 ("File List for Agenda")
15081 ("Special views current file"
15082 ["TODO Tree" org-show-todo-tree t]
15083 ["Check Deadlines" org-check-deadlines t]
15084 ["Timeline" org-timeline t]
15085 ["Tags/Property tree" org-match-sparse-tree t])
15086 "--"
15087 ["Export/Publish..." org-export t]
15088 ("LaTeX"
15089 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15090 :selected org-cdlatex-mode]
15091 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15092 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15093 ["Modify math symbol" org-cdlatex-math-modify
15094 (org-inside-LaTeX-fragment-p)]
15095 ["Insert citation" org-reftex-citation t]
15096 "--"
15097 ["Export LaTeX fragments as images"
15098 (if (featurep 'org-exp)
15099 (setq org-export-with-LaTeX-fragments
15100 (not org-export-with-LaTeX-fragments))
15101 (require 'org-exp))
15102 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15103 org-export-with-LaTeX-fragments)])
15104 "--"
15105 ("Documentation"
15106 ["Show Version" org-version t]
15107 ["Info Documentation" org-info t])
15108 ("Customize"
15109 ["Browse Org Group" org-customize t]
15110 "--"
15111 ["Expand This Menu" org-create-customize-menu
15112 (fboundp 'customize-menu-create)])
15113 "--"
15114 ("Refresh/Reload"
15115 ["Refresh setup current buffer" org-mode-restart t]
15116 ["Reload Org (after update)" org-reload t]
15117 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15120 (defun org-info (&optional node)
15121 "Read documentation for Org-mode in the info system.
15122 With optional NODE, go directly to that node."
15123 (interactive)
15124 (info (format "(org)%s" (or node ""))))
15126 (defun org-install-agenda-files-menu ()
15127 (let ((bl (buffer-list)))
15128 (save-excursion
15129 (while bl
15130 (set-buffer (pop bl))
15131 (if (org-mode-p) (setq bl nil)))
15132 (when (org-mode-p)
15133 (easy-menu-change
15134 '("Org") "File List for Agenda"
15135 (append
15136 (list
15137 ["Edit File List" (org-edit-agenda-file-list) t]
15138 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15139 ["Remove Current File from List" org-remove-file t]
15140 ["Cycle through agenda files" org-cycle-agenda-files t]
15141 ["Occur in all agenda files" org-occur-in-agenda-files t]
15142 "--")
15143 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15145 ;;;; Documentation
15147 ;;;###autoload
15148 (defun org-require-autoloaded-modules ()
15149 (interactive)
15150 (mapc 'require
15151 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15152 org-docbook org-exp org-html org-icalendar
15153 org-id org-latex
15154 org-publish org-remember org-table
15155 org-timer org-xoxo)))
15157 ;;;###autoload
15158 (defun org-reload (&optional uncompiled)
15159 "Reload all org lisp files.
15160 With prefix arg UNCOMPILED, load the uncompiled versions."
15161 (interactive "P")
15162 (require 'find-func)
15163 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15164 (dir-org (file-name-directory (org-find-library-name "org")))
15165 (dir-org-contrib (ignore-errors
15166 (file-name-directory
15167 (org-find-library-name "org-contribdir"))))
15168 (files
15169 (append (directory-files dir-org t file-re)
15170 (and dir-org-contrib
15171 (directory-files dir-org-contrib t file-re))))
15172 (remove-re (concat (if (featurep 'xemacs)
15173 "org-colview" "org-colview-xemacs")
15174 "\\'")))
15175 (setq files (mapcar 'file-name-sans-extension files))
15176 (setq files (mapcar
15177 (lambda (x) (if (string-match remove-re x) nil x))
15178 files))
15179 (setq files (delq nil files))
15180 (mapc
15181 (lambda (f)
15182 (when (featurep (intern (file-name-nondirectory f)))
15183 (if (and (not uncompiled)
15184 (file-exists-p (concat f ".elc")))
15185 (load (concat f ".elc") nil nil t)
15186 (load (concat f ".el") nil nil t))))
15187 files))
15188 (org-version))
15190 ;;;###autoload
15191 (defun org-customize ()
15192 "Call the customize function with org as argument."
15193 (interactive)
15194 (org-load-modules-maybe)
15195 (org-require-autoloaded-modules)
15196 (customize-browse 'org))
15198 (defun org-create-customize-menu ()
15199 "Create a full customization menu for Org-mode, insert it into the menu."
15200 (interactive)
15201 (org-load-modules-maybe)
15202 (org-require-autoloaded-modules)
15203 (if (fboundp 'customize-menu-create)
15204 (progn
15205 (easy-menu-change
15206 '("Org") "Customize"
15207 `(["Browse Org group" org-customize t]
15208 "--"
15209 ,(customize-menu-create 'org)
15210 ["Set" Custom-set t]
15211 ["Save" Custom-save t]
15212 ["Reset to Current" Custom-reset-current t]
15213 ["Reset to Saved" Custom-reset-saved t]
15214 ["Reset to Standard Settings" Custom-reset-standard t]))
15215 (message "\"Org\"-menu now contains full customization menu"))
15216 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15218 ;;;; Miscellaneous stuff
15220 ;;; Generally useful functions
15222 (defun org-find-text-property-in-string (prop s)
15223 "Return the first non-nil value of property PROP in string S."
15224 (or (get-text-property 0 prop s)
15225 (get-text-property (or (next-single-property-change 0 prop s) 0)
15226 prop s)))
15228 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15229 "Display the given MESSAGE as a warning."
15230 (if (fboundp 'display-warning)
15231 (display-warning 'org message
15232 (if (featurep 'xemacs)
15233 'warning
15234 :warning))
15235 (let ((buf (get-buffer-create "*Org warnings*")))
15236 (with-current-buffer buf
15237 (goto-char (point-max))
15238 (insert "Warning (Org): " message)
15239 (unless (bolp)
15240 (newline)))
15241 (display-buffer buf)
15242 (sit-for 0))))
15244 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15245 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15246 (if (and marker (marker-buffer marker)
15247 (buffer-live-p (marker-buffer marker)))
15248 (progn
15249 (switch-to-buffer (marker-buffer marker))
15250 (if (or (> marker (point-max)) (< marker (point-min)))
15251 (widen))
15252 (goto-char marker)
15253 (org-show-context 'org-goto))
15254 (if bookmark
15255 (bookmark-jump bookmark)
15256 (error "Cannot find location"))))
15258 (defun org-quote-csv-field (s)
15259 "Quote field for inclusion in CSV material."
15260 (if (string-match "[\",]" s)
15261 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15264 (defun org-plist-delete (plist property)
15265 "Delete PROPERTY from PLIST.
15266 This is in contrast to merely setting it to 0."
15267 (let (p)
15268 (while plist
15269 (if (not (eq property (car plist)))
15270 (setq p (plist-put p (car plist) (nth 1 plist))))
15271 (setq plist (cddr plist)))
15274 (defun org-force-self-insert (N)
15275 "Needed to enforce self-insert under remapping."
15276 (interactive "p")
15277 (self-insert-command N))
15279 (defun org-string-width (s)
15280 "Compute width of string, ignoring invisible characters.
15281 This ignores character with invisibility property `org-link', and also
15282 characters with property `org-cwidth', because these will become invisible
15283 upon the next fontification round."
15284 (let (b l)
15285 (when (or (eq t buffer-invisibility-spec)
15286 (assq 'org-link buffer-invisibility-spec))
15287 (while (setq b (text-property-any 0 (length s)
15288 'invisible 'org-link s))
15289 (setq s (concat (substring s 0 b)
15290 (substring s (or (next-single-property-change
15291 b 'invisible s) (length s)))))))
15292 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15293 (setq s (concat (substring s 0 b)
15294 (substring s (or (next-single-property-change
15295 b 'org-cwidth s) (length s))))))
15296 (setq l (string-width s) b -1)
15297 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15298 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15301 (defun org-get-indentation (&optional line)
15302 "Get the indentation of the current line, interpreting tabs.
15303 When LINE is given, assume it represents a line and compute its indentation."
15304 (if line
15305 (if (string-match "^ *" (org-remove-tabs line))
15306 (match-end 0))
15307 (save-excursion
15308 (beginning-of-line 1)
15309 (skip-chars-forward " \t")
15310 (current-column))))
15312 (defun org-remove-tabs (s &optional width)
15313 "Replace tabulators in S with spaces.
15314 Assumes that s is a single line, starting in column 0."
15315 (setq width (or width tab-width))
15316 (while (string-match "\t" s)
15317 (setq s (replace-match
15318 (make-string
15319 (- (* width (/ (+ (match-beginning 0) width) width))
15320 (match-beginning 0)) ?\ )
15321 t t s)))
15324 (defun org-fix-indentation (line ind)
15325 "Fix indentation in LINE.
15326 IND is a cons cell with target and minimum indentation.
15327 If the current indentation in LINE is smaller than the minimum,
15328 leave it alone. If it is larger than ind, set it to the target."
15329 (let* ((l (org-remove-tabs line))
15330 (i (org-get-indentation l))
15331 (i1 (car ind)) (i2 (cdr ind)))
15332 (if (>= i i2) (setq l (substring line i2)))
15333 (if (> i1 0)
15334 (concat (make-string i1 ?\ ) l)
15335 l)))
15337 (defun org-remove-indentation (code &optional n)
15338 "Remove the maximum common indentation from the lines in CODE.
15339 N may optionally be the number of spaces to remove."
15340 (with-temp-buffer
15341 (insert code)
15342 (org-do-remove-indentation n)
15343 (buffer-string)))
15345 (defun org-do-remove-indentation (&optional n)
15346 "Remove the maximum common indentation from the buffer."
15347 (untabify (point-min) (point-max))
15348 (let ((min 10000) re)
15349 (if n
15350 (setq min n)
15351 (goto-char (point-min))
15352 (while (re-search-forward "^ *[^ \n]" nil t)
15353 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
15354 (unless (or (= min 0) (= min 10000))
15355 (setq re (format "^ \\{%d\\}" min))
15356 (goto-char (point-min))
15357 (while (re-search-forward re nil t)
15358 (replace-match "")
15359 (end-of-line 1))
15360 min)))
15362 (defun org-base-buffer (buffer)
15363 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15364 (if (not buffer)
15365 buffer
15366 (or (buffer-base-buffer buffer)
15367 buffer)))
15369 (defun org-trim (s)
15370 "Remove whitespace at beginning and end of string."
15371 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15372 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15375 (defun org-wrap (string &optional width lines)
15376 "Wrap string to either a number of lines, or a width in characters.
15377 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15378 that costs. If there is a word longer than WIDTH, the text is actually
15379 wrapped to the length of that word.
15380 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15381 many lines, whatever width that takes.
15382 The return value is a list of lines, without newlines at the end."
15383 (let* ((words (org-split-string string "[ \t\n]+"))
15384 (maxword (apply 'max (mapcar 'org-string-width words)))
15385 w ll)
15386 (cond (width
15387 (org-do-wrap words (max maxword width)))
15388 (lines
15389 (setq w maxword)
15390 (setq ll (org-do-wrap words maxword))
15391 (if (<= (length ll) lines)
15393 (setq ll words)
15394 (while (> (length ll) lines)
15395 (setq w (1+ w))
15396 (setq ll (org-do-wrap words w)))
15397 ll))
15398 (t (error "Cannot wrap this")))))
15400 (defun org-do-wrap (words width)
15401 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15402 (let (lines line)
15403 (while words
15404 (setq line (pop words))
15405 (while (and words (< (+ (length line) (length (car words))) width))
15406 (setq line (concat line " " (pop words))))
15407 (setq lines (push line lines)))
15408 (nreverse lines)))
15410 (defun org-split-string (string &optional separators)
15411 "Splits STRING into substrings at SEPARATORS.
15412 No empty strings are returned if there are matches at the beginning
15413 and end of string."
15414 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15415 (start 0)
15416 notfirst
15417 (list nil))
15418 (while (and (string-match rexp string
15419 (if (and notfirst
15420 (= start (match-beginning 0))
15421 (< start (length string)))
15422 (1+ start) start))
15423 (< (match-beginning 0) (length string)))
15424 (setq notfirst t)
15425 (or (eq (match-beginning 0) 0)
15426 (and (eq (match-beginning 0) (match-end 0))
15427 (eq (match-beginning 0) start))
15428 (setq list
15429 (cons (substring string start (match-beginning 0))
15430 list)))
15431 (setq start (match-end 0)))
15432 (or (eq start (length string))
15433 (setq list
15434 (cons (substring string start)
15435 list)))
15436 (nreverse list)))
15438 (defun org-quote-vert (s)
15439 "Replace \"|\" with \"\\vert\"."
15440 (while (string-match "|" s)
15441 (setq s (replace-match "\\vert" t t s)))
15444 (defun org-uuidgen-p (s)
15445 "Is S an ID created by UUIDGEN?"
15446 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15448 (defun org-context ()
15449 "Return a list of contexts of the current cursor position.
15450 If several contexts apply, all are returned.
15451 Each context entry is a list with a symbol naming the context, and
15452 two positions indicating start and end of the context. Possible
15453 contexts are:
15455 :headline anywhere in a headline
15456 :headline-stars on the leading stars in a headline
15457 :todo-keyword on a TODO keyword (including DONE) in a headline
15458 :tags on the TAGS in a headline
15459 :priority on the priority cookie in a headline
15460 :item on the first line of a plain list item
15461 :item-bullet on the bullet/number of a plain list item
15462 :checkbox on the checkbox in a plain list item
15463 :table in an org-mode table
15464 :table-special on a special filed in a table
15465 :table-table in a table.el table
15466 :link on a hyperlink
15467 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15468 :target on a <<target>>
15469 :radio-target on a <<<radio-target>>>
15470 :latex-fragment on a LaTeX fragment
15471 :latex-preview on a LaTeX fragment with overlayed preview image
15473 This function expects the position to be visible because it uses font-lock
15474 faces as a help to recognize the following contexts: :table-special, :link,
15475 and :keyword."
15476 (let* ((f (get-text-property (point) 'face))
15477 (faces (if (listp f) f (list f)))
15478 (p (point)) clist o)
15479 ;; First the large context
15480 (cond
15481 ((org-on-heading-p t)
15482 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15483 (when (progn
15484 (beginning-of-line 1)
15485 (looking-at org-todo-line-tags-regexp))
15486 (push (org-point-in-group p 1 :headline-stars) clist)
15487 (push (org-point-in-group p 2 :todo-keyword) clist)
15488 (push (org-point-in-group p 4 :tags) clist))
15489 (goto-char p)
15490 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15491 (if (looking-at "\\[#[A-Z0-9]\\]")
15492 (push (org-point-in-group p 0 :priority) clist)))
15494 ((org-at-item-p)
15495 (push (org-point-in-group p 2 :item-bullet) clist)
15496 (push (list :item (point-at-bol)
15497 (save-excursion (org-end-of-item) (point)))
15498 clist)
15499 (and (org-at-item-checkbox-p)
15500 (push (org-point-in-group p 0 :checkbox) clist)))
15502 ((org-at-table-p)
15503 (push (list :table (org-table-begin) (org-table-end)) clist)
15504 (if (memq 'org-formula faces)
15505 (push (list :table-special
15506 (previous-single-property-change p 'face)
15507 (next-single-property-change p 'face)) clist)))
15508 ((org-at-table-p 'any)
15509 (push (list :table-table) clist)))
15510 (goto-char p)
15512 ;; Now the small context
15513 (cond
15514 ((org-at-timestamp-p)
15515 (push (org-point-in-group p 0 :timestamp) clist))
15516 ((memq 'org-link faces)
15517 (push (list :link
15518 (previous-single-property-change p 'face)
15519 (next-single-property-change p 'face)) clist))
15520 ((memq 'org-special-keyword faces)
15521 (push (list :keyword
15522 (previous-single-property-change p 'face)
15523 (next-single-property-change p 'face)) clist))
15524 ((org-on-target-p)
15525 (push (org-point-in-group p 0 :target) clist)
15526 (goto-char (1- (match-beginning 0)))
15527 (if (looking-at org-radio-target-regexp)
15528 (push (org-point-in-group p 0 :radio-target) clist))
15529 (goto-char p))
15530 ((setq o (car (delq nil
15531 (mapcar
15532 (lambda (x)
15533 (if (memq x org-latex-fragment-image-overlays) x))
15534 (org-overlays-at (point))))))
15535 (push (list :latex-fragment
15536 (org-overlay-start o) (org-overlay-end o)) clist)
15537 (push (list :latex-preview
15538 (org-overlay-start o) (org-overlay-end o)) clist))
15539 ((org-inside-LaTeX-fragment-p)
15540 ;; FIXME: positions wrong.
15541 (push (list :latex-fragment (point) (point)) clist)))
15543 (setq clist (nreverse (delq nil clist)))
15544 clist))
15546 ;; FIXME: Compare with at-regexp-p Do we need both?
15547 (defun org-in-regexp (re &optional nlines visually)
15548 "Check if point is inside a match of regexp.
15549 Normally only the current line is checked, but you can include NLINES extra
15550 lines both before and after point into the search.
15551 If VISUALLY is set, require that the cursor is not after the match but
15552 really on, so that the block visually is on the match."
15553 (catch 'exit
15554 (let ((pos (point))
15555 (eol (point-at-eol (+ 1 (or nlines 0))))
15556 (inc (if visually 1 0)))
15557 (save-excursion
15558 (beginning-of-line (- 1 (or nlines 0)))
15559 (while (re-search-forward re eol t)
15560 (if (and (<= (match-beginning 0) pos)
15561 (>= (+ inc (match-end 0)) pos))
15562 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15564 (defun org-at-regexp-p (regexp)
15565 "Is point inside a match of REGEXP in the current line?"
15566 (catch 'exit
15567 (save-excursion
15568 (let ((pos (point)) (end (point-at-eol)))
15569 (beginning-of-line 1)
15570 (while (re-search-forward regexp end t)
15571 (if (and (<= (match-beginning 0) pos)
15572 (>= (match-end 0) pos))
15573 (throw 'exit t)))
15574 nil))))
15576 (defun org-occur-in-agenda-files (regexp &optional nlines)
15577 "Call `multi-occur' with buffers for all agenda files."
15578 (interactive "sOrg-files matching: \np")
15579 (let* ((files (org-agenda-files))
15580 (tnames (mapcar 'file-truename files))
15581 (extra org-agenda-text-search-extra-files)
15583 (when (eq (car extra) 'agenda-archives)
15584 (setq extra (cdr extra))
15585 (setq files (org-add-archive-files files)))
15586 (while (setq f (pop extra))
15587 (unless (member (file-truename f) tnames)
15588 (add-to-list 'files f 'append)
15589 (add-to-list 'tnames (file-truename f) 'append)))
15590 (multi-occur
15591 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15592 regexp)))
15594 (if (boundp 'occur-mode-find-occurrence-hook)
15595 ;; Emacs 23
15596 (add-hook 'occur-mode-find-occurrence-hook
15597 (lambda ()
15598 (when (org-mode-p)
15599 (org-reveal))))
15600 ;; Emacs 22
15601 (defadvice occur-mode-goto-occurrence
15602 (after org-occur-reveal activate)
15603 (and (org-mode-p) (org-reveal)))
15604 (defadvice occur-mode-goto-occurrence-other-window
15605 (after org-occur-reveal activate)
15606 (and (org-mode-p) (org-reveal)))
15607 (defadvice occur-mode-display-occurrence
15608 (after org-occur-reveal activate)
15609 (when (org-mode-p)
15610 (let ((pos (occur-mode-find-occurrence)))
15611 (with-current-buffer (marker-buffer pos)
15612 (save-excursion
15613 (goto-char pos)
15614 (org-reveal)))))))
15616 (defun org-uniquify (list)
15617 "Remove duplicate elements from LIST."
15618 (let (res)
15619 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15620 res))
15622 (defun org-delete-all (elts list)
15623 "Remove all elements in ELTS from LIST."
15624 (while elts
15625 (setq list (delete (pop elts) list)))
15626 list)
15628 (defun org-back-over-empty-lines ()
15629 "Move backwards over whitespace, to the beginning of the first empty line.
15630 Returns the number of empty lines passed."
15631 (let ((pos (point)))
15632 (skip-chars-backward " \t\n\r")
15633 (beginning-of-line 2)
15634 (goto-char (min (point) pos))
15635 (count-lines (point) pos)))
15637 (defun org-skip-whitespace ()
15638 (skip-chars-forward " \t\n\r"))
15640 (defun org-point-in-group (point group &optional context)
15641 "Check if POINT is in match-group GROUP.
15642 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15643 match. If the match group does ot exist or point is not inside it,
15644 return nil."
15645 (and (match-beginning group)
15646 (>= point (match-beginning group))
15647 (<= point (match-end group))
15648 (if context
15649 (list context (match-beginning group) (match-end group))
15650 t)))
15652 (defun org-switch-to-buffer-other-window (&rest args)
15653 "Switch to buffer in a second window on the current frame.
15654 In particular, do not allow pop-up frames."
15655 (let (pop-up-frames special-display-buffer-names special-display-regexps
15656 special-display-function)
15657 (apply 'switch-to-buffer-other-window args)))
15659 (defun org-combine-plists (&rest plists)
15660 "Create a single property list from all plists in PLISTS.
15661 The process starts by copying the first list, and then setting properties
15662 from the other lists. Settings in the last list are the most significant
15663 ones and overrule settings in the other lists."
15664 (let ((rtn (copy-sequence (pop plists)))
15665 p v ls)
15666 (while plists
15667 (setq ls (pop plists))
15668 (while ls
15669 (setq p (pop ls) v (pop ls))
15670 (setq rtn (plist-put rtn p v))))
15671 rtn))
15673 (defun org-move-line-down (arg)
15674 "Move the current line down. With prefix argument, move it past ARG lines."
15675 (interactive "p")
15676 (let ((col (current-column))
15677 beg end pos)
15678 (beginning-of-line 1) (setq beg (point))
15679 (beginning-of-line 2) (setq end (point))
15680 (beginning-of-line (+ 1 arg))
15681 (setq pos (move-marker (make-marker) (point)))
15682 (insert (delete-and-extract-region beg end))
15683 (goto-char pos)
15684 (org-move-to-column col)))
15686 (defun org-move-line-up (arg)
15687 "Move the current line up. With prefix argument, move it past ARG lines."
15688 (interactive "p")
15689 (let ((col (current-column))
15690 beg end pos)
15691 (beginning-of-line 1) (setq beg (point))
15692 (beginning-of-line 2) (setq end (point))
15693 (beginning-of-line (- arg))
15694 (setq pos (move-marker (make-marker) (point)))
15695 (insert (delete-and-extract-region beg end))
15696 (goto-char pos)
15697 (org-move-to-column col)))
15699 (defun org-replace-escapes (string table)
15700 "Replace %-escapes in STRING with values in TABLE.
15701 TABLE is an association list with keys like \"%a\" and string values.
15702 The sequences in STRING may contain normal field width and padding information,
15703 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15704 so values can contain further %-escapes if they are define later in TABLE."
15705 (let ((case-fold-search nil)
15706 e re rpl)
15707 (while (setq e (pop table))
15708 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15709 (while (string-match re string)
15710 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15711 (cdr e)))
15712 (setq string (replace-match rpl t t string))))
15713 string))
15716 (defun org-sublist (list start end)
15717 "Return a section of LIST, from START to END.
15718 Counting starts at 1."
15719 (let (rtn (c start))
15720 (setq list (nthcdr (1- start) list))
15721 (while (and list (<= c end))
15722 (push (pop list) rtn)
15723 (setq c (1+ c)))
15724 (nreverse rtn)))
15726 (defun org-find-base-buffer-visiting (file)
15727 "Like `find-buffer-visiting' but always return the base buffer and
15728 not an indirect buffer."
15729 (let ((buf (or (get-file-buffer file)
15730 (find-buffer-visiting file))))
15731 (if buf
15732 (or (buffer-base-buffer buf) buf)
15733 nil)))
15735 (defun org-image-file-name-regexp (&optional extensions)
15736 "Return regexp matching the file names of images.
15737 If EXTENSIONS is given, only match these."
15738 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15739 (image-file-name-regexp)
15740 (let ((image-file-name-extensions
15741 (or extensions
15742 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15743 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15744 (concat "\\."
15745 (regexp-opt (nconc (mapcar 'upcase
15746 image-file-name-extensions)
15747 image-file-name-extensions)
15749 "\\'"))))
15751 (defun org-file-image-p (file &optional extensions)
15752 "Return non-nil if FILE is an image."
15753 (save-match-data
15754 (string-match (org-image-file-name-regexp extensions) file)))
15756 (defun org-get-cursor-date ()
15757 "Return the date at cursor in as a time.
15758 This works in the calendar and in the agenda, anywhere else it just
15759 returns the current time."
15760 (let (date day defd)
15761 (cond
15762 ((eq major-mode 'calendar-mode)
15763 (setq date (calendar-cursor-to-date)
15764 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15765 ((eq major-mode 'org-agenda-mode)
15766 (setq day (get-text-property (point) 'day))
15767 (if day
15768 (setq date (calendar-gregorian-from-absolute day)
15769 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15770 (nth 2 date))))))
15771 (or defd (current-time))))
15773 (defvar org-agenda-action-marker (make-marker)
15774 "Marker pointing to the entry for the next agenda action.")
15776 (defun org-mark-entry-for-agenda-action ()
15777 "Mark the current entry as target of an agenda action.
15778 Agenda actions are actions executed from the agenda with the key `k',
15779 which make use of the date at the cursor."
15780 (interactive)
15781 (move-marker org-agenda-action-marker
15782 (save-excursion (org-back-to-heading t) (point))
15783 (current-buffer))
15784 (message
15785 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15787 ;;; Paragraph filling stuff.
15788 ;; We want this to be just right, so use the full arsenal.
15790 (defun org-indent-line-function ()
15791 "Indent line like previous, but further if previous was headline or item."
15792 (interactive)
15793 (let* ((pos (point))
15794 (itemp (org-at-item-p))
15795 (case-fold-search t)
15796 (org-drawer-regexp (or org-drawer-regexp "\000"))
15797 column bpos bcol tpos tcol bullet btype bullet-type)
15798 ;; Find the previous relevant line
15799 (beginning-of-line 1)
15800 (cond
15801 ((looking-at "#") (setq column 0))
15802 ((looking-at "\\*+ ") (setq column 0))
15803 ((and (looking-at "[ \t]*:END:")
15804 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15805 (save-excursion
15806 (goto-char (1- (match-beginning 1)))
15807 (setq column (current-column))))
15808 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
15809 (save-excursion
15810 (re-search-backward
15811 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
15812 (setq column (org-get-indentation (match-string 0))))
15814 (beginning-of-line 0)
15815 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15816 (not (looking-at "[ \t]*:END:"))
15817 (not (looking-at org-drawer-regexp)))
15818 (beginning-of-line 0))
15819 (cond
15820 ((looking-at "\\*+[ \t]+")
15821 (if (not org-adapt-indentation)
15822 (setq column 0)
15823 (goto-char (match-end 0))
15824 (setq column (current-column))))
15825 ((looking-at org-drawer-regexp)
15826 (goto-char (1- (match-beginning 1)))
15827 (setq column (current-column)))
15828 ((looking-at "\\([ \t]*\\):END:")
15829 (goto-char (match-end 1))
15830 (setq column (current-column)))
15831 ((org-in-item-p)
15832 (org-beginning-of-item)
15833 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15834 (setq bpos (match-beginning 1) tpos (match-end 0)
15835 bcol (progn (goto-char bpos) (current-column))
15836 tcol (progn (goto-char tpos) (current-column))
15837 bullet (match-string 1)
15838 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15839 (if (> tcol (+ bcol org-description-max-indent))
15840 (setq tcol (+ bcol 5)))
15841 (if (not itemp)
15842 (setq column tcol)
15843 (goto-char pos)
15844 (beginning-of-line 1)
15845 (if (looking-at "\\S-")
15846 (progn
15847 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15848 (setq bullet (match-string 1)
15849 btype (if (string-match "[0-9]" bullet) "n" bullet))
15850 (setq column (if (equal btype bullet-type) bcol tcol)))
15851 (setq column (org-get-indentation)))))
15852 (t (setq column (org-get-indentation))))))
15853 (goto-char pos)
15854 (if (<= (current-column) (current-indentation))
15855 (org-indent-line-to column)
15856 (save-excursion (org-indent-line-to column)))
15857 (setq column (current-column))
15858 (beginning-of-line 1)
15859 (if (looking-at
15860 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15861 (replace-match (concat "\\1" (format org-property-format
15862 (match-string 2) (match-string 3)))
15863 t nil))
15864 (org-move-to-column column)))
15866 (defun org-set-autofill-regexps ()
15867 (interactive)
15868 ;; In the paragraph separator we include headlines, because filling
15869 ;; text in a line directly attached to a headline would otherwise
15870 ;; fill the headline as well.
15871 (org-set-local 'comment-start-skip "^#+[ \t]*")
15872 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15873 ;; The paragraph starter includes hand-formatted lists.
15874 (org-set-local
15875 'paragraph-start
15876 (concat
15877 "\f" "\\|"
15878 "[ ]*$" "\\|"
15879 "\\*+ " "\\|"
15880 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
15881 "[ \t]*[:|]" "\\|"
15882 "\\$\\$" "\\|"
15883 "\\\\\\(begin\\|end\\|[][]\\)"))
15884 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15885 ;; But only if the user has not turned off tables or fixed-width regions
15886 (org-set-local
15887 'auto-fill-inhibit-regexp
15888 (concat "\\*+ \\|#\\+"
15889 "\\|[ \t]*" org-keyword-time-regexp
15890 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15891 (concat
15892 "\\|[ \t]*["
15893 (if org-enable-table-editor "|" "")
15894 (if org-enable-fixed-width-editor ":" "")
15895 "]"))))
15896 ;; We use our own fill-paragraph function, to make sure that tables
15897 ;; and fixed-width regions are not wrapped. That function will pass
15898 ;; through to `fill-paragraph' when appropriate.
15899 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15900 ; Adaptive filling: To get full control, first make sure that
15901 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15902 (org-set-local 'adaptive-fill-regexp "\000")
15903 (org-set-local 'adaptive-fill-function
15904 'org-adaptive-fill-function)
15905 (org-set-local
15906 'align-mode-rules-list
15907 '((org-in-buffer-settings
15908 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15909 (modes . '(org-mode))))))
15911 (defun org-fill-paragraph (&optional justify)
15912 "Re-align a table, pass through to fill-paragraph if no table."
15913 (let ((table-p (org-at-table-p))
15914 (table.el-p (org-at-table.el-p)))
15915 (cond ((and (equal (char-after (point-at-bol)) ?*)
15916 (save-excursion (goto-char (point-at-bol))
15917 (looking-at outline-regexp)))
15918 t) ; skip headlines
15919 (table.el-p t) ; skip table.el tables
15920 (table-p (org-table-align) t) ; align org-mode tables
15921 (t nil)))) ; call paragraph-fill
15923 ;; For reference, this is the default value of adaptive-fill-regexp
15924 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15926 (defun org-adaptive-fill-function ()
15927 "Return a fill prefix for org-mode files.
15928 In particular, this makes sure hanging paragraphs for hand-formatted lists
15929 work correctly."
15930 (cond ((looking-at "#[ \t]+")
15931 (match-string 0))
15932 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15933 (save-excursion
15934 (if (> (match-end 1) (+ (match-beginning 1)
15935 org-description-max-indent))
15936 (goto-char (+ (match-beginning 1) 5))
15937 (goto-char (match-end 0)))
15938 (make-string (current-column) ?\ )))
15939 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15940 (save-excursion
15941 (goto-char (match-end 0))
15942 (make-string (current-column) ?\ )))
15943 (t nil)))
15945 ;;; Other stuff.
15947 (defun org-toggle-fixed-width-section (arg)
15948 "Toggle the fixed-width export.
15949 If there is no active region, the QUOTE keyword at the current headline is
15950 inserted or removed. When present, it causes the text between this headline
15951 and the next to be exported as fixed-width text, and unmodified.
15952 If there is an active region, this command adds or removes a colon as the
15953 first character of this line. If the first character of a line is a colon,
15954 this line is also exported in fixed-width font."
15955 (interactive "P")
15956 (let* ((cc 0)
15957 (regionp (org-region-active-p))
15958 (beg (if regionp (region-beginning) (point)))
15959 (end (if regionp (region-end)))
15960 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15961 (case-fold-search nil)
15962 (re "[ \t]*\\(: \\)")
15963 off)
15964 (if regionp
15965 (save-excursion
15966 (goto-char beg)
15967 (setq cc (current-column))
15968 (beginning-of-line 1)
15969 (setq off (looking-at re))
15970 (while (> nlines 0)
15971 (setq nlines (1- nlines))
15972 (beginning-of-line 1)
15973 (cond
15974 (arg
15975 (org-move-to-column cc t)
15976 (insert ": \n")
15977 (forward-line -1))
15978 ((and off (looking-at re))
15979 (replace-match "" t t nil 1))
15980 ((not off) (org-move-to-column cc t) (insert ": ")))
15981 (forward-line 1)))
15982 (save-excursion
15983 (org-back-to-heading)
15984 (if (looking-at (concat outline-regexp
15985 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15986 (replace-match "" t t nil 1)
15987 (if (looking-at outline-regexp)
15988 (progn
15989 (goto-char (match-end 0))
15990 (insert org-quote-string " "))))))))
15992 (defun org-reftex-citation ()
15993 "Use reftex-citation to insert a citation into the buffer.
15994 This looks for a line like
15996 #+BIBLIOGRAPHY: foo plain option:-d
15998 and derives from it that foo.bib is the bbliography file relevant
15999 for this document. It then installs the necessary environment for RefTeX
16000 to work in this buffer and calls `reftex-citation' to insert a citation
16001 into the buffer.
16003 Export of such citations to both LaTeX and HTML is handled by the contributed
16004 package org-exp-bibtex by Taru Karttunen."
16005 (interactive)
16006 (let ((reftex-docstruct-symbol 'rds)
16007 (reftex-cite-format "\\cite{%l}")
16008 rds bib)
16009 (save-excursion
16010 (save-restriction
16011 (widen)
16012 (let ((case-fold-search t)
16013 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16014 (if (not (save-excursion
16015 (or (re-search-forward re nil t)
16016 (re-search-backward re nil t))))
16017 (error "No bibliography defined in file")
16018 (setq bib (concat (match-string 1) ".bib")
16019 rds (list (list 'bib bib)))))))
16020 (call-interactively 'reftex-citation)))
16022 ;;;; Functions extending outline functionality
16024 (defun org-beginning-of-line (&optional arg)
16025 "Go to the beginning of the current line. If that is invisible, continue
16026 to a visible line beginning. This makes the function of C-a more intuitive.
16027 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16028 first attempt, and only move to after the tags when the cursor is already
16029 beyond the end of the headline."
16030 (interactive "P")
16031 (let ((pos (point))
16032 (special (if (consp org-special-ctrl-a/e)
16033 (car org-special-ctrl-a/e)
16034 org-special-ctrl-a/e))
16035 refpos)
16036 (if (org-bound-and-true-p line-move-visual)
16037 (beginning-of-visual-line 1)
16038 (beginning-of-line 1))
16039 (if (and arg (fboundp 'move-beginning-of-line))
16040 (call-interactively 'move-beginning-of-line)
16041 (if (bobp)
16043 (backward-char 1)
16044 (if (org-invisible-p)
16045 (while (and (not (bobp)) (org-invisible-p))
16046 (backward-char 1)
16047 (beginning-of-line 1))
16048 (forward-char 1))))
16049 (when special
16050 (cond
16051 ((and (looking-at org-complex-heading-regexp)
16052 (= (char-after (match-end 1)) ?\ ))
16053 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16054 (point-at-eol)))
16055 (goto-char
16056 (if (eq special t)
16057 (cond ((> pos refpos) refpos)
16058 ((= pos (point)) refpos)
16059 (t (point)))
16060 (cond ((> pos (point)) (point))
16061 ((not (eq last-command this-command)) (point))
16062 (t refpos)))))
16063 ((org-at-item-p)
16064 (goto-char
16065 (if (eq special t)
16066 (cond ((> pos (match-end 4)) (match-end 4))
16067 ((= pos (point)) (match-end 4))
16068 (t (point)))
16069 (cond ((> pos (point)) (point))
16070 ((not (eq last-command this-command)) (point))
16071 (t (match-end 4))))))))
16072 (org-no-warnings
16073 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16075 (defun org-end-of-line (&optional arg)
16076 "Go to the end of the line.
16077 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16078 first attempt, and only move to after the tags when the cursor is already
16079 beyond the end of the headline."
16080 (interactive "P")
16081 (let ((special (if (consp org-special-ctrl-a/e)
16082 (cdr org-special-ctrl-a/e)
16083 org-special-ctrl-a/e)))
16084 (if (or (not special)
16085 (not (org-on-heading-p))
16086 arg)
16087 (call-interactively
16088 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
16089 ((fboundp 'move-end-of-line) 'move-end-of-line)
16090 (t 'end-of-line)))
16091 (let ((pos (point)))
16092 (beginning-of-line 1)
16093 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16094 (if (eq special t)
16095 (if (or (< pos (match-beginning 1))
16096 (= pos (match-end 0)))
16097 (goto-char (match-beginning 1))
16098 (goto-char (match-end 0)))
16099 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16100 (goto-char (match-end 0))
16101 (goto-char (match-beginning 1))))
16102 (call-interactively (if (fboundp 'move-end-of-line)
16103 'move-end-of-line
16104 'end-of-line)))))
16105 (org-no-warnings
16106 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16108 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16109 (define-key org-mode-map "\C-e" 'org-end-of-line)
16111 (defun org-backward-sentence (&optional arg)
16112 "Go to beginning of sentence, or beginning of table field.
16113 This will call `backward-sentence' or `org-table-beginning-of-field',
16114 depending on context."
16115 (interactive "P")
16116 (cond
16117 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16118 (t (call-interactively 'backward-sentence))))
16120 (defun org-forward-sentence (&optional arg)
16121 "Go to end of sentence, or end of table field.
16122 This will call `forward-sentence' or `org-table-end-of-field',
16123 depending on context."
16124 (interactive "P")
16125 (cond
16126 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16127 (t (call-interactively 'forward-sentence))))
16129 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16130 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16132 (defun org-kill-line (&optional arg)
16133 "Kill line, to tags or end of line."
16134 (interactive "P")
16135 (cond
16136 ((or (not org-special-ctrl-k)
16137 (bolp)
16138 (not (org-on-heading-p)))
16139 (call-interactively 'kill-line))
16140 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16141 (kill-region (point) (match-beginning 1))
16142 (org-set-tags nil t))
16143 (t (kill-region (point) (point-at-eol)))))
16145 (define-key org-mode-map "\C-k" 'org-kill-line)
16147 (defun org-yank (&optional arg)
16148 "Yank. If the kill is a subtree, treat it specially.
16149 This command will look at the current kill and check if is a single
16150 subtree, or a series of subtrees[1]. If it passes the test, and if the
16151 cursor is at the beginning of a line or after the stars of a currently
16152 empty headline, then the yank is handled specially. How exactly depends
16153 on the value of the following variables, both set by default.
16155 org-yank-folded-subtrees
16156 When set, the subtree(s) will be folded after insertion, but only
16157 if doing so would now swallow text after the yanked text.
16159 org-yank-adjusted-subtrees
16160 When set, the subtree will be promoted or demoted in order to
16161 fit into the local outline tree structure, which means that the level
16162 will be adjusted so that it becomes the smaller one of the two
16163 *visible* surrounding headings.
16165 Any prefix to this command will cause `yank' to be called directly with
16166 no special treatment. In particular, a simple `C-u' prefix will just
16167 plainly yank the text as it is.
16169 \[1] The test checks if the first non-white line is a heading
16170 and if there are no other headings with fewer stars."
16171 (interactive "P")
16172 (org-yank-generic 'yank arg))
16174 (defun org-yank-generic (command arg)
16175 "Perform some yank-like command.
16177 This function implements the behavior described in the `org-yank'
16178 documentation. However, it has been generalized to work for any
16179 interactive command with similar behavior."
16181 ;; pretend to be command COMMAND
16182 (setq this-command command)
16184 (if arg
16185 (call-interactively command)
16187 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16188 (and (org-kill-is-subtree-p)
16189 (or (bolp)
16190 (and (looking-at "[ \t]*$")
16191 (string-match
16192 "\\`\\*+\\'"
16193 (buffer-substring (point-at-bol) (point)))))))
16194 swallowp)
16195 (cond
16196 ((and subtreep org-yank-folded-subtrees)
16197 (let ((beg (point))
16198 end)
16199 (if (and subtreep org-yank-adjusted-subtrees)
16200 (org-paste-subtree nil nil 'for-yank)
16201 (call-interactively command))
16203 (setq end (point))
16204 (goto-char beg)
16205 (when (and (bolp) subtreep
16206 (not (setq swallowp
16207 (org-yank-folding-would-swallow-text beg end))))
16208 (or (looking-at outline-regexp)
16209 (re-search-forward (concat "^" outline-regexp) end t))
16210 (while (and (< (point) end) (looking-at outline-regexp))
16211 (hide-subtree)
16212 (org-cycle-show-empty-lines 'folded)
16213 (condition-case nil
16214 (outline-forward-same-level 1)
16215 (error (goto-char end)))))
16216 (when swallowp
16217 (message
16218 "Inserted text not folded because that would swallow text"))
16220 (goto-char end)
16221 (skip-chars-forward " \t\n\r")
16222 (beginning-of-line 1)
16223 (push-mark beg 'nomsg)))
16224 ((and subtreep org-yank-adjusted-subtrees)
16225 (let ((beg (point-at-bol)))
16226 (org-paste-subtree nil nil 'for-yank)
16227 (push-mark beg 'nomsg)))
16229 (call-interactively command))))))
16231 (defun org-yank-folding-would-swallow-text (beg end)
16232 "Would hide-subtree at BEG swallow any text after END?"
16233 (let (level)
16234 (save-excursion
16235 (goto-char beg)
16236 (when (or (looking-at outline-regexp)
16237 (re-search-forward (concat "^" outline-regexp) end t))
16238 (setq level (org-outline-level)))
16239 (goto-char end)
16240 (skip-chars-forward " \t\r\n\v\f")
16241 (if (or (eobp)
16242 (and (bolp) (looking-at org-outline-regexp)
16243 (<= (org-outline-level) level)))
16244 nil ; Nothing would be swallowed
16245 t)))) ; something would swallow
16247 (define-key org-mode-map "\C-y" 'org-yank)
16249 (defun org-invisible-p ()
16250 "Check if point is at a character currently not visible."
16251 ;; Early versions of noutline don't have `outline-invisible-p'.
16252 (if (fboundp 'outline-invisible-p)
16253 (outline-invisible-p)
16254 (get-char-property (point) 'invisible)))
16256 (defun org-invisible-p2 ()
16257 "Check if point is at a character currently not visible."
16258 (save-excursion
16259 (if (and (eolp) (not (bobp))) (backward-char 1))
16260 ;; Early versions of noutline don't have `outline-invisible-p'.
16261 (if (fboundp 'outline-invisible-p)
16262 (outline-invisible-p)
16263 (get-char-property (point) 'invisible))))
16265 (defun org-back-to-heading (&optional invisible-ok)
16266 "Call `outline-back-to-heading', but provide a better error message."
16267 (condition-case nil
16268 (outline-back-to-heading invisible-ok)
16269 (error (error "Before first headline at position %d in buffer %s"
16270 (point) (current-buffer)))))
16272 (defun org-before-first-heading-p ()
16273 "Before first heading?"
16274 (save-excursion
16275 (null (re-search-backward "^\\*+ " nil t))))
16277 (defalias 'org-on-heading-p 'outline-on-heading-p)
16278 (defalias 'org-at-heading-p 'outline-on-heading-p)
16279 (defun org-at-heading-or-item-p ()
16280 (or (org-on-heading-p) (org-at-item-p)))
16282 (defun org-on-target-p ()
16283 (or (org-in-regexp org-radio-target-regexp)
16284 (org-in-regexp org-target-regexp)))
16286 (defun org-up-heading-all (arg)
16287 "Move to the heading line of which the present line is a subheading.
16288 This function considers both visible and invisible heading lines.
16289 With argument, move up ARG levels."
16290 (if (fboundp 'outline-up-heading-all)
16291 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16292 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16294 (defun org-up-heading-safe ()
16295 "Move to the heading line of which the present line is a subheading.
16296 This version will not throw an error. It will return the level of the
16297 headline found, or nil if no higher level is found.
16299 Also, this function will be a lot faster than `outline-up-heading',
16300 because it relies on stars being the outline starters. This can really
16301 make a significant difference in outlines with very many siblings."
16302 (let (start-level re)
16303 (org-back-to-heading t)
16304 (setq start-level (funcall outline-level))
16305 (if (equal start-level 1)
16307 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16308 (if (re-search-backward re nil t)
16309 (funcall outline-level)))))
16311 (defun org-first-sibling-p ()
16312 "Is this heading the first child of its parents?"
16313 (interactive)
16314 (let ((re (concat "^" outline-regexp))
16315 level l)
16316 (unless (org-at-heading-p t)
16317 (error "Not at a heading"))
16318 (setq level (funcall outline-level))
16319 (save-excursion
16320 (if (not (re-search-backward re nil t))
16322 (setq l (funcall outline-level))
16323 (< l level)))))
16325 (defun org-goto-sibling (&optional previous)
16326 "Goto the next sibling, even if it is invisible.
16327 When PREVIOUS is set, go to the previous sibling instead. Returns t
16328 when a sibling was found. When none is found, return nil and don't
16329 move point."
16330 (let ((fun (if previous 're-search-backward 're-search-forward))
16331 (pos (point))
16332 (re (concat "^" outline-regexp))
16333 level l)
16334 (when (condition-case nil (org-back-to-heading t) (error nil))
16335 (setq level (funcall outline-level))
16336 (catch 'exit
16337 (or previous (forward-char 1))
16338 (while (funcall fun re nil t)
16339 (setq l (funcall outline-level))
16340 (when (< l level) (goto-char pos) (throw 'exit nil))
16341 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16342 (goto-char pos)
16343 nil))))
16345 (defun org-show-siblings ()
16346 "Show all siblings of the current headline."
16347 (save-excursion
16348 (while (org-goto-sibling) (org-flag-heading nil)))
16349 (save-excursion
16350 (while (org-goto-sibling 'previous)
16351 (org-flag-heading nil))))
16353 (defun org-show-hidden-entry ()
16354 "Show an entry where even the heading is hidden."
16355 (save-excursion
16356 (org-show-entry)))
16358 (defun org-flag-heading (flag &optional entry)
16359 "Flag the current heading. FLAG non-nil means make invisible.
16360 When ENTRY is non-nil, show the entire entry."
16361 (save-excursion
16362 (org-back-to-heading t)
16363 ;; Check if we should show the entire entry
16364 (if entry
16365 (progn
16366 (org-show-entry)
16367 (save-excursion
16368 (and (outline-next-heading)
16369 (org-flag-heading nil))))
16370 (outline-flag-region (max (point-min) (1- (point)))
16371 (save-excursion (outline-end-of-heading) (point))
16372 flag))))
16374 (defun org-forward-same-level (arg)
16375 "Move forward to the ARG'th subheading at same level as this one.
16376 Stop at the first and last subheadings of a superior heading.
16377 This is like outline-forward-same-level, but invisible headings are ok."
16378 (interactive "p")
16379 (org-back-to-heading t)
16380 (while (> arg 0)
16381 (let ((point-to-move-to (save-excursion
16382 (org-get-next-sibling))))
16383 (if point-to-move-to
16384 (progn
16385 (goto-char point-to-move-to)
16386 (setq arg (1- arg)))
16387 (progn
16388 (setq arg 0)
16389 (error "No following same-level heading"))))))
16391 (defun org-get-next-sibling ()
16392 "Move to next heading of the same level, and return point.
16393 If there is no such heading, return nil.
16394 This is like outline-next-sibling, but invisible headings are ok."
16395 (let ((level (funcall outline-level)))
16396 (outline-next-heading)
16397 (while (and (not (eobp)) (> (funcall outline-level) level))
16398 (outline-next-heading))
16399 (if (or (eobp) (< (funcall outline-level) level))
16401 (point))))
16403 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16404 ;; This contains an exact copy of the original function, but it uses
16405 ;; `org-back-to-heading', to make it work also in invisible
16406 ;; trees. And is uses an invisible-OK argument.
16407 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16408 ;; Furthermore, when used inside Org, finding the end of a large subtree
16409 ;; with many children and grandchildren etc, this can be much faster
16410 ;; than the outline version.
16411 (org-back-to-heading invisible-OK)
16412 (let ((first t)
16413 (level (funcall outline-level)))
16414 (if (and (org-mode-p) (< level 1000))
16415 ;; A true heading (not a plain list item), in Org-mode
16416 ;; This means we can easily find the end by looking
16417 ;; only for the right number of stars. Using a regexp to do
16418 ;; this is so much faster than using a Lisp loop.
16419 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16420 (forward-char 1)
16421 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16422 ;; something else, do it the slow way
16423 (while (and (not (eobp))
16424 (or first (> (funcall outline-level) level)))
16425 (setq first nil)
16426 (outline-next-heading)))
16427 (unless to-heading
16428 (if (memq (preceding-char) '(?\n ?\^M))
16429 (progn
16430 ;; Go to end of line before heading
16431 (forward-char -1)
16432 (if (memq (preceding-char) '(?\n ?\^M))
16433 ;; leave blank line before heading
16434 (forward-char -1))))))
16435 (point))
16437 (defun org-show-subtree ()
16438 "Show everything after this heading at deeper levels."
16439 (outline-flag-region
16440 (point)
16441 (save-excursion
16442 (outline-end-of-subtree) (outline-next-heading) (point))
16443 nil))
16445 (defun org-show-entry ()
16446 "Show the body directly following this heading.
16447 Show the heading too, if it is currently invisible."
16448 (interactive)
16449 (save-excursion
16450 (condition-case nil
16451 (progn
16452 (org-back-to-heading t)
16453 (outline-flag-region
16454 (max (point-min) (1- (point)))
16455 (save-excursion
16456 (if (re-search-forward
16457 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16458 (match-beginning 1)
16459 (point-max)))
16460 nil)
16461 (org-cycle-hide-drawers 'children))
16462 (error nil))))
16464 (defun org-make-options-regexp (kwds &optional extra)
16465 "Make a regular expression for keyword lines."
16466 (concat
16468 "#?[ \t]*\\+\\("
16469 (mapconcat 'regexp-quote kwds "\\|")
16470 (if extra (concat "\\|" extra))
16471 "\\):[ \t]*"
16472 "\\(.+\\)"))
16474 ;; Make isearch reveal the necessary context
16475 (defun org-isearch-end ()
16476 "Reveal context after isearch exits."
16477 (when isearch-success ; only if search was successful
16478 (if (featurep 'xemacs)
16479 ;; Under XEmacs, the hook is run in the correct place,
16480 ;; we directly show the context.
16481 (org-show-context 'isearch)
16482 ;; In Emacs the hook runs *before* restoring the overlays.
16483 ;; So we have to use a one-time post-command-hook to do this.
16484 ;; (Emacs 22 has a special variable, see function `org-mode')
16485 (unless (and (boundp 'isearch-mode-end-hook-quit)
16486 isearch-mode-end-hook-quit)
16487 ;; Only when the isearch was not quitted.
16488 (org-add-hook 'post-command-hook 'org-isearch-post-command
16489 'append 'local)))))
16491 (defun org-isearch-post-command ()
16492 "Remove self from hook, and show context."
16493 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16494 (org-show-context 'isearch))
16497 ;;;; Integration with and fixes for other packages
16499 ;;; Imenu support
16501 (defvar org-imenu-markers nil
16502 "All markers currently used by Imenu.")
16503 (make-variable-buffer-local 'org-imenu-markers)
16505 (defun org-imenu-new-marker (&optional pos)
16506 "Return a new marker for use by Imenu, and remember the marker."
16507 (let ((m (make-marker)))
16508 (move-marker m (or pos (point)))
16509 (push m org-imenu-markers)
16512 (defun org-imenu-get-tree ()
16513 "Produce the index for Imenu."
16514 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16515 (setq org-imenu-markers nil)
16516 (let* ((n org-imenu-depth)
16517 (re (concat "^" outline-regexp))
16518 (subs (make-vector (1+ n) nil))
16519 (last-level 0)
16520 m level head)
16521 (save-excursion
16522 (save-restriction
16523 (widen)
16524 (goto-char (point-max))
16525 (while (re-search-backward re nil t)
16526 (setq level (org-reduced-level (funcall outline-level)))
16527 (when (<= level n)
16528 (looking-at org-complex-heading-regexp)
16529 (setq head (org-link-display-format
16530 (org-match-string-no-properties 4))
16531 m (org-imenu-new-marker))
16532 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16533 (if (>= level last-level)
16534 (push (cons head m) (aref subs level))
16535 (push (cons head (aref subs (1+ level))) (aref subs level))
16536 (loop for i from (1+ level) to n do (aset subs i nil)))
16537 (setq last-level level)))))
16538 (aref subs 1)))
16540 (eval-after-load "imenu"
16541 '(progn
16542 (add-hook 'imenu-after-jump-hook
16543 (lambda ()
16544 (if (eq major-mode 'org-mode)
16545 (org-show-context 'org-goto))))))
16547 (defun org-link-display-format (link)
16548 "Replace a link with either the description, or the link target
16549 if no description is present"
16550 (save-match-data
16551 (if (string-match org-bracket-link-analytic-regexp link)
16552 (replace-match (or (match-string 5 link)
16553 (concat (match-string 1 link)
16554 (match-string 3 link)))
16555 nil nil link)
16556 link)))
16558 ;; Speedbar support
16560 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16561 "Overlay marking the agenda restriction line in speedbar.")
16562 (org-overlay-put org-speedbar-restriction-lock-overlay
16563 'face 'org-agenda-restriction-lock)
16564 (org-overlay-put org-speedbar-restriction-lock-overlay
16565 'help-echo "Agendas are currently limited to this item.")
16566 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16568 (defun org-speedbar-set-agenda-restriction ()
16569 "Restrict future agenda commands to the location at point in speedbar.
16570 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16571 (interactive)
16572 (require 'org-agenda)
16573 (let (p m tp np dir txt)
16574 (cond
16575 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16576 'org-imenu t))
16577 (setq m (get-text-property p 'org-imenu-marker))
16578 (save-excursion
16579 (save-restriction
16580 (set-buffer (marker-buffer m))
16581 (goto-char m)
16582 (org-agenda-set-restriction-lock 'subtree))))
16583 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16584 'speedbar-function 'speedbar-find-file))
16585 (setq tp (previous-single-property-change
16586 (1+ p) 'speedbar-function)
16587 np (next-single-property-change
16588 tp 'speedbar-function)
16589 dir (speedbar-line-directory)
16590 txt (buffer-substring-no-properties (or tp (point-min))
16591 (or np (point-max))))
16592 (save-excursion
16593 (save-restriction
16594 (set-buffer (find-file-noselect
16595 (let ((default-directory dir))
16596 (expand-file-name txt))))
16597 (unless (org-mode-p)
16598 (error "Cannot restrict to non-Org-mode file"))
16599 (org-agenda-set-restriction-lock 'file))))
16600 (t (error "Don't know how to restrict Org-mode's agenda")))
16601 (org-move-overlay org-speedbar-restriction-lock-overlay
16602 (point-at-bol) (point-at-eol))
16603 (setq current-prefix-arg nil)
16604 (org-agenda-maybe-redo)))
16606 (eval-after-load "speedbar"
16607 '(progn
16608 (speedbar-add-supported-extension ".org")
16609 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16610 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16611 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16612 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16613 (add-hook 'speedbar-visiting-tag-hook
16614 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16617 ;;; Fixes and Hacks for problems with other packages
16619 ;; Make flyspell not check words in links, to not mess up our keymap
16620 (defun org-mode-flyspell-verify ()
16621 "Don't let flyspell put overlays at active buttons."
16622 (and (not (get-text-property (point) 'keymap))
16623 (not (get-text-property (point) 'org-no-flyspell))))
16625 (defun org-remove-flyspell-overlays-in (beg end)
16626 "Remove flyspell overlays in region."
16627 (and (org-bound-and-true-p flyspell-mode)
16628 (fboundp 'flyspell-delete-region-overlays)
16629 (flyspell-delete-region-overlays beg end))
16630 (add-text-properties beg end '(org-no-flyspell t)))
16632 ;; Make `bookmark-jump' show the jump location if it was hidden.
16633 (eval-after-load "bookmark"
16634 '(if (boundp 'bookmark-after-jump-hook)
16635 ;; We can use the hook
16636 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16637 ;; Hook not available, use advice
16638 (defadvice bookmark-jump (after org-make-visible activate)
16639 "Make the position visible."
16640 (org-bookmark-jump-unhide))))
16642 ;; Make sure saveplace show the location if it was hidden
16643 (eval-after-load "saveplace"
16644 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16645 "Make the position visible."
16646 (org-bookmark-jump-unhide)))
16648 (defun org-bookmark-jump-unhide ()
16649 "Unhide the current position, to show the bookmark location."
16650 (and (org-mode-p)
16651 (or (org-invisible-p)
16652 (save-excursion (goto-char (max (point-min) (1- (point))))
16653 (org-invisible-p)))
16654 (org-show-context 'bookmark-jump)))
16656 ;; Make session.el ignore our circular variable
16657 (eval-after-load "session"
16658 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16660 ;;;; Experimental code
16662 (defun org-closed-in-range ()
16663 "Sparse tree of items closed in a certain time range.
16664 Still experimental, may disappear in the future."
16665 (interactive)
16666 ;; Get the time interval from the user.
16667 (let* ((time1 (time-to-seconds
16668 (org-read-date nil 'to-time nil "Starting date: ")))
16669 (time2 (time-to-seconds
16670 (org-read-date nil 'to-time nil "End date:")))
16671 ;; callback function
16672 (callback (lambda ()
16673 (let ((time
16674 (time-to-seconds
16675 (apply 'encode-time
16676 (org-parse-time-string
16677 (match-string 1))))))
16678 ;; check if time in interval
16679 (and (>= time time1) (<= time time2))))))
16680 ;; make tree, check each match with the callback
16681 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16683 ;;;; Finish up
16685 (provide 'org)
16687 (run-hooks 'org-load-hook)
16689 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16691 ;;; org.el ends here