Speed-up cycling in buffers with *many* siblings, and *many* drawers
[org-mode.git] / lisp / org.el
blobb20431149ec719e3b61dcddf8a5a25c11b1cd808
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 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
4881 ; XEmacs does not have `next-single-char-property-change'
4882 ; I'm not sure about Emacs 21.
4883 (while (and (not (eobp)) ;; this is like `next-line'
4884 (get-char-property (1- (point)) 'invisible))
4885 (beginning-of-line 2))
4886 (while (and (not (eobp)) ;; this is like `next-line'
4887 (get-char-property (1- (point)) 'invisible))
4888 (goto-char (next-single-char-property-change (point) 'invisible))
4889 (or (bolp) (beginning-of-line 2))))
4890 (setq eol (point)))
4891 (outline-end-of-heading) (setq eoh (point))
4892 (org-end-of-subtree t)
4893 (unless (eobp)
4894 (skip-chars-forward " \t\n")
4895 (beginning-of-line 1) ; in case this is an item
4897 (setq eos (1- (point))))
4898 ;; Find out what to do next and set `this-command'
4899 (cond
4900 ((= eos eoh)
4901 ;; Nothing is hidden behind this heading
4902 (run-hook-with-args 'org-pre-cycle-hook 'empty)
4903 (message "EMPTY ENTRY")
4904 (setq org-cycle-subtree-status nil)
4905 (save-excursion
4906 (goto-char eos)
4907 (outline-next-heading)
4908 (if (org-invisible-p) (org-flag-heading nil))))
4909 ((or (>= eol eos)
4910 (not (string-match "\\S-" (buffer-substring eol eos))))
4911 ;; Entire subtree is hidden in one line: open it
4912 (run-hook-with-args 'org-pre-cycle-hook 'children)
4913 (org-show-entry)
4914 (show-children)
4915 (message "CHILDREN")
4916 (save-excursion
4917 (goto-char eos)
4918 (outline-next-heading)
4919 (if (org-invisible-p) (org-flag-heading nil)))
4920 (setq org-cycle-subtree-status 'children)
4921 (run-hook-with-args 'org-cycle-hook 'children))
4922 ((and (eq last-command this-command)
4923 (eq org-cycle-subtree-status 'children))
4924 ;; We just showed the children, now show everything.
4925 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
4926 (org-show-subtree)
4927 (message "SUBTREE")
4928 (setq org-cycle-subtree-status 'subtree)
4929 (run-hook-with-args 'org-cycle-hook 'subtree))
4931 ;; Default action: hide the subtree.
4932 (run-hook-with-args 'org-pre-cycle-hook 'folded)
4933 (hide-subtree)
4934 (message "FOLDED")
4935 (setq org-cycle-subtree-status 'folded)
4936 (run-hook-with-args 'org-cycle-hook 'folded)))))
4938 ;;;###autoload
4939 (defun org-global-cycle (&optional arg)
4940 "Cycle the global visibility. For details see `org-cycle'.
4941 With C-u prefix arg, switch to startup visibility.
4942 With a numeric prefix, show all headlines up to that level."
4943 (interactive "P")
4944 (let ((org-cycle-include-plain-lists
4945 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4946 (cond
4947 ((integerp arg)
4948 (show-all)
4949 (hide-sublevels arg)
4950 (setq org-cycle-global-status 'contents))
4951 ((equal arg '(4))
4952 (org-set-startup-visibility)
4953 (message "Startup visibility, plus VISIBILITY properties."))
4955 (org-cycle '(4))))))
4957 (defun org-set-startup-visibility ()
4958 "Set the visibility required by startup options and properties."
4959 (cond
4960 ((eq org-startup-folded t)
4961 (org-cycle '(4)))
4962 ((eq org-startup-folded 'content)
4963 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4964 (org-cycle '(4)) (org-cycle '(4)))))
4965 (if org-hide-block-startup (org-hide-block-all))
4966 (org-set-visibility-according-to-property 'no-cleanup)
4967 (org-cycle-hide-archived-subtrees 'all)
4968 (org-cycle-hide-drawers 'all)
4969 (org-cycle-show-empty-lines 'all))
4971 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4972 "Switch subtree visibilities according to :VISIBILITY: property."
4973 (interactive)
4974 (let (org-show-entry-below state)
4975 (save-excursion
4976 (goto-char (point-min))
4977 (while (re-search-forward
4978 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4979 nil t)
4980 (setq state (match-string 1))
4981 (save-excursion
4982 (org-back-to-heading t)
4983 (hide-subtree)
4984 (org-reveal)
4985 (cond
4986 ((equal state '("fold" "folded"))
4987 (hide-subtree))
4988 ((equal state "children")
4989 (org-show-hidden-entry)
4990 (show-children))
4991 ((equal state "content")
4992 (save-excursion
4993 (save-restriction
4994 (org-narrow-to-subtree)
4995 (org-content))))
4996 ((member state '("all" "showall"))
4997 (show-subtree)))))
4998 (unless no-cleanup
4999 (org-cycle-hide-archived-subtrees 'all)
5000 (org-cycle-hide-drawers 'all)
5001 (org-cycle-show-empty-lines 'all)))))
5003 (defun org-overview ()
5004 "Switch to overview mode, showing only top-level headlines.
5005 Really, this shows all headlines with level equal or greater than the level
5006 of the first headline in the buffer. This is important, because if the
5007 first headline is not level one, then (hide-sublevels 1) gives confusing
5008 results."
5009 (interactive)
5010 (let ((level (save-excursion
5011 (goto-char (point-min))
5012 (if (re-search-forward (concat "^" outline-regexp) nil t)
5013 (progn
5014 (goto-char (match-beginning 0))
5015 (funcall outline-level))))))
5016 (and level (hide-sublevels level))))
5018 (defun org-content (&optional arg)
5019 "Show all headlines in the buffer, like a table of contents.
5020 With numerical argument N, show content up to level N."
5021 (interactive "P")
5022 (save-excursion
5023 ;; Visit all headings and show their offspring
5024 (and (integerp arg) (org-overview))
5025 (goto-char (point-max))
5026 (catch 'exit
5027 (while (and (progn (condition-case nil
5028 (outline-previous-visible-heading 1)
5029 (error (goto-char (point-min))))
5031 (looking-at outline-regexp))
5032 (if (integerp arg)
5033 (show-children (1- arg))
5034 (show-branches))
5035 (if (bobp) (throw 'exit nil))))))
5038 (defun org-optimize-window-after-visibility-change (state)
5039 "Adjust the window after a change in outline visibility.
5040 This function is the default value of the hook `org-cycle-hook'."
5041 (when (get-buffer-window (current-buffer))
5042 (cond
5043 ((eq state 'content) nil)
5044 ((eq state 'all) nil)
5045 ((eq state 'folded) nil)
5046 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5047 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5049 ;; FIXME: no longer in use
5050 (defun org-compact-display-after-subtree-move ()
5051 "Show a compacter version of the tree of the entry's parent."
5052 (save-excursion
5053 (if (org-up-heading-safe)
5054 (progn
5055 (hide-subtree)
5056 (show-entry)
5057 (show-children)
5058 (org-cycle-show-empty-lines 'children)
5059 (org-cycle-hide-drawers 'children))
5060 (org-overview))))
5062 (defun org-remove-empty-overlays-at (pos)
5063 "Remove outline overlays that do not contain non-white stuff."
5064 (mapc
5065 (lambda (o)
5066 (and (eq 'outline (org-overlay-get o 'invisible))
5067 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5068 (org-overlay-end o))))
5069 (org-delete-overlay o)))
5070 (org-overlays-at pos)))
5072 (defun org-clean-visibility-after-subtree-move ()
5073 "Fix visibility issues after moving a subtree."
5074 ;; First, find a reasonable region to look at:
5075 ;; Start two siblings above, end three below
5076 (let* ((beg (save-excursion
5077 (and (outline-get-last-sibling)
5078 (outline-get-last-sibling))
5079 (point)))
5080 (end (save-excursion
5081 (and (outline-get-next-sibling)
5082 (outline-get-next-sibling)
5083 (outline-get-next-sibling))
5084 (if (org-at-heading-p)
5085 (point-at-eol)
5086 (point))))
5087 (level (looking-at "\\*+"))
5088 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5089 (save-excursion
5090 (save-restriction
5091 (narrow-to-region beg end)
5092 (when re
5093 ;; Properly fold already folded siblings
5094 (goto-char (point-min))
5095 (while (re-search-forward re nil t)
5096 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5097 (hide-entry))))
5098 (org-cycle-show-empty-lines 'overview)
5099 (org-cycle-hide-drawers 'overview)))))
5101 (defun org-cycle-show-empty-lines (state)
5102 "Show empty lines above all visible headlines.
5103 The region to be covered depends on STATE when called through
5104 `org-cycle-hook'. Lisp program can use t for STATE to get the
5105 entire buffer covered. Note that an empty line is only shown if there
5106 are at least `org-cycle-separator-lines' empty lines before the headline."
5107 (when (> org-cycle-separator-lines 0)
5108 (save-excursion
5109 (let* ((n org-cycle-separator-lines)
5110 (re (cond
5111 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5112 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5113 (t (let ((ns (number-to-string (- n 2))))
5114 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5115 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5116 beg end)
5117 (cond
5118 ((memq state '(overview contents t))
5119 (setq beg (point-min) end (point-max)))
5120 ((memq state '(children folded))
5121 (setq beg (point) end (progn (org-end-of-subtree t t)
5122 (beginning-of-line 2)
5123 (point)))))
5124 (when beg
5125 (goto-char beg)
5126 (while (re-search-forward re end t)
5127 (if (not (get-char-property (match-end 1) 'invisible))
5128 (outline-flag-region
5129 (match-beginning 1) (match-end 1) nil)))))))
5130 ;; Never hide empty lines at the end of the file.
5131 (save-excursion
5132 (goto-char (point-max))
5133 (outline-previous-heading)
5134 (outline-end-of-heading)
5135 (if (and (looking-at "[ \t\n]+")
5136 (= (match-end 0) (point-max)))
5137 (outline-flag-region (point) (match-end 0) nil))))
5139 (defun org-show-empty-lines-in-parent ()
5140 "Move to the parent and re-show empty lines before visible headlines."
5141 (save-excursion
5142 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5143 (org-cycle-show-empty-lines context))))
5145 (defun org-cycle-hide-drawers (state)
5146 "Re-hide all drawers after a visibility state change."
5147 (when (and (org-mode-p)
5148 (not (memq state '(overview folded contents))))
5149 (save-excursion
5150 (let* ((globalp (memq state '(contents all)))
5151 (beg (if globalp (point-min) (point)))
5152 (end (if globalp (point-max)
5153 (if (eq state 'children)
5154 (save-excursion (outline-next-heading) (point))
5155 (org-end-of-subtree t)))))
5156 (goto-char beg)
5157 (while (re-search-forward org-drawer-regexp end t)
5158 (org-flag-drawer t))))))
5160 (defun org-flag-drawer (flag)
5161 (save-excursion
5162 (beginning-of-line 1)
5163 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5164 (let ((b (match-end 0))
5165 (outline-regexp org-outline-regexp))
5166 (if (re-search-forward
5167 "^[ \t]*:END:"
5168 (save-excursion (outline-next-heading) (point)) t)
5169 (outline-flag-region b (point-at-eol) flag)
5170 (error ":END: line missing"))))))
5172 (defun org-subtree-end-visible-p ()
5173 "Is the end of the current subtree visible?"
5174 (pos-visible-in-window-p
5175 (save-excursion (org-end-of-subtree t) (point))))
5177 (defun org-first-headline-recenter (&optional N)
5178 "Move cursor to the first headline and recenter the headline.
5179 Optional argument N means, put the headline into the Nth line of the window."
5180 (goto-char (point-min))
5181 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5182 (beginning-of-line)
5183 (recenter (prefix-numeric-value N))))
5185 ;;; Folding of blocks
5187 (defconst org-block-regexp
5189 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5190 "Regular expression for hiding blocks.")
5192 (defvar org-hide-block-overlays nil
5193 "Overays hiding blocks.")
5194 (make-variable-buffer-local 'org-hide-block-overlays)
5196 (defun org-block-map (function &optional start end)
5197 "Call func at the head of all source blocks in the current
5198 buffer. Optional arguments START and END can be used to limit
5199 the range."
5200 (let ((start (or start (point-min)))
5201 (end (or end (point-max))))
5202 (save-excursion
5203 (goto-char start)
5204 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5205 (save-excursion
5206 (save-match-data
5207 (goto-char (match-beginning 0))
5208 (funcall function)))))))
5210 (defun org-hide-block-toggle-all ()
5211 "Toggle the visibility of all blocks in the current buffer."
5212 (org-block-map #'org-hide-block-toggle))
5214 (defun org-hide-block-all ()
5215 "Fold all blocks in the current buffer."
5216 (interactive)
5217 (org-show-block-all)
5218 (org-block-map #'org-hide-block-toggle-maybe))
5220 (defun org-show-block-all ()
5221 "Unfold all blocks in the current buffer."
5222 (mapc 'org-delete-overlay org-hide-block-overlays)
5223 (setq org-hide-block-overlays nil))
5225 (defun org-hide-block-toggle-maybe ()
5226 "Toggle visibility of block at point."
5227 (interactive)
5228 (let ((case-fold-search t))
5229 (if (save-excursion
5230 (beginning-of-line 1)
5231 (looking-at org-block-regexp))
5232 (progn (org-hide-block-toggle)
5233 t) ;; to signal that we took action
5234 nil))) ;; to signal that we did not
5236 (defun org-hide-block-toggle (&optional force)
5237 "Toggle the visibility of the current block."
5238 (interactive)
5239 (save-excursion
5240 (beginning-of-line)
5241 (if (re-search-forward org-block-regexp nil t)
5242 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5243 (end (match-end 0))
5244 ov) ;; end of entire body
5245 (if (memq t (mapcar (lambda (overlay)
5246 (eq (org-overlay-get overlay 'invisible)
5247 'org-hide-block))
5248 (org-overlays-at start)))
5249 (if (or (not force) (eq force 'off))
5250 (mapc (lambda (ov)
5251 (when (member ov org-hide-block-overlays)
5252 (setq org-hide-block-overlays
5253 (delq ov org-hide-block-overlays)))
5254 (when (eq (org-overlay-get ov 'invisible)
5255 'org-hide-block)
5256 (org-delete-overlay ov)))
5257 (org-overlays-at start)))
5258 (setq ov (org-make-overlay start end))
5259 (org-overlay-put ov 'invisible 'org-hide-block)
5260 (push ov org-hide-block-overlays)))
5261 (error "Not looking at a source block"))))
5263 ;; org-tab-after-check-for-cycling-hook
5264 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5265 ;; Remove overlays when changing major mode
5266 (add-hook 'org-mode-hook
5267 (lambda () (org-add-hook 'change-major-mode-hook
5268 'org-show-block-all 'append 'local)))
5270 ;;; Org-goto
5272 (defvar org-goto-window-configuration nil)
5273 (defvar org-goto-marker nil)
5274 (defvar org-goto-map
5275 (let ((map (make-sparse-keymap)))
5276 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5277 (while (setq cmd (pop cmds))
5278 (substitute-key-definition cmd cmd map global-map)))
5279 (suppress-keymap map)
5280 (org-defkey map "\C-m" 'org-goto-ret)
5281 (org-defkey map [(return)] 'org-goto-ret)
5282 (org-defkey map [(left)] 'org-goto-left)
5283 (org-defkey map [(right)] 'org-goto-right)
5284 (org-defkey map [(control ?g)] 'org-goto-quit)
5285 (org-defkey map "\C-i" 'org-cycle)
5286 (org-defkey map [(tab)] 'org-cycle)
5287 (org-defkey map [(down)] 'outline-next-visible-heading)
5288 (org-defkey map [(up)] 'outline-previous-visible-heading)
5289 (if org-goto-auto-isearch
5290 (if (fboundp 'define-key-after)
5291 (define-key-after map [t] 'org-goto-local-auto-isearch)
5292 nil)
5293 (org-defkey map "q" 'org-goto-quit)
5294 (org-defkey map "n" 'outline-next-visible-heading)
5295 (org-defkey map "p" 'outline-previous-visible-heading)
5296 (org-defkey map "f" 'outline-forward-same-level)
5297 (org-defkey map "b" 'outline-backward-same-level)
5298 (org-defkey map "u" 'outline-up-heading))
5299 (org-defkey map "/" 'org-occur)
5300 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5301 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5302 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5303 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5304 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5305 map))
5307 (defconst org-goto-help
5308 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5309 RET=jump to location [Q]uit and return to previous location
5310 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5312 (defvar org-goto-start-pos) ; dynamically scoped parameter
5314 ;; FIXME: Docstring doe not mention both interfaces
5315 (defun org-goto (&optional alternative-interface)
5316 "Look up a different location in the current file, keeping current visibility.
5318 When you want look-up or go to a different location in a document, the
5319 fastest way is often to fold the entire buffer and then dive into the tree.
5320 This method has the disadvantage, that the previous location will be folded,
5321 which may not be what you want.
5323 This command works around this by showing a copy of the current buffer
5324 in an indirect buffer, in overview mode. You can dive into the tree in
5325 that copy, use org-occur and incremental search to find a location.
5326 When pressing RET or `Q', the command returns to the original buffer in
5327 which the visibility is still unchanged. After RET is will also jump to
5328 the location selected in the indirect buffer and expose the
5329 the headline hierarchy above."
5330 (interactive "P")
5331 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5332 (org-refile-use-outline-path t)
5333 (org-refile-target-verify-function nil)
5334 (interface
5335 (if (not alternative-interface)
5336 org-goto-interface
5337 (if (eq org-goto-interface 'outline)
5338 'outline-path-completion
5339 'outline)))
5340 (org-goto-start-pos (point))
5341 (selected-point
5342 (if (eq interface 'outline)
5343 (car (org-get-location (current-buffer) org-goto-help))
5344 (nth 3 (org-refile-get-location "Goto: ")))))
5345 (if selected-point
5346 (progn
5347 (org-mark-ring-push org-goto-start-pos)
5348 (goto-char selected-point)
5349 (if (or (org-invisible-p) (org-invisible-p2))
5350 (org-show-context 'org-goto)))
5351 (message "Quit"))))
5353 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5354 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5355 (defvar org-goto-local-auto-isearch-map) ; defined below
5357 (defun org-get-location (buf help)
5358 "Let the user select a location in the Org-mode buffer BUF.
5359 This function uses a recursive edit. It returns the selected position
5360 or nil."
5361 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5362 (isearch-hide-immediately nil)
5363 (isearch-search-fun-function
5364 (lambda () 'org-goto-local-search-headings))
5365 (org-goto-selected-point org-goto-exit-command))
5366 (save-excursion
5367 (save-window-excursion
5368 (delete-other-windows)
5369 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5370 (switch-to-buffer
5371 (condition-case nil
5372 (make-indirect-buffer (current-buffer) "*org-goto*")
5373 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5374 (with-output-to-temp-buffer "*Help*"
5375 (princ help))
5376 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5377 (setq buffer-read-only nil)
5378 (let ((org-startup-truncated t)
5379 (org-startup-folded nil)
5380 (org-startup-align-all-tables nil))
5381 (org-mode)
5382 (org-overview))
5383 (setq buffer-read-only t)
5384 (if (and (boundp 'org-goto-start-pos)
5385 (integer-or-marker-p org-goto-start-pos))
5386 (let ((org-show-hierarchy-above t)
5387 (org-show-siblings t)
5388 (org-show-following-heading t))
5389 (goto-char org-goto-start-pos)
5390 (and (org-invisible-p) (org-show-context)))
5391 (goto-char (point-min)))
5392 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5393 (message "Select location and press RET")
5394 (use-local-map org-goto-map)
5395 (recursive-edit)
5397 (kill-buffer "*org-goto*")
5398 (cons org-goto-selected-point org-goto-exit-command)))
5400 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5401 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5402 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5403 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5405 (defun org-goto-local-search-headings (string bound noerror)
5406 "Search and make sure that any matches are in headlines."
5407 (catch 'return
5408 (while (if isearch-forward
5409 (search-forward string bound noerror)
5410 (search-backward string bound noerror))
5411 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5412 (and (member :headline context)
5413 (not (member :tags context))))
5414 (throw 'return (point))))))
5416 (defun org-goto-local-auto-isearch ()
5417 "Start isearch."
5418 (interactive)
5419 (goto-char (point-min))
5420 (let ((keys (this-command-keys)))
5421 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5422 (isearch-mode t)
5423 (isearch-process-search-char (string-to-char keys)))))
5425 (defun org-goto-ret (&optional arg)
5426 "Finish `org-goto' by going to the new location."
5427 (interactive "P")
5428 (setq org-goto-selected-point (point)
5429 org-goto-exit-command 'return)
5430 (throw 'exit nil))
5432 (defun org-goto-left ()
5433 "Finish `org-goto' by going to the new location."
5434 (interactive)
5435 (if (org-on-heading-p)
5436 (progn
5437 (beginning-of-line 1)
5438 (setq org-goto-selected-point (point)
5439 org-goto-exit-command 'left)
5440 (throw 'exit nil))
5441 (error "Not on a heading")))
5443 (defun org-goto-right ()
5444 "Finish `org-goto' by going to the new location."
5445 (interactive)
5446 (if (org-on-heading-p)
5447 (progn
5448 (setq org-goto-selected-point (point)
5449 org-goto-exit-command 'right)
5450 (throw 'exit nil))
5451 (error "Not on a heading")))
5453 (defun org-goto-quit ()
5454 "Finish `org-goto' without cursor motion."
5455 (interactive)
5456 (setq org-goto-selected-point nil)
5457 (setq org-goto-exit-command 'quit)
5458 (throw 'exit nil))
5460 ;;; Indirect buffer display of subtrees
5462 (defvar org-indirect-dedicated-frame nil
5463 "This is the frame being used for indirect tree display.")
5464 (defvar org-last-indirect-buffer nil)
5466 (defun org-tree-to-indirect-buffer (&optional arg)
5467 "Create indirect buffer and narrow it to current subtree.
5468 With numerical prefix ARG, go up to this level and then take that tree.
5469 If ARG is negative, go up that many levels.
5470 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5471 indirect buffer previously made with this command, to avoid proliferation of
5472 indirect buffers. However, when you call the command with a `C-u' prefix, or
5473 when `org-indirect-buffer-display' is `new-frame', the last buffer
5474 is kept so that you can work with several indirect buffers at the same time.
5475 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5476 requests that a new frame be made for the new buffer, so that the dedicated
5477 frame is not changed."
5478 (interactive "P")
5479 (let ((cbuf (current-buffer))
5480 (cwin (selected-window))
5481 (pos (point))
5482 beg end level heading ibuf)
5483 (save-excursion
5484 (org-back-to-heading t)
5485 (when (numberp arg)
5486 (setq level (org-outline-level))
5487 (if (< arg 0) (setq arg (+ level arg)))
5488 (while (> (setq level (org-outline-level)) arg)
5489 (outline-up-heading 1 t)))
5490 (setq beg (point)
5491 heading (org-get-heading))
5492 (org-end-of-subtree t) (setq end (point)))
5493 (if (and (buffer-live-p org-last-indirect-buffer)
5494 (not (eq org-indirect-buffer-display 'new-frame))
5495 (not arg))
5496 (kill-buffer org-last-indirect-buffer))
5497 (setq ibuf (org-get-indirect-buffer cbuf)
5498 org-last-indirect-buffer ibuf)
5499 (cond
5500 ((or (eq org-indirect-buffer-display 'new-frame)
5501 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5502 (select-frame (make-frame))
5503 (delete-other-windows)
5504 (switch-to-buffer ibuf)
5505 (org-set-frame-title heading))
5506 ((eq org-indirect-buffer-display 'dedicated-frame)
5507 (raise-frame
5508 (select-frame (or (and org-indirect-dedicated-frame
5509 (frame-live-p org-indirect-dedicated-frame)
5510 org-indirect-dedicated-frame)
5511 (setq org-indirect-dedicated-frame (make-frame)))))
5512 (delete-other-windows)
5513 (switch-to-buffer ibuf)
5514 (org-set-frame-title (concat "Indirect: " heading)))
5515 ((eq org-indirect-buffer-display 'current-window)
5516 (switch-to-buffer ibuf))
5517 ((eq org-indirect-buffer-display 'other-window)
5518 (pop-to-buffer ibuf))
5519 (t (error "Invalid value.")))
5520 (if (featurep 'xemacs)
5521 (save-excursion (org-mode) (turn-on-font-lock)))
5522 (narrow-to-region beg end)
5523 (show-all)
5524 (goto-char pos)
5525 (and (window-live-p cwin) (select-window cwin))))
5527 (defun org-get-indirect-buffer (&optional buffer)
5528 (setq buffer (or buffer (current-buffer)))
5529 (let ((n 1) (base (buffer-name buffer)) bname)
5530 (while (buffer-live-p
5531 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5532 (setq n (1+ n)))
5533 (condition-case nil
5534 (make-indirect-buffer buffer bname 'clone)
5535 (error (make-indirect-buffer buffer bname)))))
5537 (defun org-set-frame-title (title)
5538 "Set the title of the current frame to the string TITLE."
5539 ;; FIXME: how to name a single frame in XEmacs???
5540 (unless (featurep 'xemacs)
5541 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5543 ;;;; Structure editing
5545 ;;; Inserting headlines
5547 (defun org-previous-line-empty-p ()
5548 (save-excursion
5549 (and (not (bobp))
5550 (or (beginning-of-line 0) t)
5551 (save-match-data
5552 (looking-at "[ \t]*$")))))
5554 (defun org-insert-heading (&optional force-heading)
5555 "Insert a new heading or item with same depth at point.
5556 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5557 If point is at the beginning of a headline, insert a sibling before the
5558 current headline. If point is not at the beginning, do not split the line,
5559 but create the new headline after the current line."
5560 (interactive "P")
5561 (if (= (buffer-size) 0)
5562 (insert "\n* ")
5563 (when (or force-heading (not (org-insert-item)))
5564 (let* ((empty-line-p nil)
5565 (head (save-excursion
5566 (condition-case nil
5567 (progn
5568 (org-back-to-heading)
5569 (setq empty-line-p (org-previous-line-empty-p))
5570 (match-string 0))
5571 (error "*"))))
5572 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5573 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5574 pos hide-previous previous-pos)
5575 (cond
5576 ((and (org-on-heading-p) (bolp)
5577 (or (bobp)
5578 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5579 ;; insert before the current line
5580 (open-line (if blank 2 1)))
5581 ((and (bolp)
5582 (or (bobp)
5583 (save-excursion
5584 (backward-char 1) (not (org-invisible-p)))))
5585 ;; insert right here
5586 nil)
5588 ;; somewhere in the line
5589 (save-excursion
5590 (setq previous-pos (point-at-bol))
5591 (end-of-line)
5592 (setq hide-previous (org-invisible-p)))
5593 (and org-insert-heading-respect-content (org-show-subtree))
5594 (let ((split
5595 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5596 (save-excursion
5597 (let ((p (point)))
5598 (goto-char (point-at-bol))
5599 (and (looking-at org-complex-heading-regexp)
5600 (> p (match-beginning 4)))))))
5601 tags pos)
5602 (cond
5603 (org-insert-heading-respect-content
5604 (org-end-of-subtree nil t)
5605 (or (bolp) (newline))
5606 (or (org-previous-line-empty-p)
5607 (and blank (newline)))
5608 (open-line 1))
5609 ((org-on-heading-p)
5610 (when hide-previous
5611 (show-children)
5612 (org-show-entry))
5613 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5614 (setq tags (and (match-end 2) (match-string 2)))
5615 (and (match-end 1)
5616 (delete-region (match-beginning 1) (match-end 1)))
5617 (setq pos (point-at-bol))
5618 (or split (end-of-line 1))
5619 (delete-horizontal-space)
5620 (newline (if blank 2 1))
5621 (when tags
5622 (save-excursion
5623 (goto-char pos)
5624 (end-of-line 1)
5625 (insert " " tags)
5626 (org-set-tags nil 'align))))
5628 (or split (end-of-line 1))
5629 (newline (if blank 2 1)))))))
5630 (insert head) (just-one-space)
5631 (setq pos (point))
5632 (end-of-line 1)
5633 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5634 (when (and org-insert-heading-respect-content hide-previous)
5635 (save-excursion
5636 (goto-char previous-pos)
5637 (hide-subtree)))
5638 (run-hooks 'org-insert-heading-hook)))))
5640 (defun org-get-heading (&optional no-tags)
5641 "Return the heading of the current entry, without the stars."
5642 (save-excursion
5643 (org-back-to-heading t)
5644 (if (looking-at
5645 (if no-tags
5646 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5647 "\\*+[ \t]+\\([^\r\n]*\\)"))
5648 (match-string 1) "")))
5650 (defun org-heading-components ()
5651 "Return the components of the current heading.
5652 This is a list with the following elements:
5653 - the level as an integer
5654 - the reduced level, different if `org-odd-levels-only' is set.
5655 - the TODO keyword, or nil
5656 - the priority character, like ?A, or nil if no priority is given
5657 - the headline text itself, or the tags string if no headline text
5658 - the tags string, or nil."
5659 (save-excursion
5660 (org-back-to-heading t)
5661 (if (looking-at org-complex-heading-regexp)
5662 (list (length (match-string 1))
5663 (org-reduced-level (length (match-string 1)))
5664 (org-match-string-no-properties 2)
5665 (and (match-end 3) (aref (match-string 3) 2))
5666 (org-match-string-no-properties 4)
5667 (org-match-string-no-properties 5)))))
5669 (defun org-get-entry ()
5670 "Get the entry text, after heading, entire subtree."
5671 (save-excursion
5672 (org-back-to-heading t)
5673 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5675 (defun org-insert-heading-after-current ()
5676 "Insert a new heading with same level as current, after current subtree."
5677 (interactive)
5678 (org-back-to-heading)
5679 (org-insert-heading)
5680 (org-move-subtree-down)
5681 (end-of-line 1))
5683 (defun org-insert-heading-respect-content ()
5684 (interactive)
5685 (let ((org-insert-heading-respect-content t))
5686 (org-insert-heading t)))
5688 (defun org-insert-todo-heading-respect-content (&optional force-state)
5689 (interactive "P")
5690 (let ((org-insert-heading-respect-content t))
5691 (org-insert-todo-heading force-state t)))
5693 (defun org-insert-todo-heading (arg &optional force-heading)
5694 "Insert a new heading with the same level and TODO state as current heading.
5695 If the heading has no TODO state, or if the state is DONE, use the first
5696 state (TODO by default). Also with prefix arg, force first state."
5697 (interactive "P")
5698 (when (or force-heading (not (org-insert-item 'checkbox)))
5699 (org-insert-heading force-heading)
5700 (save-excursion
5701 (org-back-to-heading)
5702 (outline-previous-heading)
5703 (looking-at org-todo-line-regexp))
5704 (let*
5705 ((new-mark-x
5706 (if (or arg
5707 (not (match-beginning 2))
5708 (member (match-string 2) org-done-keywords))
5709 (car org-todo-keywords-1)
5710 (match-string 2)))
5711 (new-mark
5713 (run-hook-with-args-until-success
5714 'org-todo-get-default-hook new-mark-x nil)
5715 new-mark-x)))
5716 (beginning-of-line 1)
5717 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5718 (if org-treat-insert-todo-heading-as-state-change
5719 (org-todo new-mark)
5720 (insert new-mark " "))))
5721 (when org-provide-todo-statistics
5722 (org-update-parent-todo-statistics))))
5724 (defun org-insert-subheading (arg)
5725 "Insert a new subheading and demote it.
5726 Works for outline headings and for plain lists alike."
5727 (interactive "P")
5728 (org-insert-heading arg)
5729 (cond
5730 ((org-on-heading-p) (org-do-demote))
5731 ((org-at-item-p) (org-indent-item 1))))
5733 (defun org-insert-todo-subheading (arg)
5734 "Insert a new subheading with TODO keyword or checkbox and demote it.
5735 Works for outline headings and for plain lists alike."
5736 (interactive "P")
5737 (org-insert-todo-heading arg)
5738 (cond
5739 ((org-on-heading-p) (org-do-demote))
5740 ((org-at-item-p) (org-indent-item 1))))
5742 ;;; Promotion and Demotion
5744 (defun org-promote-subtree ()
5745 "Promote the entire subtree.
5746 See also `org-promote'."
5747 (interactive)
5748 (save-excursion
5749 (org-map-tree 'org-promote))
5750 (org-fix-position-after-promote))
5752 (defun org-demote-subtree ()
5753 "Demote the entire subtree. See `org-demote'.
5754 See also `org-promote'."
5755 (interactive)
5756 (save-excursion
5757 (org-map-tree 'org-demote))
5758 (org-fix-position-after-promote))
5761 (defun org-do-promote ()
5762 "Promote the current heading higher up the tree.
5763 If the region is active in `transient-mark-mode', promote all headings
5764 in the region."
5765 (interactive)
5766 (save-excursion
5767 (if (org-region-active-p)
5768 (org-map-region 'org-promote (region-beginning) (region-end))
5769 (org-promote)))
5770 (org-fix-position-after-promote))
5772 (defun org-do-demote ()
5773 "Demote the current heading lower down the tree.
5774 If the region is active in `transient-mark-mode', demote all headings
5775 in the region."
5776 (interactive)
5777 (save-excursion
5778 (if (org-region-active-p)
5779 (org-map-region 'org-demote (region-beginning) (region-end))
5780 (org-demote)))
5781 (org-fix-position-after-promote))
5783 (defun org-fix-position-after-promote ()
5784 "Make sure that after pro/demotion cursor position is right."
5785 (let ((pos (point)))
5786 (when (save-excursion
5787 (beginning-of-line 1)
5788 (looking-at org-todo-line-regexp)
5789 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5790 (cond ((eobp) (insert " "))
5791 ((eolp) (insert " "))
5792 ((equal (char-after) ?\ ) (forward-char 1))))))
5794 (defun org-reduced-level (l)
5795 "Compute the effective level of a heading.
5796 This takes into account the setting of `org-odd-levels-only'."
5797 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5799 (defun org-get-valid-level (level &optional change)
5800 "Rectify a level change under the influence of `org-odd-levels-only'
5801 LEVEL is a current level, CHANGE is by how much the level should be
5802 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5803 even level numbers will become the next higher odd number."
5804 (if org-odd-levels-only
5805 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5806 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5807 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5808 (max 1 (+ level (or change 0)))))
5810 (if (boundp 'define-obsolete-function-alias)
5811 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5812 (define-obsolete-function-alias 'org-get-legal-level
5813 'org-get-valid-level)
5814 (define-obsolete-function-alias 'org-get-legal-level
5815 'org-get-valid-level "23.1")))
5817 (defun org-promote ()
5818 "Promote the current heading higher up the tree.
5819 If the region is active in `transient-mark-mode', promote all headings
5820 in the region."
5821 (org-back-to-heading t)
5822 (let* ((level (save-match-data (funcall outline-level)))
5823 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5824 (diff (abs (- level (length up-head) -1))))
5825 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5826 (replace-match up-head nil t)
5827 ;; Fixup tag positioning
5828 (and org-auto-align-tags (org-set-tags nil t))
5829 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5831 (defun org-demote ()
5832 "Demote the current heading lower down the tree.
5833 If the region is active in `transient-mark-mode', demote all headings
5834 in the region."
5835 (org-back-to-heading t)
5836 (let* ((level (save-match-data (funcall outline-level)))
5837 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5838 (diff (abs (- level (length down-head) -1))))
5839 (replace-match down-head nil t)
5840 ;; Fixup tag positioning
5841 (and org-auto-align-tags (org-set-tags nil t))
5842 (if org-adapt-indentation (org-fixup-indentation diff))))
5844 (defun org-map-tree (fun)
5845 "Call FUN for every heading underneath the current one."
5846 (org-back-to-heading)
5847 (let ((level (funcall outline-level)))
5848 (save-excursion
5849 (funcall fun)
5850 (while (and (progn
5851 (outline-next-heading)
5852 (> (funcall outline-level) level))
5853 (not (eobp)))
5854 (funcall fun)))))
5856 (defun org-map-region (fun beg end)
5857 "Call FUN for every heading between BEG and END."
5858 (let ((org-ignore-region t))
5859 (save-excursion
5860 (setq end (copy-marker end))
5861 (goto-char beg)
5862 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5863 (< (point) end))
5864 (funcall fun))
5865 (while (and (progn
5866 (outline-next-heading)
5867 (< (point) end))
5868 (not (eobp)))
5869 (funcall fun)))))
5871 (defun org-fixup-indentation (diff)
5872 "Change the indentation in the current entry by DIFF
5873 However, if any line in the current entry has no indentation, or if it
5874 would end up with no indentation after the change, nothing at all is done."
5875 (save-excursion
5876 (let ((end (save-excursion (outline-next-heading)
5877 (point-marker)))
5878 (prohibit (if (> diff 0)
5879 "^\\S-"
5880 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5881 col)
5882 (unless (save-excursion (end-of-line 1)
5883 (re-search-forward prohibit end t))
5884 (while (and (< (point) end)
5885 (re-search-forward "^[ \t]+" end t))
5886 (goto-char (match-end 0))
5887 (setq col (current-column))
5888 (if (< diff 0) (replace-match ""))
5889 (org-indent-to-column (+ diff col))))
5890 (move-marker end nil))))
5892 (defun org-convert-to-odd-levels ()
5893 "Convert an org-mode file with all levels allowed to one with odd levels.
5894 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5895 level 5 etc."
5896 (interactive)
5897 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5898 (let ((org-odd-levels-only nil) n)
5899 (save-excursion
5900 (goto-char (point-min))
5901 (while (re-search-forward "^\\*\\*+ " nil t)
5902 (setq n (- (length (match-string 0)) 2))
5903 (while (>= (setq n (1- n)) 0)
5904 (org-demote))
5905 (end-of-line 1))))))
5908 (defun org-convert-to-oddeven-levels ()
5909 "Convert an org-mode file with only odd levels to one with odd and even levels.
5910 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5911 section with an even level, conversion would destroy the structure of the file. An error
5912 is signaled in this case."
5913 (interactive)
5914 (goto-char (point-min))
5915 ;; First check if there are no even levels
5916 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5917 (org-show-context t)
5918 (error "Not all levels are odd in this file. Conversion not possible."))
5919 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5920 (let ((org-odd-levels-only nil) n)
5921 (save-excursion
5922 (goto-char (point-min))
5923 (while (re-search-forward "^\\*\\*+ " nil t)
5924 (setq n (/ (1- (length (match-string 0))) 2))
5925 (while (>= (setq n (1- n)) 0)
5926 (org-promote))
5927 (end-of-line 1))))))
5929 (defun org-tr-level (n)
5930 "Make N odd if required."
5931 (if org-odd-levels-only (1+ (/ n 2)) n))
5933 ;;; Vertical tree motion, cutting and pasting of subtrees
5935 (defun org-move-subtree-up (&optional arg)
5936 "Move the current subtree up past ARG headlines of the same level."
5937 (interactive "p")
5938 (org-move-subtree-down (- (prefix-numeric-value arg))))
5940 (defun org-move-subtree-down (&optional arg)
5941 "Move the current subtree down past ARG headlines of the same level."
5942 (interactive "p")
5943 (setq arg (prefix-numeric-value arg))
5944 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5945 'outline-get-last-sibling))
5946 (ins-point (make-marker))
5947 (cnt (abs arg))
5948 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5949 ;; Select the tree
5950 (org-back-to-heading)
5951 (setq beg0 (point))
5952 (save-excursion
5953 (setq ne-beg (org-back-over-empty-lines))
5954 (setq beg (point)))
5955 (save-match-data
5956 (save-excursion (outline-end-of-heading)
5957 (setq folded (org-invisible-p)))
5958 (outline-end-of-subtree))
5959 (outline-next-heading)
5960 (setq ne-end (org-back-over-empty-lines))
5961 (setq end (point))
5962 (goto-char beg0)
5963 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5964 ;; include less whitespace
5965 (save-excursion
5966 (goto-char beg)
5967 (forward-line (- ne-beg ne-end))
5968 (setq beg (point))))
5969 ;; Find insertion point, with error handling
5970 (while (> cnt 0)
5971 (or (and (funcall movfunc) (looking-at outline-regexp))
5972 (progn (goto-char beg0)
5973 (error "Cannot move past superior level or buffer limit")))
5974 (setq cnt (1- cnt)))
5975 (if (> arg 0)
5976 ;; Moving forward - still need to move over subtree
5977 (progn (org-end-of-subtree t t)
5978 (save-excursion
5979 (org-back-over-empty-lines)
5980 (or (bolp) (newline)))))
5981 (setq ne-ins (org-back-over-empty-lines))
5982 (move-marker ins-point (point))
5983 (setq txt (buffer-substring beg end))
5984 (org-save-markers-in-region beg end)
5985 (delete-region beg end)
5986 (org-remove-empty-overlays-at beg)
5987 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5988 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5989 (and (not (bolp)) (looking-at "\n") (forward-char 1))
5990 (let ((bbb (point)))
5991 (insert-before-markers txt)
5992 (org-reinstall-markers-in-region bbb)
5993 (move-marker ins-point bbb))
5994 (or (bolp) (insert "\n"))
5995 (setq ins-end (point))
5996 (goto-char ins-point)
5997 (org-skip-whitespace)
5998 (when (and (< arg 0)
5999 (org-first-sibling-p)
6000 (> ne-ins ne-beg))
6001 ;; Move whitespace back to beginning
6002 (save-excursion
6003 (goto-char ins-end)
6004 (let ((kill-whole-line t))
6005 (kill-line (- ne-ins ne-beg)) (point)))
6006 (insert (make-string (- ne-ins ne-beg) ?\n)))
6007 (move-marker ins-point nil)
6008 (if folded
6009 (hide-entry)
6010 (org-show-entry)
6011 (show-children)
6012 (org-cycle-hide-drawers 'children))
6013 (org-clean-visibility-after-subtree-move)))
6015 (defvar org-subtree-clip ""
6016 "Clipboard for cut and paste of subtrees.
6017 This is actually only a copy of the kill, because we use the normal kill
6018 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6020 (defvar org-subtree-clip-folded nil
6021 "Was the last copied subtree folded?
6022 This is used to fold the tree back after pasting.")
6024 (defun org-cut-subtree (&optional n)
6025 "Cut the current subtree into the clipboard.
6026 With prefix arg N, cut this many sequential subtrees.
6027 This is a short-hand for marking the subtree and then cutting it."
6028 (interactive "p")
6029 (org-copy-subtree n 'cut))
6031 (defun org-copy-subtree (&optional n cut force-store-markers)
6032 "Cut the current subtree into the clipboard.
6033 With prefix arg N, cut this many sequential subtrees.
6034 This is a short-hand for marking the subtree and then copying it.
6035 If CUT is non-nil, actually cut the subtree.
6036 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6037 of some markers in the region, even if CUT is non-nil. This is
6038 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6039 (interactive "p")
6040 (let (beg end folded (beg0 (point)))
6041 (if (interactive-p)
6042 (org-back-to-heading nil) ; take what looks like a subtree
6043 (org-back-to-heading t)) ; take what is really there
6044 (org-back-over-empty-lines)
6045 (setq beg (point))
6046 (skip-chars-forward " \t\r\n")
6047 (save-match-data
6048 (save-excursion (outline-end-of-heading)
6049 (setq folded (org-invisible-p)))
6050 (condition-case nil
6051 (outline-forward-same-level (1- n))
6052 (error nil))
6053 (org-end-of-subtree t t))
6054 (org-back-over-empty-lines)
6055 (setq end (point))
6056 (goto-char beg0)
6057 (when (> end beg)
6058 (setq org-subtree-clip-folded folded)
6059 (when (or cut force-store-markers)
6060 (org-save-markers-in-region beg end))
6061 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6062 (setq org-subtree-clip (current-kill 0))
6063 (message "%s: Subtree(s) with %d characters"
6064 (if cut "Cut" "Copied")
6065 (length org-subtree-clip)))))
6067 (defun org-paste-subtree (&optional level tree for-yank)
6068 "Paste the clipboard as a subtree, with modification of headline level.
6069 The entire subtree is promoted or demoted in order to match a new headline
6070 level.
6072 If the cursor is at the beginning of a headline, the same level as
6073 that headline is used to paste the tree
6075 If not, the new level is derived from the *visible* headings
6076 before and after the insertion point, and taken to be the inferior headline
6077 level of the two. So if the previous visible heading is level 3 and the
6078 next is level 4 (or vice versa), level 4 will be used for insertion.
6079 This makes sure that the subtree remains an independent subtree and does
6080 not swallow low level entries.
6082 You can also force a different level, either by using a numeric prefix
6083 argument, or by inserting the heading marker by hand. For example, if the
6084 cursor is after \"*****\", then the tree will be shifted to level 5.
6086 If optional TREE is given, use this text instead of the kill ring.
6088 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6089 move back over whitespace before inserting, and move point to the end of
6090 the inserted text when done."
6091 (interactive "P")
6092 (unless (org-kill-is-subtree-p tree)
6093 (error "%s"
6094 (substitute-command-keys
6095 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6096 (let* ((visp (not (org-invisible-p)))
6097 (txt (or tree (and kill-ring (current-kill 0))))
6098 (^re (concat "^\\(" outline-regexp "\\)"))
6099 (re (concat "\\(" outline-regexp "\\)"))
6100 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6102 (old-level (if (string-match ^re txt)
6103 (- (match-end 0) (match-beginning 0) 1)
6104 -1))
6105 (force-level (cond (level (prefix-numeric-value level))
6106 ((and (looking-at "[ \t]*$")
6107 (string-match
6108 ^re_ (buffer-substring
6109 (point-at-bol) (point))))
6110 (- (match-end 1) (match-beginning 1)))
6111 ((and (bolp)
6112 (looking-at org-outline-regexp))
6113 (- (match-end 0) (point) 1))
6114 (t nil)))
6115 (previous-level (save-excursion
6116 (condition-case nil
6117 (progn
6118 (outline-previous-visible-heading 1)
6119 (if (looking-at re)
6120 (- (match-end 0) (match-beginning 0) 1)
6122 (error 1))))
6123 (next-level (save-excursion
6124 (condition-case nil
6125 (progn
6126 (or (looking-at outline-regexp)
6127 (outline-next-visible-heading 1))
6128 (if (looking-at re)
6129 (- (match-end 0) (match-beginning 0) 1)
6131 (error 1))))
6132 (new-level (or force-level (max previous-level next-level)))
6133 (shift (if (or (= old-level -1)
6134 (= new-level -1)
6135 (= old-level new-level))
6137 (- new-level old-level)))
6138 (delta (if (> shift 0) -1 1))
6139 (func (if (> shift 0) 'org-demote 'org-promote))
6140 (org-odd-levels-only nil)
6141 beg end newend)
6142 ;; Remove the forced level indicator
6143 (if force-level
6144 (delete-region (point-at-bol) (point)))
6145 ;; Paste
6146 (beginning-of-line 1)
6147 (unless for-yank (org-back-over-empty-lines))
6148 (setq beg (point))
6149 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6150 (insert-before-markers txt)
6151 (unless (string-match "\n\\'" txt) (insert "\n"))
6152 (setq newend (point))
6153 (org-reinstall-markers-in-region beg)
6154 (setq end (point))
6155 (goto-char beg)
6156 (skip-chars-forward " \t\n\r")
6157 (setq beg (point))
6158 (if (and (org-invisible-p) visp)
6159 (save-excursion (outline-show-heading)))
6160 ;; Shift if necessary
6161 (unless (= shift 0)
6162 (save-restriction
6163 (narrow-to-region beg end)
6164 (while (not (= shift 0))
6165 (org-map-region func (point-min) (point-max))
6166 (setq shift (+ delta shift)))
6167 (goto-char (point-min))
6168 (setq newend (point-max))))
6169 (when (or (interactive-p) for-yank)
6170 (message "Clipboard pasted as level %d subtree" new-level))
6171 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6172 kill-ring
6173 (eq org-subtree-clip (current-kill 0))
6174 org-subtree-clip-folded)
6175 ;; The tree was folded before it was killed/copied
6176 (hide-subtree))
6177 (and for-yank (goto-char newend))))
6179 (defun org-kill-is-subtree-p (&optional txt)
6180 "Check if the current kill is an outline subtree, or a set of trees.
6181 Returns nil if kill does not start with a headline, or if the first
6182 headline level is not the largest headline level in the tree.
6183 So this will actually accept several entries of equal levels as well,
6184 which is OK for `org-paste-subtree'.
6185 If optional TXT is given, check this string instead of the current kill."
6186 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6187 (start-level (and kill
6188 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6189 org-outline-regexp "\\)")
6190 kill)
6191 (- (match-end 2) (match-beginning 2) 1)))
6192 (re (concat "^" org-outline-regexp))
6193 (start (1+ (or (match-beginning 2) -1))))
6194 (if (not start-level)
6195 (progn
6196 nil) ;; does not even start with a heading
6197 (catch 'exit
6198 (while (setq start (string-match re kill (1+ start)))
6199 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6200 (throw 'exit nil)))
6201 t))))
6203 (defvar org-markers-to-move nil
6204 "Markers that should be moved with a cut-and-paste operation.
6205 Those markers are stored together with their positions relative to
6206 the start of the region.")
6208 (defun org-save-markers-in-region (beg end)
6209 "Check markers in region.
6210 If these markers are between BEG and END, record their position relative
6211 to BEG, so that after moving the block of text, we can put the markers back
6212 into place.
6213 This function gets called just before an entry or tree gets cut from the
6214 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6215 called immediately, to move the markers with the entries."
6216 (setq org-markers-to-move nil)
6217 (when (featurep 'org-clock)
6218 (org-clock-save-markers-for-cut-and-paste beg end))
6219 (when (featurep 'org-agenda)
6220 (org-agenda-save-markers-for-cut-and-paste beg end)))
6222 (defun org-check-and-save-marker (marker beg end)
6223 "Check if MARKER is between BEG and END.
6224 If yes, remember the marker and the distance to BEG."
6225 (when (and (marker-buffer marker)
6226 (equal (marker-buffer marker) (current-buffer)))
6227 (if (and (>= marker beg) (< marker end))
6228 (push (cons marker (- marker beg)) org-markers-to-move))))
6230 (defun org-reinstall-markers-in-region (beg)
6231 "Move all remembered markers to their position relative to BEG."
6232 (mapc (lambda (x)
6233 (move-marker (car x) (+ beg (cdr x))))
6234 org-markers-to-move)
6235 (setq org-markers-to-move nil))
6237 (defun org-narrow-to-subtree ()
6238 "Narrow buffer to the current subtree."
6239 (interactive)
6240 (save-excursion
6241 (save-match-data
6242 (narrow-to-region
6243 (progn (org-back-to-heading t) (point))
6244 (progn (org-end-of-subtree t) (point))))))
6246 (defun org-clone-subtree-with-time-shift (n &optional shift)
6247 "Clone the task (subtree) at point N times.
6248 The clones will be inserted as siblings.
6250 In interactive use, the user will be prompted for the number of clones
6251 to be produced, and for a time SHIFT, which may be a repeater as used
6252 in time stamps, for example `+3d'.
6254 When a valid repeater is given and the entry contains any time stamps,
6255 the clones will become a sequence in time, with time stamps in the
6256 subtree shifted for each clone produced. If SHIFT is nil or the
6257 empty string, time stamps will be left alone.
6259 If the original subtree did contain time stamps with a repeater,
6260 the following will happen:
6261 - the repeater will be removed in each clone
6262 - an additional clone will be produced, with the current, unshifted
6263 date(s) in the entry.
6264 - the original entry will be placed *after* all the clones, with
6265 repeater intact.
6266 - the start days in the repeater in the original entry will be shifted
6267 to past the last clone.
6268 I this way you can spell out a number of instances of a repeating task,
6269 and still retain the repeater to cover future instances of the task."
6270 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6271 (let (beg end template task
6272 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6273 (if (not (and (integerp n) (> n 0)))
6274 (error "Invalid number of replications %s" n))
6275 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6276 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6277 shift)))
6278 (error "Invalid shift specification %s" shift))
6279 (when doshift
6280 (setq shift-n (string-to-number (match-string 1 shift))
6281 shift-what (cdr (assoc (match-string 2 shift)
6282 '(("d" . day) ("w" . week)
6283 ("m" . month) ("y" . year))))))
6284 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6285 (setq nmin 1 nmax n)
6286 (org-back-to-heading t)
6287 (setq beg (point))
6288 (org-end-of-subtree t t)
6289 (setq end (point))
6290 (setq template (buffer-substring beg end))
6291 (when (and doshift
6292 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6293 (delete-region beg end)
6294 (setq end beg)
6295 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6296 (goto-char end)
6297 (loop for n from nmin to nmax do
6298 (if (not doshift)
6299 (setq task template)
6300 (with-temp-buffer
6301 (insert template)
6302 (org-mode)
6303 (goto-char (point-min))
6304 (while (re-search-forward org-ts-regexp-both nil t)
6305 (org-timestamp-change (* n shift-n) shift-what))
6306 (unless (= n n-no-remove)
6307 (goto-char (point-min))
6308 (while (re-search-forward org-ts-regexp nil t)
6309 (save-excursion
6310 (goto-char (match-beginning 0))
6311 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6312 (delete-region (match-beginning 1) (match-end 1))))))
6313 (setq task (buffer-string))))
6314 (insert task))
6315 (goto-char beg)))
6317 ;;; Outline Sorting
6319 (defun org-sort (with-case)
6320 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6321 Optional argument WITH-CASE means sort case-sensitively.
6322 With a double prefix argument, also remove duplicate entries."
6323 (interactive "P")
6324 (if (org-at-table-p)
6325 (org-call-with-arg 'org-table-sort-lines with-case)
6326 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6328 (defun org-sort-remove-invisible (s)
6329 (remove-text-properties 0 (length s) org-rm-props s)
6330 (while (string-match org-bracket-link-regexp s)
6331 (setq s (replace-match (if (match-end 2)
6332 (match-string 3 s)
6333 (match-string 1 s)) t t s)))
6336 (defvar org-priority-regexp) ; defined later in the file
6338 (defvar org-after-sorting-entries-or-items-hook nil
6339 "Hook that is run after a bunch of entries or items have been sorted.
6340 When children are sorted, the cursor is in the parent line when this
6341 hook gets called. When a region or a plain list is sorted, the cursor
6342 will be in the first entry of the sorted region/list.")
6344 (defun org-sort-entries-or-items
6345 (&optional with-case sorting-type getkey-func compare-func property)
6346 "Sort entries on a certain level of an outline tree, or plain list items.
6347 If there is an active region, the entries in the region are sorted.
6348 Else, if the cursor is before the first entry, sort the top-level items.
6349 Else, the children of the entry at point are sorted.
6350 If the cursor is at the first item in a plain list, the list items will be
6351 sorted.
6353 Sorting can be alphabetically, numerically, by date/time as given by
6354 a time stamp, by a property or by priority.
6356 The command prompts for the sorting type unless it has been given to the
6357 function through the SORTING-TYPE argument, which needs to a character,
6358 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6359 precise meaning of each character:
6361 n Numerically, by converting the beginning of the entry/item to a number.
6362 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6363 t By date/time, either the first active time stamp in the entry, or, if
6364 none exist, by the first inactive one.
6365 In items, only the first line will be chekced.
6366 s By the scheduled date/time.
6367 d By deadline date/time.
6368 c By creation time, which is assumed to be the first inactive time stamp
6369 at the beginning of a line.
6370 p By priority according to the cookie.
6371 r By the value of a property.
6373 Capital letters will reverse the sort order.
6375 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6376 called with point at the beginning of the record. It must return either
6377 a string or a number that should serve as the sorting key for that record.
6379 Comparing entries ignores case by default. However, with an optional argument
6380 WITH-CASE, the sorting considers case as well."
6381 (interactive "P")
6382 (let ((case-func (if with-case 'identity 'downcase))
6383 start beg end stars re re2
6384 txt what tmp plain-list-p)
6385 ;; Find beginning and end of region to sort
6386 (cond
6387 ((org-region-active-p)
6388 ;; we will sort the region
6389 (setq end (region-end)
6390 what "region")
6391 (goto-char (region-beginning))
6392 (if (not (org-on-heading-p)) (outline-next-heading))
6393 (setq start (point)))
6394 ((org-at-item-p)
6395 ;; we will sort this plain list
6396 (org-beginning-of-item-list) (setq start (point))
6397 (org-end-of-item-list) (setq end (point))
6398 (goto-char start)
6399 (setq plain-list-p t
6400 what "plain list"))
6401 ((or (org-on-heading-p)
6402 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6403 ;; we will sort the children of the current headline
6404 (org-back-to-heading)
6405 (setq start (point)
6406 end (progn (org-end-of-subtree t t)
6407 (org-back-over-empty-lines)
6408 (point))
6409 what "children")
6410 (goto-char start)
6411 (show-subtree)
6412 (outline-next-heading))
6414 ;; we will sort the top-level entries in this file
6415 (goto-char (point-min))
6416 (or (org-on-heading-p) (outline-next-heading))
6417 (setq start (point) end (point-max) what "top-level")
6418 (goto-char start)
6419 (show-all)))
6421 (setq beg (point))
6422 (if (>= beg end) (error "Nothing to sort"))
6424 (unless plain-list-p
6425 (looking-at "\\(\\*+\\)")
6426 (setq stars (match-string 1)
6427 re (concat "^" (regexp-quote stars) " +")
6428 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6429 txt (buffer-substring beg end))
6430 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6431 (if (and (not (equal stars "*")) (string-match re2 txt))
6432 (error "Region to sort contains a level above the first entry")))
6434 (unless sorting-type
6435 (message
6436 (if plain-list-p
6437 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6438 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6439 [t]ime [s]cheduled [d]eadline [c]reated
6440 A/N/T/S/D/C/P/O/F means reversed:")
6441 what)
6442 (setq sorting-type (read-char-exclusive))
6444 (and (= (downcase sorting-type) ?f)
6445 (setq getkey-func
6446 (org-ido-completing-read "Sort using function: "
6447 obarray 'fboundp t nil nil))
6448 (setq getkey-func (intern getkey-func)))
6450 (and (= (downcase sorting-type) ?r)
6451 (setq property
6452 (org-ido-completing-read "Property: "
6453 (mapcar 'list (org-buffer-property-keys t))
6454 nil t))))
6456 (message "Sorting entries...")
6458 (save-restriction
6459 (narrow-to-region start end)
6461 (let ((dcst (downcase sorting-type))
6462 (case-fold-search nil)
6463 (now (current-time)))
6464 (sort-subr
6465 (/= dcst sorting-type)
6466 ;; This function moves to the beginning character of the "record" to
6467 ;; be sorted.
6468 (if plain-list-p
6469 (lambda nil
6470 (if (org-at-item-p) t (goto-char (point-max))))
6471 (lambda nil
6472 (if (re-search-forward re nil t)
6473 (goto-char (match-beginning 0))
6474 (goto-char (point-max)))))
6475 ;; This function moves to the last character of the "record" being
6476 ;; sorted.
6477 (if plain-list-p
6478 'org-end-of-item
6479 (lambda nil
6480 (save-match-data
6481 (condition-case nil
6482 (outline-forward-same-level 1)
6483 (error
6484 (goto-char (point-max)))))))
6486 ;; This function returns the value that gets sorted against.
6487 (if plain-list-p
6488 (lambda nil
6489 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6490 (cond
6491 ((= dcst ?n)
6492 (string-to-number (buffer-substring (match-end 0)
6493 (point-at-eol))))
6494 ((= dcst ?a)
6495 (buffer-substring (match-end 0) (point-at-eol)))
6496 ((= dcst ?t)
6497 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6498 (re-search-forward org-ts-regexp-both
6499 (point-at-eol) t))
6500 (org-time-string-to-seconds (match-string 0))
6501 (time-to-seconds now)))
6502 ((= dcst ?f)
6503 (if getkey-func
6504 (progn
6505 (setq tmp (funcall getkey-func))
6506 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6507 tmp)
6508 (error "Invalid key function `%s'" getkey-func)))
6509 (t (error "Invalid sorting type `%c'" sorting-type)))))
6510 (lambda nil
6511 (cond
6512 ((= dcst ?n)
6513 (if (looking-at org-complex-heading-regexp)
6514 (string-to-number (match-string 4))
6515 nil))
6516 ((= dcst ?a)
6517 (if (looking-at org-complex-heading-regexp)
6518 (funcall case-func (match-string 4))
6519 nil))
6520 ((= dcst ?t)
6521 (let ((end (save-excursion (outline-next-heading) (point))))
6522 (if (or (re-search-forward org-ts-regexp end t)
6523 (re-search-forward org-ts-regexp-both end t))
6524 (org-time-string-to-seconds (match-string 0))
6525 (time-to-seconds now))))
6526 ((= dcst ?c)
6527 (let ((end (save-excursion (outline-next-heading) (point))))
6528 (if (re-search-forward
6529 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6530 end t)
6531 (org-time-string-to-seconds (match-string 0))
6532 (time-to-seconds now))))
6533 ((= dcst ?s)
6534 (let ((end (save-excursion (outline-next-heading) (point))))
6535 (if (re-search-forward org-scheduled-time-regexp end t)
6536 (org-time-string-to-seconds (match-string 1))
6537 (time-to-seconds now))))
6538 ((= dcst ?d)
6539 (let ((end (save-excursion (outline-next-heading) (point))))
6540 (if (re-search-forward org-deadline-time-regexp end t)
6541 (org-time-string-to-seconds (match-string 1))
6542 (time-to-seconds now))))
6543 ((= dcst ?p)
6544 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6545 (string-to-char (match-string 2))
6546 org-default-priority))
6547 ((= dcst ?r)
6548 (or (org-entry-get nil property) ""))
6549 ((= dcst ?o)
6550 (if (looking-at org-complex-heading-regexp)
6551 (- 9999 (length (member (match-string 2)
6552 org-todo-keywords-1)))))
6553 ((= dcst ?f)
6554 (if getkey-func
6555 (progn
6556 (setq tmp (funcall getkey-func))
6557 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6558 tmp)
6559 (error "Invalid key function `%s'" getkey-func)))
6560 (t (error "Invalid sorting type `%c'" sorting-type)))))
6562 (cond
6563 ((= dcst ?a) 'string<)
6564 ((= dcst ?f) compare-func)
6565 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6566 (t nil)))))
6567 (run-hooks 'org-after-sorting-entries-or-items-hook)
6568 (message "Sorting entries...done")))
6570 (defun org-do-sort (table what &optional with-case sorting-type)
6571 "Sort TABLE of WHAT according to SORTING-TYPE.
6572 The user will be prompted for the SORTING-TYPE if the call to this
6573 function does not specify it. WHAT is only for the prompt, to indicate
6574 what is being sorted. The sorting key will be extracted from
6575 the car of the elements of the table.
6576 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6577 (unless sorting-type
6578 (message
6579 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6580 what)
6581 (setq sorting-type (read-char-exclusive)))
6582 (let ((dcst (downcase sorting-type))
6583 extractfun comparefun)
6584 ;; Define the appropriate functions
6585 (cond
6586 ((= dcst ?n)
6587 (setq extractfun 'string-to-number
6588 comparefun (if (= dcst sorting-type) '< '>)))
6589 ((= dcst ?a)
6590 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6591 (lambda(x) (downcase (org-sort-remove-invisible x))))
6592 comparefun (if (= dcst sorting-type)
6593 'string<
6594 (lambda (a b) (and (not (string< a b))
6595 (not (string= a b)))))))
6596 ((= dcst ?t)
6597 (setq extractfun
6598 (lambda (x)
6599 (if (or (string-match org-ts-regexp x)
6600 (string-match org-ts-regexp-both x))
6601 (time-to-seconds
6602 (org-time-string-to-time (match-string 0 x)))
6604 comparefun (if (= dcst sorting-type) '< '>)))
6605 (t (error "Invalid sorting type `%c'" sorting-type)))
6607 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6608 table)
6609 (lambda (a b) (funcall comparefun (car a) (car b))))))
6612 ;;; The orgstruct minor mode
6614 ;; Define a minor mode which can be used in other modes in order to
6615 ;; integrate the org-mode structure editing commands.
6617 ;; This is really a hack, because the org-mode structure commands use
6618 ;; keys which normally belong to the major mode. Here is how it
6619 ;; works: The minor mode defines all the keys necessary to operate the
6620 ;; structure commands, but wraps the commands into a function which
6621 ;; tests if the cursor is currently at a headline or a plain list
6622 ;; item. If that is the case, the structure command is used,
6623 ;; temporarily setting many Org-mode variables like regular
6624 ;; expressions for filling etc. However, when any of those keys is
6625 ;; used at a different location, function uses `key-binding' to look
6626 ;; up if the key has an associated command in another currently active
6627 ;; keymap (minor modes, major mode, global), and executes that
6628 ;; command. There might be problems if any of the keys is otherwise
6629 ;; used as a prefix key.
6631 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6632 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6633 ;; addresses this by checking explicitly for both bindings.
6635 (defvar orgstruct-mode-map (make-sparse-keymap)
6636 "Keymap for the minor `orgstruct-mode'.")
6638 (defvar org-local-vars nil
6639 "List of local variables, for use by `orgstruct-mode'")
6641 ;;;###autoload
6642 (define-minor-mode orgstruct-mode
6643 "Toggle the minor more `orgstruct-mode'.
6644 This mode is for using Org-mode structure commands in other modes.
6645 The following key behave as if Org-mode was active, if the cursor
6646 is on a headline, or on a plain list item (both in the definition
6647 of Org-mode).
6649 M-up Move entry/item up
6650 M-down Move entry/item down
6651 M-left Promote
6652 M-right Demote
6653 M-S-up Move entry/item up
6654 M-S-down Move entry/item down
6655 M-S-left Promote subtree
6656 M-S-right Demote subtree
6657 M-q Fill paragraph and items like in Org-mode
6658 C-c ^ Sort entries
6659 C-c - Cycle list bullet
6660 TAB Cycle item visibility
6661 M-RET Insert new heading/item
6662 S-M-RET Insert new TODO heading / Checkbox item
6663 C-c C-c Set tags / toggle checkbox"
6664 nil " OrgStruct" nil
6665 (org-load-modules-maybe)
6666 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6668 ;;;###autoload
6669 (defun turn-on-orgstruct ()
6670 "Unconditionally turn on `orgstruct-mode'."
6671 (orgstruct-mode 1))
6673 (defun orgstruct++-mode (&optional arg)
6674 "Toggle `orgstruct-mode', the enhanced version of it.
6675 In addition to setting orgstruct-mode, this also exports all indentation and
6676 autofilling variables from org-mode into the buffer. It will also
6677 recognize item context in multiline items.
6678 Note that turning off orgstruct-mode will *not* remove the
6679 indentation/paragraph settings. This can only be done by refreshing the
6680 major mode, for example with \[normal-mode]."
6681 (interactive "P")
6682 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6683 (if (< arg 1)
6684 (orgstruct-mode -1)
6685 (orgstruct-mode 1)
6686 (let (var val)
6687 (mapc
6688 (lambda (x)
6689 (when (string-match
6690 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6691 (symbol-name (car x)))
6692 (setq var (car x) val (nth 1 x))
6693 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6694 org-local-vars)
6695 (org-set-local 'orgstruct-is-++ t))))
6697 (defvar orgstruct-is-++ nil
6698 "Is orgstruct-mode in ++ version in the current-buffer?")
6699 (make-variable-buffer-local 'orgstruct-is-++)
6701 ;;;###autoload
6702 (defun turn-on-orgstruct++ ()
6703 "Unconditionally turn on `orgstruct++-mode'."
6704 (orgstruct++-mode 1))
6706 (defun orgstruct-error ()
6707 "Error when there is no default binding for a structure key."
6708 (interactive)
6709 (error "This key has no function outside structure elements"))
6711 (defun orgstruct-setup ()
6712 "Setup orgstruct keymaps."
6713 (let ((nfunc 0)
6714 (bindings
6715 (list
6716 '([(meta up)] org-metaup)
6717 '([(meta down)] org-metadown)
6718 '([(meta left)] org-metaleft)
6719 '([(meta right)] org-metaright)
6720 '([(meta shift up)] org-shiftmetaup)
6721 '([(meta shift down)] org-shiftmetadown)
6722 '([(meta shift left)] org-shiftmetaleft)
6723 '([(meta shift right)] org-shiftmetaright)
6724 '([?\e (up)] org-metaup)
6725 '([?\e (down)] org-metadown)
6726 '([?\e (left)] org-metaleft)
6727 '([?\e (right)] org-metaright)
6728 '([?\e (shift up)] org-shiftmetaup)
6729 '([?\e (shift down)] org-shiftmetadown)
6730 '([?\e (shift left)] org-shiftmetaleft)
6731 '([?\e (shift right)] org-shiftmetaright)
6732 '([(shift up)] org-shiftup)
6733 '([(shift down)] org-shiftdown)
6734 '([(shift left)] org-shiftleft)
6735 '([(shift right)] org-shiftright)
6736 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6737 '("\M-q" fill-paragraph)
6738 '("\C-c^" org-sort)
6739 '("\C-c-" org-cycle-list-bullet)))
6740 elt key fun cmd)
6741 (while (setq elt (pop bindings))
6742 (setq nfunc (1+ nfunc))
6743 (setq key (org-key (car elt))
6744 fun (nth 1 elt)
6745 cmd (orgstruct-make-binding fun nfunc key))
6746 (org-defkey orgstruct-mode-map key cmd))
6748 ;; Special treatment needed for TAB and RET
6749 (org-defkey orgstruct-mode-map [(tab)]
6750 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6751 (org-defkey orgstruct-mode-map "\C-i"
6752 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6754 (org-defkey orgstruct-mode-map "\M-\C-m"
6755 (orgstruct-make-binding 'org-insert-heading 105
6756 "\M-\C-m" [(meta return)]))
6757 (org-defkey orgstruct-mode-map [(meta return)]
6758 (orgstruct-make-binding 'org-insert-heading 106
6759 [(meta return)] "\M-\C-m"))
6761 (org-defkey orgstruct-mode-map [(shift meta return)]
6762 (orgstruct-make-binding 'org-insert-todo-heading 107
6763 [(meta return)] "\M-\C-m"))
6765 (org-defkey orgstruct-mode-map "\e\C-m"
6766 (orgstruct-make-binding 'org-insert-heading 108
6767 "\e\C-m" [?\e (return)]))
6768 (org-defkey orgstruct-mode-map [?\e (return)]
6769 (orgstruct-make-binding 'org-insert-heading 109
6770 [?\e (return)] "\e\C-m"))
6771 (org-defkey orgstruct-mode-map [?\e (shift return)]
6772 (orgstruct-make-binding 'org-insert-todo-heading 110
6773 [?\e (return)] "\e\C-m"))
6775 (unless org-local-vars
6776 (setq org-local-vars (org-get-local-variables)))
6780 (defun orgstruct-make-binding (fun n &rest keys)
6781 "Create a function for binding in the structure minor mode.
6782 FUN is the command to call inside a table. N is used to create a unique
6783 command name. KEYS are keys that should be checked in for a command
6784 to execute outside of tables."
6785 (eval
6786 (list 'defun
6787 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6788 '(arg)
6789 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6790 "Outside of structure, run the binding of `"
6791 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6792 "'.")
6793 '(interactive "p")
6794 (list 'if
6795 `(org-context-p 'headline 'item
6796 (and orgstruct-is-++
6797 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6798 'item-body))
6799 (list 'org-run-like-in-org-mode (list 'quote fun))
6800 (list 'let '(orgstruct-mode)
6801 (list 'call-interactively
6802 (append '(or)
6803 (mapcar (lambda (k)
6804 (list 'key-binding k))
6805 keys)
6806 '('orgstruct-error))))))))
6808 (defun org-context-p (&rest contexts)
6809 "Check if local context is any of CONTEXTS.
6810 Possible values in the list of contexts are `table', `headline', and `item'."
6811 (let ((pos (point)))
6812 (goto-char (point-at-bol))
6813 (prog1 (or (and (memq 'table contexts)
6814 (looking-at "[ \t]*|"))
6815 (and (memq 'headline contexts)
6816 ;;????????? (looking-at "\\*+"))
6817 (looking-at outline-regexp))
6818 (and (memq 'item contexts)
6819 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6820 (and (memq 'item-body contexts)
6821 (org-in-item-p)))
6822 (goto-char pos))))
6824 (defun org-get-local-variables ()
6825 "Return a list of all local variables in an org-mode buffer."
6826 (let (varlist)
6827 (with-current-buffer (get-buffer-create "*Org tmp*")
6828 (erase-buffer)
6829 (org-mode)
6830 (setq varlist (buffer-local-variables)))
6831 (kill-buffer "*Org tmp*")
6832 (delq nil
6833 (mapcar
6834 (lambda (x)
6835 (setq x
6836 (if (symbolp x)
6837 (list x)
6838 (list (car x) (list 'quote (cdr x)))))
6839 (if (string-match
6840 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6841 (symbol-name (car x)))
6842 x nil))
6843 varlist))))
6845 ;;;###autoload
6846 (defun org-run-like-in-org-mode (cmd)
6847 "Run a command, pretending that the current buffer is in Org-mode.
6848 This will temporarily bind local variables that are typically bound in
6849 Org-mode to the values they have in Org-mode, and then interactively
6850 call CMD."
6851 (org-load-modules-maybe)
6852 (unless org-local-vars
6853 (setq org-local-vars (org-get-local-variables)))
6854 (eval (list 'let org-local-vars
6855 (list 'call-interactively (list 'quote cmd)))))
6857 ;;;; Archiving
6859 (defun org-get-category (&optional pos)
6860 "Get the category applying to position POS."
6861 (get-text-property (or pos (point)) 'org-category))
6863 (defun org-refresh-category-properties ()
6864 "Refresh category text properties in the buffer."
6865 (let ((def-cat (cond
6866 ((null org-category)
6867 (if buffer-file-name
6868 (file-name-sans-extension
6869 (file-name-nondirectory buffer-file-name))
6870 "???"))
6871 ((symbolp org-category) (symbol-name org-category))
6872 (t org-category)))
6873 beg end cat pos optionp)
6874 (org-unmodified
6875 (save-excursion
6876 (save-restriction
6877 (widen)
6878 (goto-char (point-min))
6879 (put-text-property (point) (point-max) 'org-category def-cat)
6880 (while (re-search-forward
6881 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6882 (setq pos (match-end 0)
6883 optionp (equal (char-after (match-beginning 0)) ?#)
6884 cat (org-trim (match-string 2)))
6885 (if optionp
6886 (setq beg (point-at-bol) end (point-max))
6887 (org-back-to-heading t)
6888 (setq beg (point) end (org-end-of-subtree t t)))
6889 (put-text-property beg end 'org-category cat)
6890 (goto-char pos)))))))
6893 ;;;; Link Stuff
6895 ;;; Link abbreviations
6897 (defun org-link-expand-abbrev (link)
6898 "Apply replacements as defined in `org-link-abbrev-alist."
6899 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6900 (let* ((key (match-string 1 link))
6901 (as (or (assoc key org-link-abbrev-alist-local)
6902 (assoc key org-link-abbrev-alist)))
6903 (tag (and (match-end 2) (match-string 3 link)))
6904 rpl)
6905 (if (not as)
6906 link
6907 (setq rpl (cdr as))
6908 (cond
6909 ((symbolp rpl) (funcall rpl tag))
6910 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6911 ((string-match "%h" rpl)
6912 (replace-match (url-hexify-string (or tag "")) t t rpl))
6913 (t (concat rpl tag)))))
6914 link))
6916 ;;; Storing and inserting links
6918 (defvar org-insert-link-history nil
6919 "Minibuffer history for links inserted with `org-insert-link'.")
6921 (defvar org-stored-links nil
6922 "Contains the links stored with `org-store-link'.")
6924 (defvar org-store-link-plist nil
6925 "Plist with info about the most recently link created with `org-store-link'.")
6927 (defvar org-link-protocols nil
6928 "Link protocols added to Org-mode using `org-add-link-type'.")
6930 (defvar org-store-link-functions nil
6931 "List of functions that are called to create and store a link.
6932 Each function will be called in turn until one returns a non-nil
6933 value. Each function should check if it is responsible for creating
6934 this link (for example by looking at the major mode).
6935 If not, it must exit and return nil.
6936 If yes, it should return a non-nil value after a calling
6937 `org-store-link-props' with a list of properties and values.
6938 Special properties are:
6940 :type The link prefix. like \"http\". This must be given.
6941 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6942 This is obligatory as well.
6943 :description Optional default description for the second pair
6944 of brackets in an Org-mode link. The user can still change
6945 this when inserting this link into an Org-mode buffer.
6947 In addition to these, any additional properties can be specified
6948 and then used in remember templates.")
6950 (defun org-add-link-type (type &optional follow export)
6951 "Add TYPE to the list of `org-link-types'.
6952 Re-compute all regular expressions depending on `org-link-types'
6954 FOLLOW and EXPORT are two functions.
6956 FOLLOW should take the link path as the single argument and do whatever
6957 is necessary to follow the link, for example find a file or display
6958 a mail message.
6960 EXPORT should format the link path for export to one of the export formats.
6961 It should be a function accepting three arguments:
6963 path the path of the link, the text after the prefix (like \"http:\")
6964 desc the description of the link, if any, nil if there was no description
6965 format the export format, a symbol like `html' or `latex'.
6967 The function may use the FORMAT information to return different values
6968 depending on the format. The return value will be put literally into
6969 the exported file.
6970 Org-mode has a built-in default for exporting links. If you are happy with
6971 this default, there is no need to define an export function for the link
6972 type. For a simple example of an export function, see `org-bbdb.el'."
6973 (add-to-list 'org-link-types type t)
6974 (org-make-link-regexps)
6975 (if (assoc type org-link-protocols)
6976 (setcdr (assoc type org-link-protocols) (list follow export))
6977 (push (list type follow export) org-link-protocols)))
6979 ;;;###autoload
6980 (defun org-store-link (arg)
6981 "\\<org-mode-map>Store an org-link to the current location.
6982 This link is added to `org-stored-links' and can later be inserted
6983 into an org-buffer with \\[org-insert-link].
6985 For some link types, a prefix arg is interpreted:
6986 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6987 For file links, arg negates `org-context-in-file-links'."
6988 (interactive "P")
6989 (org-load-modules-maybe)
6990 (setq org-store-link-plist nil) ; reset
6991 (let ((outline-regexp (org-get-limited-outline-regexp))
6992 link cpltxt desc description search txt custom-id)
6993 (cond
6995 ((run-hook-with-args-until-success 'org-store-link-functions)
6996 (setq link (plist-get org-store-link-plist :link)
6997 desc (or (plist-get org-store-link-plist :description) link)))
6999 ((equal (buffer-name) "*Org Edit Src Example*")
7000 (let (label gc)
7001 (while (or (not label)
7002 (save-excursion
7003 (save-restriction
7004 (widen)
7005 (goto-char (point-min))
7006 (re-search-forward
7007 (regexp-quote (format org-coderef-label-format label))
7008 nil t))))
7009 (when label (message "Label exists already") (sit-for 2))
7010 (setq label (read-string "Code line label: " label)))
7011 (end-of-line 1)
7012 (setq link (format org-coderef-label-format label))
7013 (setq gc (- 79 (length link)))
7014 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7015 (insert link)
7016 (setq link (concat "(" label ")") desc nil)))
7018 ((eq major-mode 'calendar-mode)
7019 (let ((cd (calendar-cursor-to-date)))
7020 (setq link
7021 (format-time-string
7022 (car org-time-stamp-formats)
7023 (apply 'encode-time
7024 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7025 nil nil nil))))
7026 (org-store-link-props :type "calendar" :date cd)))
7028 ((eq major-mode 'w3-mode)
7029 (setq cpltxt (if (and (buffer-name)
7030 (not (string-match "Untitled" (buffer-name))))
7031 (buffer-name)
7032 (url-view-url t))
7033 link (org-make-link (url-view-url t)))
7034 (org-store-link-props :type "w3" :url (url-view-url t)))
7036 ((eq major-mode 'w3m-mode)
7037 (setq cpltxt (or w3m-current-title w3m-current-url)
7038 link (org-make-link w3m-current-url))
7039 (org-store-link-props :type "w3m" :url (url-view-url t)))
7041 ((setq search (run-hook-with-args-until-success
7042 'org-create-file-search-functions))
7043 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7044 "::" search))
7045 (setq cpltxt (or description link)))
7047 ((eq major-mode 'image-mode)
7048 (setq cpltxt (concat "file:"
7049 (abbreviate-file-name buffer-file-name))
7050 link (org-make-link cpltxt))
7051 (org-store-link-props :type "image" :file buffer-file-name))
7053 ((eq major-mode 'dired-mode)
7054 ;; link to the file in the current line
7055 (setq cpltxt (concat "file:"
7056 (abbreviate-file-name
7057 (expand-file-name
7058 (dired-get-filename nil t))))
7059 link (org-make-link cpltxt)))
7061 ((and buffer-file-name (org-mode-p))
7062 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7063 (cond
7064 ((org-in-regexp "<<\\(.*?\\)>>")
7065 (setq cpltxt
7066 (concat "file:"
7067 (abbreviate-file-name buffer-file-name)
7068 "::" (match-string 1))
7069 link (org-make-link cpltxt)))
7070 ((and (featurep 'org-id)
7071 (or (eq org-link-to-org-use-id t)
7072 (and (eq org-link-to-org-use-id 'create-if-interactive)
7073 (interactive-p))
7074 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7075 (interactive-p)
7076 (not custom-id))
7077 (and org-link-to-org-use-id
7078 (condition-case nil
7079 (org-entry-get nil "ID")
7080 (error nil)))))
7081 ;; We can make a link using the ID.
7082 (setq link (condition-case nil
7083 (prog1 (org-id-store-link)
7084 (setq desc (plist-get org-store-link-plist
7085 :description)))
7086 (error
7087 ;; probably before first headline, link to file only
7088 (concat "file:"
7089 (abbreviate-file-name buffer-file-name))))))
7091 ;; Just link to current headline
7092 (setq cpltxt (concat "file:"
7093 (abbreviate-file-name buffer-file-name)))
7094 ;; Add a context search string
7095 (when (org-xor org-context-in-file-links arg)
7096 (setq txt (cond
7097 ((org-on-heading-p) nil)
7098 ((org-region-active-p)
7099 (buffer-substring (region-beginning) (region-end)))
7100 (t nil)))
7101 (when (or (null txt) (string-match "\\S-" txt))
7102 (setq cpltxt
7103 (concat cpltxt "::"
7104 (condition-case nil
7105 (org-make-org-heading-search-string txt)
7106 (error "")))
7107 desc (or (nth 4 (org-heading-components)) "NONE"))))
7108 (if (string-match "::\\'" cpltxt)
7109 (setq cpltxt (substring cpltxt 0 -2)))
7110 (setq link (org-make-link cpltxt)))))
7112 ((buffer-file-name (buffer-base-buffer))
7113 ;; Just link to this file here.
7114 (setq cpltxt (concat "file:"
7115 (abbreviate-file-name
7116 (buffer-file-name (buffer-base-buffer)))))
7117 ;; Add a context string
7118 (when (org-xor org-context-in-file-links arg)
7119 (setq txt (if (org-region-active-p)
7120 (buffer-substring (region-beginning) (region-end))
7121 (buffer-substring (point-at-bol) (point-at-eol))))
7122 ;; Only use search option if there is some text.
7123 (when (string-match "\\S-" txt)
7124 (setq cpltxt
7125 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7126 desc "NONE")))
7127 (setq link (org-make-link cpltxt)))
7129 ((interactive-p)
7130 (error "Cannot link to a buffer which is not visiting a file"))
7132 (t (setq link nil)))
7134 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7135 (setq link (or link cpltxt)
7136 desc (or desc cpltxt))
7137 (if (equal desc "NONE") (setq desc nil))
7139 (if (and (or (interactive-p) executing-kbd-macro) link)
7140 (progn
7141 (setq org-stored-links
7142 (cons (list link desc) org-stored-links))
7143 (message "Stored: %s" (or desc link))
7144 (when custom-id
7145 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7146 "::#" custom-id))
7147 (setq org-stored-links
7148 (cons (list link desc) org-stored-links))))
7149 (and link (org-make-link-string link desc)))))
7151 (defun org-store-link-props (&rest plist)
7152 "Store link properties, extract names and addresses."
7153 (let (x adr)
7154 (when (setq x (plist-get plist :from))
7155 (setq adr (mail-extract-address-components x))
7156 (setq plist (plist-put plist :fromname (car adr)))
7157 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7158 (when (setq x (plist-get plist :to))
7159 (setq adr (mail-extract-address-components x))
7160 (setq plist (plist-put plist :toname (car adr)))
7161 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7162 (let ((from (plist-get plist :from))
7163 (to (plist-get plist :to)))
7164 (when (and from to org-from-is-user-regexp)
7165 (setq plist
7166 (plist-put plist :fromto
7167 (if (string-match org-from-is-user-regexp from)
7168 (concat "to %t")
7169 (concat "from %f"))))))
7170 (setq org-store-link-plist plist))
7172 (defun org-add-link-props (&rest plist)
7173 "Add these properties to the link property list."
7174 (let (key value)
7175 (while plist
7176 (setq key (pop plist) value (pop plist))
7177 (setq org-store-link-plist
7178 (plist-put org-store-link-plist key value)))))
7180 (defun org-email-link-description (&optional fmt)
7181 "Return the description part of an email link.
7182 This takes information from `org-store-link-plist' and formats it
7183 according to FMT (default from `org-email-link-description-format')."
7184 (setq fmt (or fmt org-email-link-description-format))
7185 (let* ((p org-store-link-plist)
7186 (to (plist-get p :toaddress))
7187 (from (plist-get p :fromaddress))
7188 (table
7189 (list
7190 (cons "%c" (plist-get p :fromto))
7191 (cons "%F" (plist-get p :from))
7192 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7193 (cons "%T" (plist-get p :to))
7194 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7195 (cons "%s" (plist-get p :subject))
7196 (cons "%m" (plist-get p :message-id)))))
7197 (when (string-match "%c" fmt)
7198 ;; Check if the user wrote this message
7199 (if (and org-from-is-user-regexp from to
7200 (save-match-data (string-match org-from-is-user-regexp from)))
7201 (setq fmt (replace-match "to %t" t t fmt))
7202 (setq fmt (replace-match "from %f" t t fmt))))
7203 (org-replace-escapes fmt table)))
7205 (defun org-make-org-heading-search-string (&optional string heading)
7206 "Make search string for STRING or current headline."
7207 (interactive)
7208 (let ((s (or string (org-get-heading))))
7209 (unless (and string (not heading))
7210 ;; We are using a headline, clean up garbage in there.
7211 (if (string-match org-todo-regexp s)
7212 (setq s (replace-match "" t t s)))
7213 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7214 (setq s (replace-match "" t t s)))
7215 (setq s (org-trim s))
7216 (if (string-match (concat "^\\(" org-quote-string "\\|"
7217 org-comment-string "\\)") s)
7218 (setq s (replace-match "" t t s)))
7219 (while (string-match org-ts-regexp s)
7220 (setq s (replace-match "" t t s))))
7221 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7222 (setq s (replace-match " " t t s)))
7223 (or string (setq s (concat "*" s))) ; Add * for headlines
7224 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7226 (defun org-make-link (&rest strings)
7227 "Concatenate STRINGS."
7228 (apply 'concat strings))
7230 (defun org-make-link-string (link &optional description)
7231 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7232 (unless (string-match "\\S-" link)
7233 (error "Empty link"))
7234 (when (stringp description)
7235 ;; Remove brackets from the description, they are fatal.
7236 (while (string-match "\\[" description)
7237 (setq description (replace-match "{" t t description)))
7238 (while (string-match "\\]" description)
7239 (setq description (replace-match "}" t t description))))
7240 (when (equal (org-link-escape link) description)
7241 ;; No description needed, it is identical
7242 (setq description nil))
7243 (when (and (not description)
7244 (not (equal link (org-link-escape link))))
7245 (setq description (org-extract-attributes link)))
7246 (concat "[[" (org-link-escape link) "]"
7247 (if description (concat "[" description "]") "")
7248 "]"))
7250 (defconst org-link-escape-chars
7251 '((?\ . "%20")
7252 (?\[ . "%5B")
7253 (?\] . "%5D")
7254 (?\340 . "%E0") ; `a
7255 (?\342 . "%E2") ; ^a
7256 (?\347 . "%E7") ; ,c
7257 (?\350 . "%E8") ; `e
7258 (?\351 . "%E9") ; 'e
7259 (?\352 . "%EA") ; ^e
7260 (?\356 . "%EE") ; ^i
7261 (?\364 . "%F4") ; ^o
7262 (?\371 . "%F9") ; `u
7263 (?\373 . "%FB") ; ^u
7264 (?\; . "%3B")
7265 (?? . "%3F")
7266 (?= . "%3D")
7267 (?+ . "%2B")
7269 "Association list of escapes for some characters problematic in links.
7270 This is the list that is used for internal purposes.")
7272 (defvar org-url-encoding-use-url-hexify nil)
7274 (defconst org-link-escape-chars-browser
7275 '((?\ . "%20")) ; 32 for the SPC char
7276 "Association list of escapes for some characters problematic in links.
7277 This is the list that is used before handing over to the browser.")
7279 (defun org-link-escape (text &optional table)
7280 "Escape characters in TEXT that are problematic for links."
7281 (if org-url-encoding-use-url-hexify
7282 (url-hexify-string text)
7283 (setq table (or table org-link-escape-chars))
7284 (when text
7285 (let ((re (mapconcat (lambda (x) (regexp-quote
7286 (char-to-string (car x))))
7287 table "\\|")))
7288 (while (string-match re text)
7289 (setq text
7290 (replace-match
7291 (cdr (assoc (string-to-char (match-string 0 text))
7292 table))
7293 t t text)))
7294 text))))
7296 (defun org-link-unescape (text &optional table)
7297 "Reverse the action of `org-link-escape'."
7298 (if org-url-encoding-use-url-hexify
7299 (url-unhex-string text)
7300 (setq table (or table org-link-escape-chars))
7301 (when text
7302 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7303 table "\\|")))
7304 (while (string-match re text)
7305 (setq text
7306 (replace-match
7307 (char-to-string (car (rassoc (match-string 0 text) table)))
7308 t t text)))
7309 text))))
7311 (defun org-xor (a b)
7312 "Exclusive or."
7313 (if a (not b) b))
7315 (defun org-fixup-message-id-for-http (s)
7316 "Replace special characters in a message id, so it can be used in an http query."
7317 (while (string-match "<" s)
7318 (setq s (replace-match "%3C" t t s)))
7319 (while (string-match ">" s)
7320 (setq s (replace-match "%3E" t t s)))
7321 (while (string-match "@" s)
7322 (setq s (replace-match "%40" t t s)))
7325 ;;;###autoload
7326 (defun org-insert-link-global ()
7327 "Insert a link like Org-mode does.
7328 This command can be called in any mode to insert a link in Org-mode syntax."
7329 (interactive)
7330 (org-load-modules-maybe)
7331 (org-run-like-in-org-mode 'org-insert-link))
7333 (defun org-insert-link (&optional complete-file link-location)
7334 "Insert a link. At the prompt, enter the link.
7336 Completion can be used to insert any of the link protocol prefixes like
7337 http or ftp in use.
7339 The history can be used to select a link previously stored with
7340 `org-store-link'. When the empty string is entered (i.e. if you just
7341 press RET at the prompt), the link defaults to the most recently
7342 stored link. As SPC triggers completion in the minibuffer, you need to
7343 use M-SPC or C-q SPC to force the insertion of a space character.
7345 You will also be prompted for a description, and if one is given, it will
7346 be displayed in the buffer instead of the link.
7348 If there is already a link at point, this command will allow you to edit link
7349 and description parts.
7351 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7352 be selected using completion. The path to the file will be relative to the
7353 current directory if the file is in the current directory or a subdirectory.
7354 Otherwise, the link will be the absolute path as completed in the minibuffer
7355 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7356 option `org-link-file-path-type'.
7358 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7359 the current directory or below.
7361 With three \\[universal-argument] prefixes, negate the meaning of
7362 `org-keep-stored-link-after-insertion'.
7364 If `org-make-link-description-function' is non-nil, this function will be
7365 called with the link target, and the result will be the default
7366 link description.
7368 If the LINK-LOCATION parameter is non-nil, this value will be
7369 used as the link location instead of reading one interactively."
7370 (interactive "P")
7371 (let* ((wcf (current-window-configuration))
7372 (region (if (org-region-active-p)
7373 (buffer-substring (region-beginning) (region-end))))
7374 (remove (and region (list (region-beginning) (region-end))))
7375 (desc region)
7376 tmphist ; byte-compile incorrectly complains about this
7377 (link link-location)
7378 entry file all-prefixes)
7379 (cond
7380 (link-location) ; specified by arg, just use it.
7381 ((org-in-regexp org-bracket-link-regexp 1)
7382 ;; We do have a link at point, and we are going to edit it.
7383 (setq remove (list (match-beginning 0) (match-end 0)))
7384 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7385 (setq link (read-string "Link: "
7386 (org-link-unescape
7387 (org-match-string-no-properties 1)))))
7388 ((or (org-in-regexp org-angle-link-re)
7389 (org-in-regexp org-plain-link-re))
7390 ;; Convert to bracket link
7391 (setq remove (list (match-beginning 0) (match-end 0))
7392 link (read-string "Link: "
7393 (org-remove-angle-brackets (match-string 0)))))
7394 ((member complete-file '((4) (16)))
7395 ;; Completing read for file names.
7396 (setq link (org-file-complete-link complete-file)))
7398 ;; Read link, with completion for stored links.
7399 (with-output-to-temp-buffer "*Org Links*"
7400 (princ "Insert a link.
7401 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7402 (when org-stored-links
7403 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7404 (princ (mapconcat
7405 (lambda (x)
7406 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7407 (reverse org-stored-links) "\n"))))
7408 (let ((cw (selected-window)))
7409 (select-window (get-buffer-window "*Org Links*"))
7410 (setq truncate-lines t)
7411 (unless (pos-visible-in-window-p (point-max))
7412 (org-fit-window-to-buffer))
7413 (and (window-live-p cw) (select-window cw)))
7414 ;; Fake a link history, containing the stored links.
7415 (setq tmphist (append (mapcar 'car org-stored-links)
7416 org-insert-link-history))
7417 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7418 (mapcar 'car org-link-abbrev-alist)
7419 org-link-types))
7420 (unwind-protect
7421 (progn
7422 (setq link
7423 (let ((org-completion-use-ido nil))
7424 (org-completing-read
7425 "Link: "
7426 (mapcar (lambda (x) (list (concat x ":")))
7427 all-prefixes)
7428 nil nil nil
7429 'tmphist
7430 (or (car (car org-stored-links))))))
7431 (if (or (member link all-prefixes)
7432 (and (equal ":" (substring link -1))
7433 (member (substring link 0 -1) all-prefixes)
7434 (setq link (substring link 0 -1))))
7435 (setq link (org-link-try-special-completion link))))
7436 (set-window-configuration wcf)
7437 (kill-buffer "*Org Links*"))
7438 (setq entry (assoc link org-stored-links))
7439 (or entry (push link org-insert-link-history))
7440 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7441 (not org-keep-stored-link-after-insertion))
7442 (setq org-stored-links (delq (assoc link org-stored-links)
7443 org-stored-links)))
7444 (setq desc (or desc (nth 1 entry)))))
7446 (if (string-match org-plain-link-re link)
7447 ;; URL-like link, normalize the use of angular brackets.
7448 (setq link (org-make-link (org-remove-angle-brackets link))))
7450 ;; Check if we are linking to the current file with a search option
7451 ;; If yes, simplify the link by using only the search option.
7452 (when (and buffer-file-name
7453 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7454 (let* ((path (match-string 1 link))
7455 (case-fold-search nil)
7456 (search (match-string 2 link)))
7457 (save-match-data
7458 (if (equal (file-truename buffer-file-name) (file-truename path))
7459 ;; We are linking to this same file, with a search option
7460 (setq link search)))))
7462 ;; Check if we can/should use a relative path. If yes, simplify the link
7463 (when (string-match "^file:\\(.*\\)" link)
7464 (let* ((path (match-string 1 link))
7465 (origpath path)
7466 (case-fold-search nil))
7467 (cond
7468 ((or (eq org-link-file-path-type 'absolute)
7469 (equal complete-file '(16)))
7470 (setq path (abbreviate-file-name (expand-file-name path))))
7471 ((eq org-link-file-path-type 'noabbrev)
7472 (setq path (expand-file-name path)))
7473 ((eq org-link-file-path-type 'relative)
7474 (setq path (file-relative-name path)))
7476 (save-match-data
7477 (if (string-match (concat "^" (regexp-quote
7478 (file-name-as-directory
7479 (expand-file-name "."))))
7480 (expand-file-name path))
7481 ;; We are linking a file with relative path name.
7482 (setq path (substring (expand-file-name path)
7483 (match-end 0)))
7484 (setq path (abbreviate-file-name (expand-file-name path)))))))
7485 (setq link (concat "file:" path))
7486 (if (equal desc origpath)
7487 (setq desc path))))
7489 (if org-make-link-description-function
7490 (setq desc (funcall org-make-link-description-function link desc)))
7492 (setq desc (read-string "Description: " desc))
7493 (unless (string-match "\\S-" desc) (setq desc nil))
7494 (if remove (apply 'delete-region remove))
7495 (insert (org-make-link-string link desc))))
7497 (defun org-link-try-special-completion (type)
7498 "If there is completion support for link type TAPE, offer it."
7499 (let ((fun (intern (concat "org-" type "-complete-link"))))
7500 (if (functionp fun)
7501 (funcall fun)
7502 (read-string "Link (no completion support): " (concat type ":")))))
7504 (defun org-file-complete-link (&optional arg)
7505 "Create a file link using completion."
7506 (let (file link)
7507 (setq file (read-file-name "File: "))
7508 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7509 (pwd1 (file-name-as-directory (abbreviate-file-name
7510 (expand-file-name ".")))))
7511 (cond
7512 ((equal arg '(16))
7513 (setq link (org-make-link
7514 "file:"
7515 (abbreviate-file-name (expand-file-name file)))))
7516 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7517 (setq link (org-make-link "file:" (match-string 1 file))))
7518 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7519 (expand-file-name file))
7520 (setq link (org-make-link
7521 "file:" (match-string 1 (expand-file-name file)))))
7522 (t (setq link (org-make-link "file:" file)))))
7523 link))
7525 (defun org-completing-read (&rest args)
7526 "Completing-read with SPACE being a normal character."
7527 (let ((minibuffer-local-completion-map
7528 (copy-keymap minibuffer-local-completion-map)))
7529 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7530 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7531 (apply 'org-ido-completing-read args)))
7533 (defun org-completing-read-no-ido (&rest args)
7534 (let (org-completion-use-ido)
7535 (apply 'org-completing-read args)))
7537 (defun org-ido-completing-read (&rest args)
7538 "Completing-read using `ido-mode' speedups if available"
7539 (if (and org-completion-use-ido
7540 (fboundp 'ido-completing-read)
7541 (boundp 'ido-mode) ido-mode
7542 (listp (second args)))
7543 (let ((ido-enter-matching-directory nil))
7544 (apply 'ido-completing-read (concat (car args))
7545 (mapcar (lambda (x) (car x)) (nth 1 args))
7546 (cddr args)))
7547 (apply 'completing-read args)))
7549 (defun org-extract-attributes (s)
7550 "Extract the attributes cookie from a string and set as text property."
7551 (let (a attr (start 0) key value)
7552 (save-match-data
7553 (when (string-match "{{\\([^}]+\\)}}$" s)
7554 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7555 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7556 (setq key (match-string 1 a) value (match-string 2 a)
7557 start (match-end 0)
7558 attr (plist-put attr (intern key) value))))
7559 (org-add-props s nil 'org-attr attr))
7562 (defun org-extract-attributes-from-string (tag)
7563 (let (key value attr)
7564 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7565 (setq key (match-string 1 tag) value (match-string 2 tag)
7566 tag (replace-match "" t t tag)
7567 attr (plist-put attr (intern key) value)))
7568 (cons tag attr)))
7570 (defun org-attributes-to-string (plist)
7571 "Format a property list into an HTML attribute list."
7572 (let ((s "") key value)
7573 (while plist
7574 (setq key (pop plist) value (pop plist))
7575 (and value
7576 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7579 ;;; Opening/following a link
7581 (defvar org-link-search-failed nil)
7583 (defun org-next-link ()
7584 "Move forward to the next link.
7585 If the link is in hidden text, expose it."
7586 (interactive)
7587 (when (and org-link-search-failed (eq this-command last-command))
7588 (goto-char (point-min))
7589 (message "Link search wrapped back to beginning of buffer"))
7590 (setq org-link-search-failed nil)
7591 (let* ((pos (point))
7592 (ct (org-context))
7593 (a (assoc :link ct)))
7594 (if a (goto-char (nth 2 a)))
7595 (if (re-search-forward org-any-link-re nil t)
7596 (progn
7597 (goto-char (match-beginning 0))
7598 (if (org-invisible-p) (org-show-context)))
7599 (goto-char pos)
7600 (setq org-link-search-failed t)
7601 (error "No further link found"))))
7603 (defun org-previous-link ()
7604 "Move backward to the previous link.
7605 If the link is in hidden text, expose it."
7606 (interactive)
7607 (when (and org-link-search-failed (eq this-command last-command))
7608 (goto-char (point-max))
7609 (message "Link search wrapped back to end of buffer"))
7610 (setq org-link-search-failed nil)
7611 (let* ((pos (point))
7612 (ct (org-context))
7613 (a (assoc :link ct)))
7614 (if a (goto-char (nth 1 a)))
7615 (if (re-search-backward org-any-link-re nil t)
7616 (progn
7617 (goto-char (match-beginning 0))
7618 (if (org-invisible-p) (org-show-context)))
7619 (goto-char pos)
7620 (setq org-link-search-failed t)
7621 (error "No further link found"))))
7623 (defun org-translate-link (s)
7624 "Translate a link string if a translation function has been defined."
7625 (if (and org-link-translation-function
7626 (fboundp org-link-translation-function)
7627 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7628 (progn
7629 (setq s (funcall org-link-translation-function
7630 (match-string 1) (match-string 2)))
7631 (concat (car s) ":" (cdr s)))
7634 (defun org-translate-link-from-planner (type path)
7635 "Translate a link from Emacs Planner syntax so that Org can follow it.
7636 This is still an experimental function, your mileage may vary."
7637 (cond
7638 ((member type '("http" "https" "news" "ftp"))
7639 ;; standard Internet links are the same.
7640 nil)
7641 ((and (equal type "irc") (string-match "^//" path))
7642 ;; Planner has two / at the beginning of an irc link, we have 1.
7643 ;; We should have zero, actually....
7644 (setq path (substring path 1)))
7645 ((and (equal type "lisp") (string-match "^/" path))
7646 ;; Planner has a slash, we do not.
7647 (setq type "elisp" path (substring path 1)))
7648 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7649 ;; A typical message link. Planner has the id after the fina slash,
7650 ;; we separate it with a hash mark
7651 (setq path (concat (match-string 1 path) "#"
7652 (org-remove-angle-brackets (match-string 2 path)))))
7654 (cons type path))
7656 (defun org-find-file-at-mouse (ev)
7657 "Open file link or URL at mouse."
7658 (interactive "e")
7659 (mouse-set-point ev)
7660 (org-open-at-point 'in-emacs))
7662 (defun org-open-at-mouse (ev)
7663 "Open file link or URL at mouse."
7664 (interactive "e")
7665 (mouse-set-point ev)
7666 (if (eq major-mode 'org-agenda-mode)
7667 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7668 (org-open-at-point))
7670 (defvar org-window-config-before-follow-link nil
7671 "The window configuration before following a link.
7672 This is saved in case the need arises to restore it.")
7674 (defvar org-open-link-marker (make-marker)
7675 "Marker pointing to the location where `org-open-at-point; was called.")
7677 ;;;###autoload
7678 (defun org-open-at-point-global ()
7679 "Follow a link like Org-mode does.
7680 This command can be called in any mode to follow a link that has
7681 Org-mode syntax."
7682 (interactive)
7683 (org-run-like-in-org-mode 'org-open-at-point))
7685 ;;;###autoload
7686 (defun org-open-link-from-string (s &optional arg)
7687 "Open a link in the string S, as if it was in Org-mode."
7688 (interactive "sLink: \nP")
7689 (let ((reference-buffer (current-buffer)))
7690 (with-temp-buffer
7691 (let ((org-inhibit-startup t))
7692 (org-mode)
7693 (insert s)
7694 (goto-char (point-min))
7695 (org-open-at-point arg reference-buffer)))))
7697 (defun org-open-at-point (&optional in-emacs reference-buffer)
7698 "Open link at or after point.
7699 If there is no link at point, this function will search forward up to
7700 the end of the current line.
7701 Normally, files will be opened by an appropriate application. If the
7702 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7703 With a double prefix argument, try to open outside of Emacs, in the
7704 application the system uses for this file type."
7705 (interactive "P")
7706 (org-load-modules-maybe)
7707 (move-marker org-open-link-marker (point))
7708 (setq org-window-config-before-follow-link (current-window-configuration))
7709 (org-remove-occur-highlights nil nil t)
7710 (cond
7711 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7712 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7713 (org-footnote-action))
7715 (let (type path link line search (pos (point)))
7716 (catch 'match
7717 (save-excursion
7718 (skip-chars-forward "^]\n\r")
7719 (when (org-in-regexp org-bracket-link-regexp)
7720 (setq link (org-extract-attributes
7721 (org-link-unescape (org-match-string-no-properties 1))))
7722 (while (string-match " *\n *" link)
7723 (setq link (replace-match " " t t link)))
7724 (setq link (org-link-expand-abbrev link))
7725 (cond
7726 ((or (file-name-absolute-p link)
7727 (string-match "^\\.\\.?/" link))
7728 (setq type "file" path link))
7729 ((string-match org-link-re-with-space3 link)
7730 (setq type (match-string 1 link) path (match-string 2 link)))
7731 (t (setq type "thisfile" path link)))
7732 (throw 'match t)))
7734 (when (get-text-property (point) 'org-linked-text)
7735 (setq type "thisfile"
7736 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7737 (1+ (point)) (point))
7738 path (buffer-substring
7739 (previous-single-property-change pos 'org-linked-text)
7740 (next-single-property-change pos 'org-linked-text)))
7741 (throw 'match t))
7743 (save-excursion
7744 (when (or (org-in-regexp org-angle-link-re)
7745 (org-in-regexp org-plain-link-re))
7746 (setq type (match-string 1) path (match-string 2))
7747 (throw 'match t)))
7748 (save-excursion
7749 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7750 (setq type "tags"
7751 path (match-string 1))
7752 (while (string-match ":" path)
7753 (setq path (replace-match "+" t t path)))
7754 (throw 'match t)))
7755 (when (org-in-regexp "<\\([^><\n]+\\)>")
7756 (setq type "tree-match"
7757 path (match-string 1))
7758 (throw 'match t)))
7759 (unless path
7760 (error "No link found"))
7762 ;; switch back to reference buffer
7763 ;; needed when if called in a temporary buffer through
7764 ;; org-open-link-from-string
7765 (and reference-buffer (switch-to-buffer reference-buffer))
7767 ;; Remove any trailing spaces in path
7768 (if (string-match " +\\'" path)
7769 (setq path (replace-match "" t t path)))
7770 (if (and org-link-translation-function
7771 (fboundp org-link-translation-function))
7772 ;; Check if we need to translate the link
7773 (let ((tmp (funcall org-link-translation-function type path)))
7774 (setq type (car tmp) path (cdr tmp))))
7776 (cond
7778 ((assoc type org-link-protocols)
7779 (funcall (nth 1 (assoc type org-link-protocols)) path))
7781 ((equal type "mailto")
7782 (let ((cmd (car org-link-mailto-program))
7783 (args (cdr org-link-mailto-program)) args1
7784 (address path) (subject "") a)
7785 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7786 (setq address (match-string 1 path)
7787 subject (org-link-escape (match-string 2 path))))
7788 (while args
7789 (cond
7790 ((not (stringp (car args))) (push (pop args) args1))
7791 (t (setq a (pop args))
7792 (if (string-match "%a" a)
7793 (setq a (replace-match address t t a)))
7794 (if (string-match "%s" a)
7795 (setq a (replace-match subject t t a)))
7796 (push a args1))))
7797 (apply cmd (nreverse args1))))
7799 ((member type '("http" "https" "ftp" "news"))
7800 (browse-url (concat type ":" (org-link-escape
7801 path org-link-escape-chars-browser))))
7803 ((member type '("message"))
7804 (browse-url (concat type ":" path)))
7806 ((string= type "tags")
7807 (org-tags-view in-emacs path))
7808 ((string= type "thisfile")
7809 (if in-emacs
7810 (switch-to-buffer-other-window
7811 (org-get-buffer-for-internal-link (current-buffer)))
7812 (org-mark-ring-push))
7813 (let ((cmd `(org-link-search
7814 ,path
7815 ,(cond ((equal in-emacs '(4)) 'occur)
7816 ((equal in-emacs '(16)) 'org-occur)
7817 (t nil))
7818 ,pos)))
7819 (condition-case nil (eval cmd)
7820 (error (progn (widen) (eval cmd))))))
7822 ((string= type "tree-match")
7823 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7825 ((string= type "file")
7826 (if (string-match "::\\([0-9]+\\)\\'" path)
7827 (setq line (string-to-number (match-string 1 path))
7828 path (substring path 0 (match-beginning 0)))
7829 (if (string-match "::\\(.+\\)\\'" path)
7830 (setq search (match-string 1 path)
7831 path (substring path 0 (match-beginning 0)))))
7832 (if (string-match "[*?{]" (file-name-nondirectory path))
7833 (dired path)
7834 (org-open-file path in-emacs line search)))
7836 ((string= type "news")
7837 (require 'org-gnus)
7838 (org-gnus-follow-link path))
7840 ((string= type "shell")
7841 (let ((cmd path))
7842 (if (or (not org-confirm-shell-link-function)
7843 (funcall org-confirm-shell-link-function
7844 (format "Execute \"%s\" in shell? "
7845 (org-add-props cmd nil
7846 'face 'org-warning))))
7847 (progn
7848 (message "Executing %s" cmd)
7849 (shell-command cmd))
7850 (error "Abort"))))
7852 ((string= type "elisp")
7853 (let ((cmd path))
7854 (if (or (not org-confirm-elisp-link-function)
7855 (funcall org-confirm-elisp-link-function
7856 (format "Execute \"%s\" as elisp? "
7857 (org-add-props cmd nil
7858 'face 'org-warning))))
7859 (message "%s => %s" cmd
7860 (if (equal (string-to-char cmd) ?\()
7861 (eval (read cmd))
7862 (call-interactively (read cmd))))
7863 (error "Abort"))))
7866 (browse-url-at-point))))))
7867 (move-marker org-open-link-marker nil)
7868 (run-hook-with-args 'org-follow-link-hook))
7870 ;;;; Time estimates
7872 (defun org-get-effort (&optional pom)
7873 "Get the effort estimate for the current entry."
7874 (org-entry-get pom org-effort-property))
7876 ;;; File search
7878 (defvar org-create-file-search-functions nil
7879 "List of functions to construct the right search string for a file link.
7880 These functions are called in turn with point at the location to
7881 which the link should point.
7883 A function in the hook should first test if it would like to
7884 handle this file type, for example by checking the major-mode or
7885 the file extension. If it decides not to handle this file, it
7886 should just return nil to give other functions a chance. If it
7887 does handle the file, it must return the search string to be used
7888 when following the link. The search string will be part of the
7889 file link, given after a double colon, and `org-open-at-point'
7890 will automatically search for it. If special measures must be
7891 taken to make the search successful, another function should be
7892 added to the companion hook `org-execute-file-search-functions',
7893 which see.
7895 A function in this hook may also use `setq' to set the variable
7896 `description' to provide a suggestion for the descriptive text to
7897 be used for this link when it gets inserted into an Org-mode
7898 buffer with \\[org-insert-link].")
7900 (defvar org-execute-file-search-functions nil
7901 "List of functions to execute a file search triggered by a link.
7903 Functions added to this hook must accept a single argument, the
7904 search string that was part of the file link, the part after the
7905 double colon. The function must first check if it would like to
7906 handle this search, for example by checking the major-mode or the
7907 file extension. If it decides not to handle this search, it
7908 should just return nil to give other functions a chance. If it
7909 does handle the search, it must return a non-nil value to keep
7910 other functions from trying.
7912 Each function can access the current prefix argument through the
7913 variable `current-prefix-argument'. Note that a single prefix is
7914 used to force opening a link in Emacs, so it may be good to only
7915 use a numeric or double prefix to guide the search function.
7917 In case this is needed, a function in this hook can also restore
7918 the window configuration before `org-open-at-point' was called using:
7920 (set-window-configuration org-window-config-before-follow-link)")
7922 (defun org-link-search (s &optional type avoid-pos)
7923 "Search for a link search option.
7924 If S is surrounded by forward slashes, it is interpreted as a
7925 regular expression. In org-mode files, this will create an `org-occur'
7926 sparse tree. In ordinary files, `occur' will be used to list matches.
7927 If the current buffer is in `dired-mode', grep will be used to search
7928 in all files. If AVOID-POS is given, ignore matches near that position."
7929 (let ((case-fold-search t)
7930 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7931 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7932 (append '(("") (" ") ("\t") ("\n"))
7933 org-emphasis-alist)
7934 "\\|") "\\)"))
7935 (pos (point))
7936 (pre nil) (post nil)
7937 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7938 (cond
7939 ;; First check if there are any special
7940 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7941 ;; Now try the builtin stuff
7942 ((and (equal (string-to-char s0) ?#)
7943 (> (length s0) 1)
7944 (save-excursion
7945 (goto-char (point-min))
7946 (and
7947 (re-search-forward
7948 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
7949 (setq type 'dedicated
7950 pos (match-beginning 0))))
7951 ;; There is an exact target for this
7952 (goto-char pos)
7953 (org-back-to-heading t)))
7954 ((save-excursion
7955 (goto-char (point-min))
7956 (and
7957 (re-search-forward
7958 (concat "<<" (regexp-quote s0) ">>") nil t)
7959 (setq type 'dedicated
7960 pos (match-beginning 0))))
7961 ;; There is an exact target for this
7962 (goto-char pos))
7963 ((and (string-match "^(\\(.*\\))$" s0)
7964 (save-excursion
7965 (goto-char (point-min))
7966 (and
7967 (re-search-forward
7968 (concat "[^[]" (regexp-quote
7969 (format org-coderef-label-format
7970 (match-string 1 s0))))
7971 nil t)
7972 (setq type 'dedicated
7973 pos (1+ (match-beginning 0))))))
7974 ;; There is a coderef target for this
7975 (goto-char pos))
7976 ((string-match "^/\\(.*\\)/$" s)
7977 ;; A regular expression
7978 (cond
7979 ((org-mode-p)
7980 (org-occur (match-string 1 s)))
7981 ;;((eq major-mode 'dired-mode)
7982 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7983 (t (org-do-occur (match-string 1 s)))))
7985 ;; A normal search strings
7986 (when (equal (string-to-char s) ?*)
7987 ;; Anchor on headlines, post may include tags.
7988 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7989 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7990 s (substring s 1)))
7991 (remove-text-properties
7992 0 (length s)
7993 '(face nil mouse-face nil keymap nil fontified nil) s)
7994 ;; Make a series of regular expressions to find a match
7995 (setq words (org-split-string s "[ \n\r\t]+")
7997 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7998 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7999 "\\)" markers)
8000 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8001 re2a (concat "[ \t\r\n]" re2a_)
8002 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8003 re4 (concat "[^a-zA-Z_]" re4_)
8005 re1 (concat pre re2 post)
8006 re3 (concat pre (if pre re4_ re4) post)
8007 re5 (concat pre ".*" re4)
8008 re2 (concat pre re2)
8009 re2a (concat pre (if pre re2a_ re2a))
8010 re4 (concat pre (if pre re4_ re4))
8011 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8012 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8013 re5 "\\)"
8015 (cond
8016 ((eq type 'org-occur) (org-occur reall))
8017 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8018 (t (goto-char (point-min))
8019 (setq type 'fuzzy)
8020 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8021 (org-search-not-self 1 re1 nil t)
8022 (org-search-not-self 1 re2 nil t)
8023 (org-search-not-self 1 re2a nil t)
8024 (org-search-not-self 1 re3 nil t)
8025 (org-search-not-self 1 re4 nil t)
8026 (org-search-not-self 1 re5 nil t)
8028 (goto-char (match-beginning 1))
8029 (goto-char pos)
8030 (error "No match")))))
8032 ;; Normal string-search
8033 (goto-char (point-min))
8034 (if (search-forward s nil t)
8035 (goto-char (match-beginning 0))
8036 (error "No match"))))
8037 (and (org-mode-p) (org-show-context 'link-search))
8038 type))
8040 (defun org-search-not-self (group &rest args)
8041 "Execute `re-search-forward', but only accept matches that do not
8042 enclose the position of `org-open-link-marker'."
8043 (let ((m org-open-link-marker))
8044 (catch 'exit
8045 (while (apply 're-search-forward args)
8046 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8047 (goto-char (match-end group))
8048 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8049 (> (match-beginning 0) (marker-position m))
8050 (< (match-end 0) (marker-position m)))
8051 (save-match-data
8052 (or (not (org-in-regexp
8053 org-bracket-link-analytic-regexp 1))
8054 (not (match-end 4)) ; no description
8055 (and (<= (match-beginning 4) (point))
8056 (>= (match-end 4) (point))))))
8057 (throw 'exit (point))))))))
8059 (defun org-get-buffer-for-internal-link (buffer)
8060 "Return a buffer to be used for displaying the link target of internal links."
8061 (cond
8062 ((not org-display-internal-link-with-indirect-buffer)
8063 buffer)
8064 ((string-match "(Clone)$" (buffer-name buffer))
8065 (message "Buffer is already a clone, not making another one")
8066 ;; we also do not modify visibility in this case
8067 buffer)
8068 (t ; make a new indirect buffer for displaying the link
8069 (let* ((bn (buffer-name buffer))
8070 (ibn (concat bn "(Clone)"))
8071 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8072 (with-current-buffer ib (org-overview))
8073 ib))))
8075 (defun org-do-occur (regexp &optional cleanup)
8076 "Call the Emacs command `occur'.
8077 If CLEANUP is non-nil, remove the printout of the regular expression
8078 in the *Occur* buffer. This is useful if the regex is long and not useful
8079 to read."
8080 (occur regexp)
8081 (when cleanup
8082 (let ((cwin (selected-window)) win beg end)
8083 (when (setq win (get-buffer-window "*Occur*"))
8084 (select-window win))
8085 (goto-char (point-min))
8086 (when (re-search-forward "match[a-z]+" nil t)
8087 (setq beg (match-end 0))
8088 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8089 (setq end (1- (match-beginning 0)))))
8090 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8091 (goto-char (point-min))
8092 (select-window cwin))))
8094 ;;; The mark ring for links jumps
8096 (defvar org-mark-ring nil
8097 "Mark ring for positions before jumps in Org-mode.")
8098 (defvar org-mark-ring-last-goto nil
8099 "Last position in the mark ring used to go back.")
8100 ;; Fill and close the ring
8101 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8102 (loop for i from 1 to org-mark-ring-length do
8103 (push (make-marker) org-mark-ring))
8104 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8105 org-mark-ring)
8107 (defun org-mark-ring-push (&optional pos buffer)
8108 "Put the current position or POS into the mark ring and rotate it."
8109 (interactive)
8110 (setq pos (or pos (point)))
8111 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8112 (move-marker (car org-mark-ring)
8113 (or pos (point))
8114 (or buffer (current-buffer)))
8115 (message "%s"
8116 (substitute-command-keys
8117 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8119 (defun org-mark-ring-goto (&optional n)
8120 "Jump to the previous position in the mark ring.
8121 With prefix arg N, jump back that many stored positions. When
8122 called several times in succession, walk through the entire ring.
8123 Org-mode commands jumping to a different position in the current file,
8124 or to another Org-mode file, automatically push the old position
8125 onto the ring."
8126 (interactive "p")
8127 (let (p m)
8128 (if (eq last-command this-command)
8129 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8130 (setq p org-mark-ring))
8131 (setq org-mark-ring-last-goto p)
8132 (setq m (car p))
8133 (switch-to-buffer (marker-buffer m))
8134 (goto-char m)
8135 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8137 (defun org-remove-angle-brackets (s)
8138 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8139 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8141 (defun org-add-angle-brackets (s)
8142 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8143 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8145 (defun org-remove-double-quotes (s)
8146 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8147 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8150 ;;; Following specific links
8152 (defun org-follow-timestamp-link ()
8153 (cond
8154 ((org-at-date-range-p t)
8155 (let ((org-agenda-start-on-weekday)
8156 (t1 (match-string 1))
8157 (t2 (match-string 2)))
8158 (setq t1 (time-to-days (org-time-string-to-time t1))
8159 t2 (time-to-days (org-time-string-to-time t2)))
8160 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8161 ((org-at-timestamp-p t)
8162 (org-agenda-list nil (time-to-days (org-time-string-to-time
8163 (substring (match-string 1) 0 10)))
8165 (t (error "This should not happen"))))
8168 ;;; Following file links
8169 (defvar org-wait nil)
8170 (defun org-open-file (path &optional in-emacs line search)
8171 "Open the file at PATH.
8172 First, this expands any special file name abbreviations. Then the
8173 configuration variable `org-file-apps' is checked if it contains an
8174 entry for this file type, and if yes, the corresponding command is launched.
8176 If no application is found, Emacs simply visits the file.
8178 With optional prefix argument IN-EMACS, Emacs will visit the file.
8179 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8180 and o use an external application to visit the file.
8182 Optional LINE specifies a line to go to, optional SEARCH a string to
8183 search for. If LINE or SEARCH is given, the file will always be
8184 opened in Emacs.
8185 If the file does not exist, an error is thrown."
8186 (setq in-emacs (or in-emacs line search))
8187 (let* ((file (if (equal path "")
8188 buffer-file-name
8189 (substitute-in-file-name (expand-file-name path))))
8190 (apps (append org-file-apps (org-default-apps)))
8191 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8192 (dirp (if remp nil (file-directory-p file)))
8193 (file (if (and dirp org-open-directory-means-index-dot-org)
8194 (concat (file-name-as-directory file) "index.org")
8195 file))
8196 (a-m-a-p (assq 'auto-mode apps))
8197 (dfile (downcase file))
8198 (old-buffer (current-buffer))
8199 (old-pos (point))
8200 (old-mode major-mode)
8201 ext cmd)
8202 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8203 (setq ext (match-string 1 dfile))
8204 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8205 (setq ext (match-string 1 dfile))))
8206 (cond
8207 ((equal in-emacs '(16))
8208 (setq cmd (cdr (assoc 'system apps))))
8209 (in-emacs (setq cmd 'emacs))
8211 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8212 (and dirp (cdr (assoc 'directory apps)))
8213 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8214 'string-match)
8215 (cdr (assoc ext apps))
8216 (cdr (assoc t apps))))))
8217 (when (eq cmd 'system)
8218 (setq cmd (cdr (assoc 'system apps))))
8219 (when (eq cmd 'default)
8220 (setq cmd (cdr (assoc t apps))))
8221 (when (eq cmd 'mailcap)
8222 (require 'mailcap)
8223 (mailcap-parse-mailcaps)
8224 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8225 (command (mailcap-mime-info mime-type)))
8226 (if (stringp command)
8227 (setq cmd command)
8228 (setq cmd 'emacs))))
8229 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8230 (not (file-exists-p file))
8231 (not org-open-non-existing-files))
8232 (error "No such file: %s" file))
8233 (cond
8234 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8235 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8236 (while (string-match "['\"]%s['\"]" cmd)
8237 (setq cmd (replace-match "%s" t t cmd)))
8238 (while (string-match "%s" cmd)
8239 (setq cmd (replace-match
8240 (save-match-data
8241 (shell-quote-argument
8242 (convert-standard-filename file)))
8243 t t cmd)))
8244 (save-window-excursion
8245 (start-process-shell-command cmd nil cmd)
8246 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8248 ((or (stringp cmd)
8249 (eq cmd 'emacs))
8250 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8251 (widen)
8252 (if line (goto-line line)
8253 (if search (org-link-search search))))
8254 ((consp cmd)
8255 (let ((file (convert-standard-filename file)))
8256 (eval cmd)))
8257 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8258 (and (org-mode-p) (eq old-mode 'org-mode)
8259 (or (not (equal old-buffer (current-buffer)))
8260 (not (equal old-pos (point))))
8261 (org-mark-ring-push old-pos old-buffer))))
8263 (defun org-default-apps ()
8264 "Return the default applications for this operating system."
8265 (cond
8266 ((eq system-type 'darwin)
8267 org-file-apps-defaults-macosx)
8268 ((eq system-type 'windows-nt)
8269 org-file-apps-defaults-windowsnt)
8270 (t org-file-apps-defaults-gnu)))
8272 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8273 "Convert extensions to regular expressions in the cars of LIST.
8274 Also, weed out any non-string entries, because the return value is used
8275 only for regexp matching.
8276 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8277 point to the symbol `emacs', indicating that the file should
8278 be opened in Emacs."
8279 (append
8280 (delq nil
8281 (mapcar (lambda (x)
8282 (if (not (stringp (car x)))
8284 (if (string-match "\\W" (car x))
8286 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8287 list))
8288 (if add-auto-mode
8289 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8291 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8292 (defun org-file-remote-p (file)
8293 "Test whether FILE specifies a location on a remote system.
8294 Return non-nil if the location is indeed remote.
8296 For example, the filename \"/user@host:/foo\" specifies a location
8297 on the system \"/user@host:\"."
8298 (cond ((fboundp 'file-remote-p)
8299 (file-remote-p file))
8300 ((fboundp 'tramp-handle-file-remote-p)
8301 (tramp-handle-file-remote-p file))
8302 ((and (boundp 'ange-ftp-name-format)
8303 (string-match (car ange-ftp-name-format) file))
8305 (t nil)))
8308 ;;;; Refiling
8310 (defun org-get-org-file ()
8311 "Read a filename, with default directory `org-directory'."
8312 (let ((default (or org-default-notes-file remember-data-file)))
8313 (read-file-name (format "File name [%s]: " default)
8314 (file-name-as-directory org-directory)
8315 default)))
8317 (defun org-notes-order-reversed-p ()
8318 "Check if the current file should receive notes in reversed order."
8319 (cond
8320 ((not org-reverse-note-order) nil)
8321 ((eq t org-reverse-note-order) t)
8322 ((not (listp org-reverse-note-order)) nil)
8323 (t (catch 'exit
8324 (let ((all org-reverse-note-order)
8325 entry)
8326 (while (setq entry (pop all))
8327 (if (string-match (car entry) buffer-file-name)
8328 (throw 'exit (cdr entry))))
8329 nil)))))
8331 (defvar org-refile-target-table nil
8332 "The list of refile targets, created by `org-refile'.")
8334 (defvar org-agenda-new-buffers nil
8335 "Buffers created to visit agenda files.")
8337 (defun org-get-refile-targets (&optional default-buffer)
8338 "Produce a table with refile targets."
8339 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8340 targets txt re files f desc descre fast-path-p level pos0)
8341 (message "Getting targets...")
8342 (with-current-buffer (or default-buffer (current-buffer))
8343 (while (setq entry (pop entries))
8344 (setq files (car entry) desc (cdr entry))
8345 (setq fast-path-p nil)
8346 (cond
8347 ((null files) (setq files (list (current-buffer))))
8348 ((eq files 'org-agenda-files)
8349 (setq files (org-agenda-files 'unrestricted)))
8350 ((and (symbolp files) (fboundp files))
8351 (setq files (funcall files)))
8352 ((and (symbolp files) (boundp files))
8353 (setq files (symbol-value files))))
8354 (if (stringp files) (setq files (list files)))
8355 (cond
8356 ((eq (car desc) :tag)
8357 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8358 ((eq (car desc) :todo)
8359 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8360 ((eq (car desc) :regexp)
8361 (setq descre (cdr desc)))
8362 ((eq (car desc) :level)
8363 (setq descre (concat "^\\*\\{" (number-to-string
8364 (if org-odd-levels-only
8365 (1- (* 2 (cdr desc)))
8366 (cdr desc)))
8367 "\\}[ \t]")))
8368 ((eq (car desc) :maxlevel)
8369 (setq fast-path-p t)
8370 (setq descre (concat "^\\*\\{1," (number-to-string
8371 (if org-odd-levels-only
8372 (1- (* 2 (cdr desc)))
8373 (cdr desc)))
8374 "\\}[ \t]")))
8375 (t (error "Bad refiling target description %s" desc)))
8376 (while (setq f (pop files))
8377 (save-excursion
8378 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8379 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8380 (setq f (expand-file-name f))
8381 (if (eq org-refile-use-outline-path 'file)
8382 (push (list (file-name-nondirectory f) f nil nil) targets))
8383 (save-excursion
8384 (save-restriction
8385 (widen)
8386 (goto-char (point-min))
8387 (while (re-search-forward descre nil t)
8388 (goto-char (setq pos0 (point-at-bol)))
8389 (catch 'next
8390 (when org-refile-target-verify-function
8391 (save-match-data
8392 (or (funcall org-refile-target-verify-function)
8393 (throw 'next t))))
8394 (when (looking-at org-complex-heading-regexp)
8395 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8396 txt (org-link-display-format (match-string 4))
8397 re (concat "^" (regexp-quote
8398 (buffer-substring (match-beginning 1)
8399 (match-end 4)))))
8400 (if (match-end 5) (setq re (concat re "[ \t]+"
8401 (regexp-quote
8402 (match-string 5)))))
8403 (setq re (concat re "[ \t]*$"))
8404 (when org-refile-use-outline-path
8405 (setq txt (mapconcat 'org-protect-slash
8406 (append
8407 (if (eq org-refile-use-outline-path 'file)
8408 (list (file-name-nondirectory
8409 (buffer-file-name (buffer-base-buffer))))
8410 (if (eq org-refile-use-outline-path 'full-file-path)
8411 (list (buffer-file-name (buffer-base-buffer)))))
8412 (org-get-outline-path fast-path-p level txt)
8413 (list txt))
8414 "/")))
8415 (push (list txt f re (point)) targets)))
8416 (when (= (point) pos0)
8417 ;; verification function has not moved point
8418 (goto-char (point-at-eol))))))))))
8419 (message "Getting targets...done")
8420 (nreverse targets)))
8422 (defun org-protect-slash (s)
8423 (while (string-match "/" s)
8424 (setq s (replace-match "\\" t t s)))
8427 (defvar org-olpa (make-vector 20 nil))
8429 (defun org-get-outline-path (&optional fastp level heading)
8430 "Return the outline path to the current entry, as a list."
8431 (if fastp
8432 (progn
8433 (if (> level 19)
8434 (error "Outline path failure, more than 19 levels."))
8435 (loop for i from level upto 19 do
8436 (aset org-olpa i nil))
8437 (prog1
8438 (delq nil (append org-olpa nil))
8439 (aset org-olpa level heading)))
8440 (let (rtn)
8441 (save-excursion
8442 (while (org-up-heading-safe)
8443 (when (looking-at org-complex-heading-regexp)
8444 (push (org-match-string-no-properties 4) rtn)))
8445 rtn))))
8447 (defvar org-refile-history nil
8448 "History for refiling operations.")
8450 (defvar org-after-refile-insert-hook nil
8451 "Hook run after `org-refile' has inserted its stuff at the new location.
8452 Note that this is still *before* the stuff will be removed from
8453 the *old* location.")
8455 (defun org-refile (&optional goto default-buffer rfloc)
8456 "Move the entry at point to another heading.
8457 The list of target headings is compiled using the information in
8458 `org-refile-targets', which see. This list is created before each use
8459 and will therefore always be up-to-date.
8461 At the target location, the entry is filed as a subitem of the target heading.
8462 Depending on `org-reverse-note-order', the new subitem will either be the
8463 first or the last subitem.
8465 If there is an active region, all entries in that region will be moved.
8466 However, the region must fulfil the requirement that the first heading
8467 is the first one sets the top-level of the moved text - at most siblings
8468 below it are allowed.
8470 With prefix arg GOTO, the command will only visit the target location,
8471 not actually move anything.
8472 With a double prefix `C-u C-u', go to the location where the last refiling
8473 operation has put the subtree.
8475 RFLOC can be a refile location obtained in a different way.
8477 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8478 (interactive "P")
8479 (let* ((cbuf (current-buffer))
8480 (regionp (org-region-active-p))
8481 (region-start (and regionp (region-beginning)))
8482 (region-end (and regionp (region-end)))
8483 (region-length (and regionp (- region-end region-start)))
8484 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8485 pos it nbuf file re level reversed)
8486 (when regionp (goto-char region-start)
8487 (unless (org-kill-is-subtree-p
8488 (buffer-substring region-start region-end))
8489 (error "The region is not a (sequence of) subtree(s)")))
8490 (if (equal goto '(16))
8491 (org-refile-goto-last-stored)
8492 (when (setq it (or rfloc
8493 (org-refile-get-location
8494 (if goto "Goto: " "Refile to: ") default-buffer
8495 org-refile-allow-creating-parent-nodes)))
8496 (setq file (nth 1 it)
8497 re (nth 2 it)
8498 pos (nth 3 it))
8499 (if (and (not goto)
8501 (equal (buffer-file-name) file)
8502 (if regionp
8503 (and (>= pos region-start)
8504 (<= pos region-end))
8505 (and (>= pos (point))
8506 (< pos (save-excursion
8507 (org-end-of-subtree t t))))))
8508 (error "Cannot refile to position inside the tree or region"))
8510 (setq nbuf (or (find-buffer-visiting file)
8511 (find-file-noselect file)))
8512 (if goto
8513 (progn
8514 (switch-to-buffer nbuf)
8515 (goto-char pos)
8516 (org-show-context 'org-goto))
8517 (if regionp
8518 (progn
8519 (kill-new (buffer-substring region-start region-end))
8520 (org-save-markers-in-region region-start region-end))
8521 (org-copy-subtree 1 nil t))
8522 (save-excursion
8523 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8524 (find-file-noselect file))))
8525 (setq reversed (org-notes-order-reversed-p))
8526 (save-excursion
8527 (save-restriction
8528 (widen)
8529 (if pos
8530 (progn
8531 (goto-char pos)
8532 (looking-at outline-regexp)
8533 (setq level (org-get-valid-level (funcall outline-level) 1))
8534 (goto-char
8535 (if reversed
8536 (or (outline-next-heading) (point-max))
8537 (or (save-excursion (outline-get-next-sibling))
8538 (org-end-of-subtree t t)
8539 (point-max)))))
8540 (setq level 1)
8541 (if (not reversed)
8542 (goto-char (point-max))
8543 (goto-char (point-min))
8544 (or (outline-next-heading) (goto-char (point-max)))))
8545 (if (not (bolp)) (newline))
8546 (bookmark-set "org-refile-last-stored")
8547 (org-paste-subtree level)
8548 (if (fboundp 'deactivate-mark) (deactivate-mark))
8549 (run-hooks 'org-after-refile-insert-hook))))
8550 (if regionp
8551 (delete-region (point) (+ (point) region-length))
8552 (org-cut-subtree))
8553 (when (featurep 'org-inlinetask)
8554 (org-inlinetask-remove-END-maybe))
8555 (setq org-markers-to-move nil)
8556 (message "Refiled to \"%s\"" (car it))))))
8557 (org-reveal))
8559 (defun org-refile-goto-last-stored ()
8560 "Go to the location where the last refile was stored."
8561 (interactive)
8562 (bookmark-jump "org-refile-last-stored")
8563 (message "This is the location of the last refile"))
8565 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8566 "Prompt the user for a refile location, using PROMPT."
8567 (let ((org-refile-targets org-refile-targets)
8568 (org-refile-use-outline-path org-refile-use-outline-path))
8569 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8570 (unless org-refile-target-table
8571 (error "No refile targets"))
8572 (let* ((cbuf (current-buffer))
8573 (partial-completion-mode nil)
8574 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8575 (cfunc (if (and org-refile-use-outline-path
8576 org-outline-path-complete-in-steps)
8577 'org-olpath-completing-read
8578 'org-ido-completing-read))
8579 (extra (if org-refile-use-outline-path "/" ""))
8580 (filename (and cfn (expand-file-name cfn)))
8581 (tbl (mapcar
8582 (lambda (x)
8583 (if (and (not (member org-refile-use-outline-path
8584 '(file full-file-path)))
8585 (not (equal filename (nth 1 x))))
8586 (cons (concat (car x) extra " ("
8587 (file-name-nondirectory (nth 1 x)) ")")
8588 (cdr x))
8589 (cons (concat (car x) extra) (cdr x))))
8590 org-refile-target-table))
8591 (completion-ignore-case t)
8592 pa answ parent-target child parent)
8593 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8594 nil 'org-refile-history))
8595 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8596 (if pa
8597 (progn
8598 (setcar org-refile-history (car pa))
8600 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8601 (setq parent (match-string 1 answ)
8602 child (match-string 2 answ))
8603 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8604 (when (and parent-target
8605 (or (eq new-nodes t)
8606 (and (eq new-nodes 'confirm)
8607 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8608 (org-refile-new-child parent-target child))))))
8610 (defun org-refile-new-child (parent-target child)
8611 "Use refile target PARENT-TARGET to add new CHILD below it."
8612 (unless parent-target
8613 (error "Cannot find parent for new node"))
8614 (let ((file (nth 1 parent-target))
8615 (pos (nth 3 parent-target))
8616 level)
8617 (with-current-buffer (or (find-buffer-visiting file)
8618 (find-file-noselect file))
8619 (save-excursion
8620 (save-restriction
8621 (widen)
8622 (if pos
8623 (goto-char pos)
8624 (goto-char (point-max))
8625 (if (not (bolp)) (newline)))
8626 (when (looking-at outline-regexp)
8627 (setq level (funcall outline-level))
8628 (org-end-of-subtree t t))
8629 (org-back-over-empty-lines)
8630 (insert "\n" (make-string
8631 (if pos (org-get-valid-level level 1) 1) ?*)
8632 " " child "\n")
8633 (beginning-of-line 0)
8634 (list (concat (car parent-target) "/" child) file "" (point)))))))
8636 (defun org-olpath-completing-read (prompt collection &rest args)
8637 "Read an outline path like a file name."
8638 (let ((thetable collection)
8639 (org-completion-use-ido nil)) ; does not work with ido.
8640 (apply
8641 'org-ido-completing-read prompt
8642 (lambda (string predicate &optional flag)
8643 (let (rtn r f (l (length string)))
8644 (cond
8645 ((eq flag nil)
8646 ;; try completion
8647 (try-completion string thetable))
8648 ((eq flag t)
8649 ;; all-completions
8650 (setq rtn (all-completions string thetable predicate))
8651 (mapcar
8652 (lambda (x)
8653 (setq r (substring x l))
8654 (if (string-match " ([^)]*)$" x)
8655 (setq f (match-string 0 x))
8656 (setq f ""))
8657 (if (string-match "/" r)
8658 (concat string (substring r 0 (match-end 0)) f)
8660 rtn))
8661 ((eq flag 'lambda)
8662 ;; exact match?
8663 (assoc string thetable)))
8665 args)))
8667 ;;;; Dynamic blocks
8669 (defun org-find-dblock (name)
8670 "Find the first dynamic block with name NAME in the buffer.
8671 If not found, stay at current position and return nil."
8672 (let (pos)
8673 (save-excursion
8674 (goto-char (point-min))
8675 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8676 nil t)
8677 (match-beginning 0))))
8678 (if pos (goto-char pos))
8679 pos))
8681 (defconst org-dblock-start-re
8682 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8683 "Matches the startline of a dynamic block, with parameters.")
8685 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8686 "Matches the end of a dynamic block.")
8688 (defun org-create-dblock (plist)
8689 "Create a dynamic block section, with parameters taken from PLIST.
8690 PLIST must contain a :name entry which is used as name of the block."
8691 (unless (bolp) (newline))
8692 (let ((name (plist-get plist :name)))
8693 (insert "#+BEGIN: " name)
8694 (while plist
8695 (if (eq (car plist) :name)
8696 (setq plist (cddr plist))
8697 (insert " " (prin1-to-string (pop plist)))))
8698 (insert "\n\n#+END:\n")
8699 (beginning-of-line -2)))
8701 (defun org-prepare-dblock ()
8702 "Prepare dynamic block for refresh.
8703 This empties the block, puts the cursor at the insert position and returns
8704 the property list including an extra property :name with the block name."
8705 (unless (looking-at org-dblock-start-re)
8706 (error "Not at a dynamic block"))
8707 (let* ((begdel (1+ (match-end 0)))
8708 (name (org-no-properties (match-string 1)))
8709 (params (append (list :name name)
8710 (read (concat "(" (match-string 3) ")")))))
8711 (unless (re-search-forward org-dblock-end-re nil t)
8712 (error "Dynamic block not terminated"))
8713 (setq params
8714 (append params
8715 (list :content (buffer-substring
8716 begdel (match-beginning 0)))))
8717 (delete-region begdel (match-beginning 0))
8718 (goto-char begdel)
8719 (open-line 1)
8720 params))
8722 (defun org-map-dblocks (&optional command)
8723 "Apply COMMAND to all dynamic blocks in the current buffer.
8724 If COMMAND is not given, use `org-update-dblock'."
8725 (let ((cmd (or command 'org-update-dblock))
8726 pos)
8727 (save-excursion
8728 (goto-char (point-min))
8729 (while (re-search-forward org-dblock-start-re nil t)
8730 (goto-char (setq pos (match-beginning 0)))
8731 (condition-case nil
8732 (funcall cmd)
8733 (error (message "Error during update of dynamic block")))
8734 (goto-char pos)
8735 (unless (re-search-forward org-dblock-end-re nil t)
8736 (error "Dynamic block not terminated"))))))
8738 (defun org-dblock-update (&optional arg)
8739 "User command for updating dynamic blocks.
8740 Update the dynamic block at point. With prefix ARG, update all dynamic
8741 blocks in the buffer."
8742 (interactive "P")
8743 (if arg
8744 (org-update-all-dblocks)
8745 (or (looking-at org-dblock-start-re)
8746 (org-beginning-of-dblock))
8747 (org-update-dblock)))
8749 (defun org-update-dblock ()
8750 "Update the dynamic block at point
8751 This means to empty the block, parse for parameters and then call
8752 the correct writing function."
8753 (save-window-excursion
8754 (let* ((pos (point))
8755 (line (org-current-line))
8756 (params (org-prepare-dblock))
8757 (name (plist-get params :name))
8758 (cmd (intern (concat "org-dblock-write:" name))))
8759 (message "Updating dynamic block `%s' at line %d..." name line)
8760 (funcall cmd params)
8761 (message "Updating dynamic block `%s' at line %d...done" name line)
8762 (goto-char pos))))
8764 (defun org-beginning-of-dblock ()
8765 "Find the beginning of the dynamic block at point.
8766 Error if there is no such block at point."
8767 (let ((pos (point))
8768 beg)
8769 (end-of-line 1)
8770 (if (and (re-search-backward org-dblock-start-re nil t)
8771 (setq beg (match-beginning 0))
8772 (re-search-forward org-dblock-end-re nil t)
8773 (> (match-end 0) pos))
8774 (goto-char beg)
8775 (goto-char pos)
8776 (error "Not in a dynamic block"))))
8778 (defun org-update-all-dblocks ()
8779 "Update all dynamic blocks in the buffer.
8780 This function can be used in a hook."
8781 (when (org-mode-p)
8782 (org-map-dblocks 'org-update-dblock)))
8785 ;;;; Completion
8787 (defconst org-additional-option-like-keywords
8788 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
8789 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
8790 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "ATTR_LaTeX"
8791 "BEGIN:" "END:"
8792 "ORGTBL" "TBLFM:" "TBLNAME:"
8793 "BEGIN_EXAMPLE" "END_EXAMPLE"
8794 "BEGIN_QUOTE" "END_QUOTE"
8795 "BEGIN_VERSE" "END_VERSE"
8796 "BEGIN_CENTER" "END_CENTER"
8797 "BEGIN_SRC" "END_SRC"
8798 "CATEGORY" "COLUMNS"
8799 "CAPTION" "LABEL"
8800 "BIND"))
8802 (defcustom org-structure-template-alist
8804 ("s" "#+begin_src ?\n\n#+end_src"
8805 "<src lang=\"?\">\n\n</src>")
8806 ("e" "#+begin_example\n?\n#+end_example"
8807 "<example>\n?\n</example>")
8808 ("q" "#+begin_quote\n?\n#+end_quote"
8809 "<quote>\n?\n</quote>")
8810 ("v" "#+begin_verse\n?\n#+end_verse"
8811 "<verse>\n?\n/verse>")
8812 ("c" "#+begin_center\n?\n#+end_center"
8813 "<center>\n?\n/center>")
8814 ("l" "#+begin_latex\n?\n#+end_latex"
8815 "<literal style=\"latex\">\n?\n</literal>")
8816 ("L" "#+latex: "
8817 "<literal style=\"latex\">?</literal>")
8818 ("h" "#+begin_html\n?\n#+end_html"
8819 "<literal style=\"html\">\n?\n</literal>")
8820 ("H" "#+html: "
8821 "<literal style=\"html\">?</literal>")
8822 ("a" "#+begin_ascii\n?\n#+end_ascii")
8823 ("A" "#+ascii: ")
8824 ("i" "#+include %file ?"
8825 "<include file=%file markup=\"?\">")
8827 "Structure completion elements.
8828 This is a list of abbreviation keys and values. The value gets inserted
8829 it you type @samp{.} followed by the key and then the completion key,
8830 usually `M-TAB'. %file will be replaced by a file name after prompting
8831 for the file using completion.
8832 There are two templates for each key, the first uses the original Org syntax,
8833 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8834 the default when the /org-mtags.el/ module has been loaded. See also the
8835 variable `org-mtags-prefer-muse-templates'.
8836 This is an experimental feature, it is undecided if it is going to stay in."
8837 :group 'org-completion
8838 :type '(repeat
8839 (string :tag "Key")
8840 (string :tag "Template")
8841 (string :tag "Muse Template")))
8843 (defun org-try-structure-completion ()
8844 "Try to complete a structure template before point.
8845 This looks for strings like \"<e\" on an otherwise empty line and
8846 expands them."
8847 (let ((l (buffer-substring (point-at-bol) (point)))
8849 (when (and (looking-at "[ \t]*$")
8850 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8851 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8852 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8853 (match-beginning 1)) a)
8854 t)))
8856 (defun org-complete-expand-structure-template (start cell)
8857 "Expand a structure template."
8858 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8859 (rpl (nth (if musep 2 1) cell))
8860 (ind ""))
8861 (delete-region start (point))
8862 (when (string-match "\\`#\\+" rpl)
8863 (cond
8864 ((bolp))
8865 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8866 (setq ind (buffer-substring (point-at-bol) (point))))
8867 (t (newline))))
8868 (setq start (point))
8869 (if (string-match "%file" rpl)
8870 (setq rpl (replace-match
8871 (concat
8872 "\""
8873 (save-match-data
8874 (abbreviate-file-name (read-file-name "Include file: ")))
8875 "\"")
8876 t t rpl)))
8877 (setq rpl (mapconcat 'identity (split-string rpl "\n")
8878 (concat "\n" ind)))
8879 (insert rpl)
8880 (if (re-search-backward "\\?" start t) (delete-char 1))))
8883 (defun org-complete (&optional arg)
8884 "Perform completion on word at point.
8885 At the beginning of a headline, this completes TODO keywords as given in
8886 `org-todo-keywords'.
8887 If the current word is preceded by a backslash, completes the TeX symbols
8888 that are supported for HTML support.
8889 If the current word is preceded by \"#+\", completes special words for
8890 setting file options.
8891 In the line after \"#+STARTUP:, complete valid keywords.\"
8892 At all other locations, this simply calls the value of
8893 `org-completion-fallback-command'."
8894 (interactive "P")
8895 (org-without-partial-completion
8896 (catch 'exit
8897 (let* ((a nil)
8898 (end (point))
8899 (beg1 (save-excursion
8900 (skip-chars-backward (org-re "[:alnum:]_@"))
8901 (point)))
8902 (beg (save-excursion
8903 (skip-chars-backward "a-zA-Z0-9_:$")
8904 (point)))
8905 (confirm (lambda (x) (stringp (car x))))
8906 (searchhead (equal (char-before beg) ?*))
8907 (struct
8908 (when (and (member (char-before beg1) '(?. ?<))
8909 (setq a (assoc (buffer-substring beg1 (point))
8910 org-structure-template-alist)))
8911 (org-complete-expand-structure-template (1- beg1) a)
8912 (throw 'exit t)))
8913 (tag (and (equal (char-before beg1) ?:)
8914 (equal (char-after (point-at-bol)) ?*)))
8915 (prop (and (equal (char-before beg1) ?:)
8916 (not (equal (char-after (point-at-bol)) ?*))))
8917 (texp (equal (char-before beg) ?\\))
8918 (link (equal (char-before beg) ?\[))
8919 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8920 beg)
8921 "#+"))
8922 (startup (string-match "^#\\+STARTUP:.*"
8923 (buffer-substring (point-at-bol) (point))))
8924 (completion-ignore-case opt)
8925 (type nil)
8926 (tbl nil)
8927 (table (cond
8928 (opt
8929 (setq type :opt)
8930 (require 'org-exp)
8931 (append
8932 (mapcar
8933 (lambda (x)
8934 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8935 (cons (match-string 2 x) (match-string 1 x)))
8936 (org-split-string (org-get-current-options) "\n"))
8937 (mapcar 'list org-additional-option-like-keywords)))
8938 (startup
8939 (setq type :startup)
8940 org-startup-options)
8941 (link (append org-link-abbrev-alist-local
8942 org-link-abbrev-alist))
8943 (texp
8944 (setq type :tex)
8945 org-html-entities)
8946 ((string-match "\\`\\*+[ \t]+\\'"
8947 (buffer-substring (point-at-bol) beg))
8948 (setq type :todo)
8949 (mapcar 'list org-todo-keywords-1))
8950 (searchhead
8951 (setq type :searchhead)
8952 (save-excursion
8953 (goto-char (point-min))
8954 (while (re-search-forward org-todo-line-regexp nil t)
8955 (push (list
8956 (org-make-org-heading-search-string
8957 (match-string 3) t))
8958 tbl)))
8959 tbl)
8960 (tag (setq type :tag beg beg1)
8961 (or org-tag-alist (org-get-buffer-tags)))
8962 (prop (setq type :prop beg beg1)
8963 (mapcar 'list (org-buffer-property-keys nil t t)))
8964 (t (progn
8965 (call-interactively org-completion-fallback-command)
8966 (throw 'exit nil)))))
8967 (pattern (buffer-substring-no-properties beg end))
8968 (completion (try-completion pattern table confirm)))
8969 (cond ((eq completion t)
8970 (if (not (assoc (upcase pattern) table))
8971 (message "Already complete")
8972 (if (and (equal type :opt)
8973 (not (member (car (assoc (upcase pattern) table))
8974 org-additional-option-like-keywords)))
8975 (insert (substring (cdr (assoc (upcase pattern) table))
8976 (length pattern)))
8977 (if (memq type '(:tag :prop)) (insert ":")))))
8978 ((null completion)
8979 (message "Can't find completion for \"%s\"" pattern)
8980 (ding))
8981 ((not (string= pattern completion))
8982 (delete-region beg end)
8983 (if (string-match " +$" completion)
8984 (setq completion (replace-match "" t t completion)))
8985 (insert completion)
8986 (if (get-buffer-window "*Completions*")
8987 (delete-window (get-buffer-window "*Completions*")))
8988 (if (assoc completion table)
8989 (if (eq type :todo) (insert " ")
8990 (if (memq type '(:tag :prop)) (insert ":"))))
8991 (if (and (equal type :opt) (assoc completion table))
8992 (message "%s" (substitute-command-keys
8993 "Press \\[org-complete] again to insert example settings"))))
8995 (message "Making completion list...")
8996 (let ((list (sort (all-completions pattern table confirm)
8997 'string<)))
8998 (with-output-to-temp-buffer "*Completions*"
8999 (condition-case nil
9000 ;; Protection needed for XEmacs and emacs 21
9001 (display-completion-list list pattern)
9002 (error (display-completion-list list)))))
9003 (message "Making completion list...%s" "done")))))))
9005 ;;;; TODO, DEADLINE, Comments
9007 (defun org-toggle-comment ()
9008 "Change the COMMENT state of an entry."
9009 (interactive)
9010 (save-excursion
9011 (org-back-to-heading)
9012 (let (case-fold-search)
9013 (if (looking-at (concat outline-regexp
9014 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9015 (replace-match "" t t nil 1)
9016 (if (looking-at outline-regexp)
9017 (progn
9018 (goto-char (match-end 0))
9019 (insert org-comment-string " ")))))))
9021 (defvar org-last-todo-state-is-todo nil
9022 "This is non-nil when the last TODO state change led to a TODO state.
9023 If the last change removed the TODO tag or switched to DONE, then
9024 this is nil.")
9026 (defvar org-setting-tags nil) ; dynamically skipped
9028 (defun org-parse-local-options (string var)
9029 "Parse STRING for startup setting relevant for variable VAR."
9030 (let ((rtn (symbol-value var))
9031 e opts)
9032 (save-match-data
9033 (if (or (not string) (not (string-match "\\S-" string)))
9035 (setq opts (delq nil (mapcar (lambda (x)
9036 (setq e (assoc x org-startup-options))
9037 (if (eq (nth 1 e) var) e nil))
9038 (org-split-string string "[ \t]+"))))
9039 (if (not opts)
9041 (setq rtn nil)
9042 (while (setq e (pop opts))
9043 (if (not (nth 3 e))
9044 (setq rtn (nth 2 e))
9045 (if (not (listp rtn)) (setq rtn nil))
9046 (push (nth 2 e) rtn)))
9047 rtn)))))
9049 (defvar org-todo-setup-filter-hook nil
9050 "Hook for functions that pre-filter todo specs.
9052 Each function takes a todo spec and returns either `nil' or the spec
9053 transformed into canonical form." )
9055 (defvar org-todo-get-default-hook nil
9056 "Hook for functions that get a default item for todo.
9058 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9059 `nil' or a string to be used for the todo mark." )
9061 (defvar org-agenda-headline-snapshot-before-repeat)
9063 (defun org-todo (&optional arg)
9064 "Change the TODO state of an item.
9065 The state of an item is given by a keyword at the start of the heading,
9066 like
9067 *** TODO Write paper
9068 *** DONE Call mom
9070 The different keywords are specified in the variable `org-todo-keywords'.
9071 By default the available states are \"TODO\" and \"DONE\".
9072 So for this example: when the item starts with TODO, it is changed to DONE.
9073 When it starts with DONE, the DONE is removed. And when neither TODO nor
9074 DONE are present, add TODO at the beginning of the heading.
9076 With C-u prefix arg, use completion to determine the new state.
9077 With numeric prefix arg, switch to that state.
9078 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9079 With a tripple C-u prefix, circumvent any state blocking.
9081 For calling through lisp, arg is also interpreted in the following way:
9082 'none -> empty state
9083 \"\"(empty string) -> switch to empty state
9084 'done -> switch to DONE
9085 'nextset -> switch to the next set of keywords
9086 'previousset -> switch to the previous set of keywords
9087 \"WAITING\" -> switch to the specified keyword, but only if it
9088 really is a member of `org-todo-keywords'."
9089 (interactive "P")
9090 (if (equal arg '(16)) (setq arg 'nextset))
9091 (let ((org-blocker-hook org-blocker-hook)
9092 (case-fold-search nil))
9093 (when (equal arg '(64))
9094 (setq arg nil org-blocker-hook nil))
9095 (when (and org-blocker-hook
9096 (or org-inhibit-blocking
9097 (org-entry-get nil "NOBLOCKING")))
9098 (setq org-blocker-hook nil))
9099 (save-excursion
9100 (catch 'exit
9101 (org-back-to-heading)
9102 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9103 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9104 (looking-at " *"))
9105 (let* ((match-data (match-data))
9106 (startpos (point-at-bol))
9107 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9108 (org-log-done org-log-done)
9109 (org-log-repeat org-log-repeat)
9110 (org-todo-log-states org-todo-log-states)
9111 (this (match-string 1))
9112 (hl-pos (match-beginning 0))
9113 (head (org-get-todo-sequence-head this))
9114 (ass (assoc head org-todo-kwd-alist))
9115 (interpret (nth 1 ass))
9116 (done-word (nth 3 ass))
9117 (final-done-word (nth 4 ass))
9118 (last-state (or this ""))
9119 (completion-ignore-case t)
9120 (member (member this org-todo-keywords-1))
9121 (tail (cdr member))
9122 (state (cond
9123 ((and org-todo-key-trigger
9124 (or (and (equal arg '(4))
9125 (eq org-use-fast-todo-selection 'prefix))
9126 (and (not arg) org-use-fast-todo-selection
9127 (not (eq org-use-fast-todo-selection
9128 'prefix)))))
9129 ;; Use fast selection
9130 (org-fast-todo-selection))
9131 ((and (equal arg '(4))
9132 (or (not org-use-fast-todo-selection)
9133 (not org-todo-key-trigger)))
9134 ;; Read a state with completion
9135 (org-ido-completing-read
9136 "State: " (mapcar (lambda(x) (list x))
9137 org-todo-keywords-1)
9138 nil t))
9139 ((eq arg 'right)
9140 (if this
9141 (if tail (car tail) nil)
9142 (car org-todo-keywords-1)))
9143 ((eq arg 'left)
9144 (if (equal member org-todo-keywords-1)
9146 (if this
9147 (nth (- (length org-todo-keywords-1)
9148 (length tail) 2)
9149 org-todo-keywords-1)
9150 (org-last org-todo-keywords-1))))
9151 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9152 (setq arg nil))) ; hack to fall back to cycling
9153 (arg
9154 ;; user or caller requests a specific state
9155 (cond
9156 ((equal arg "") nil)
9157 ((eq arg 'none) nil)
9158 ((eq arg 'done) (or done-word (car org-done-keywords)))
9159 ((eq arg 'nextset)
9160 (or (car (cdr (member head org-todo-heads)))
9161 (car org-todo-heads)))
9162 ((eq arg 'previousset)
9163 (let ((org-todo-heads (reverse org-todo-heads)))
9164 (or (car (cdr (member head org-todo-heads)))
9165 (car org-todo-heads))))
9166 ((car (member arg org-todo-keywords-1)))
9167 ((nth (1- (prefix-numeric-value arg))
9168 org-todo-keywords-1))))
9169 ((null member) (or head (car org-todo-keywords-1)))
9170 ((equal this final-done-word) nil) ;; -> make empty
9171 ((null tail) nil) ;; -> first entry
9172 ((memq interpret '(type priority))
9173 (if (eq this-command last-command)
9174 (car tail)
9175 (if (> (length tail) 0)
9176 (or done-word (car org-done-keywords))
9177 nil)))
9179 (car tail))))
9180 (state (or
9181 (run-hook-with-args-until-success
9182 'org-todo-get-default-hook state last-state)
9183 state))
9184 (next (if state (concat " " state " ") " "))
9185 (change-plist (list :type 'todo-state-change :from this :to state
9186 :position startpos))
9187 dolog now-done-p)
9188 (when org-blocker-hook
9189 (setq org-last-todo-state-is-todo
9190 (not (member this org-done-keywords)))
9191 (unless (save-excursion
9192 (save-match-data
9193 (run-hook-with-args-until-failure
9194 'org-blocker-hook change-plist)))
9195 (if (interactive-p)
9196 (error "TODO state change from %s to %s blocked" this state)
9197 ;; fail silently
9198 (message "TODO state change from %s to %s blocked" this state)
9199 (throw 'exit nil))))
9200 (store-match-data match-data)
9201 (replace-match next t t)
9202 (unless (pos-visible-in-window-p hl-pos)
9203 (message "TODO state changed to %s" (org-trim next)))
9204 (unless head
9205 (setq head (org-get-todo-sequence-head state)
9206 ass (assoc head org-todo-kwd-alist)
9207 interpret (nth 1 ass)
9208 done-word (nth 3 ass)
9209 final-done-word (nth 4 ass)))
9210 (when (memq arg '(nextset previousset))
9211 (message "Keyword-Set %d/%d: %s"
9212 (- (length org-todo-sets) -1
9213 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9214 (length org-todo-sets)
9215 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9216 (setq org-last-todo-state-is-todo
9217 (not (member state org-done-keywords)))
9218 (setq now-done-p (and (member state org-done-keywords)
9219 (not (member this org-done-keywords))))
9220 (and logging (org-local-logging logging))
9221 (when (and (or org-todo-log-states org-log-done)
9222 (not (eq org-inhibit-logging t))
9223 (not (memq arg '(nextset previousset))))
9224 ;; we need to look at recording a time and note
9225 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9226 (nth 2 (assoc this org-todo-log-states))))
9227 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9228 (setq dolog 'time))
9229 (when (and state
9230 (member state org-not-done-keywords)
9231 (not (member this org-not-done-keywords)))
9232 ;; This is now a todo state and was not one before
9233 ;; If there was a CLOSED time stamp, get rid of it.
9234 (org-add-planning-info nil nil 'closed))
9235 (when (and now-done-p org-log-done)
9236 ;; It is now done, and it was not done before
9237 (org-add-planning-info 'closed (org-current-time))
9238 (if (and (not dolog) (eq 'note org-log-done))
9239 (org-add-log-setup 'done state this 'findpos 'note)))
9240 (when (and state dolog)
9241 ;; This is a non-nil state, and we need to log it
9242 (org-add-log-setup 'state state this 'findpos dolog)))
9243 ;; Fixup tag positioning
9244 (org-todo-trigger-tag-changes state)
9245 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9246 (when org-provide-todo-statistics
9247 (org-update-parent-todo-statistics))
9248 (run-hooks 'org-after-todo-state-change-hook)
9249 (if (and arg (not (member state org-done-keywords)))
9250 (setq head (org-get-todo-sequence-head state)))
9251 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9252 ;; Do we need to trigger a repeat?
9253 (when now-done-p
9254 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9255 ;; This is for the agenda, take a snapshot of the headline.
9256 (save-match-data
9257 (setq org-agenda-headline-snapshot-before-repeat
9258 (org-get-heading))))
9259 (org-auto-repeat-maybe state))
9260 ;; Fixup cursor location if close to the keyword
9261 (if (and (outline-on-heading-p)
9262 (not (bolp))
9263 (save-excursion (beginning-of-line 1)
9264 (looking-at org-todo-line-regexp))
9265 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9266 (progn
9267 (goto-char (or (match-end 2) (match-end 1)))
9268 (and (looking-at " ") (just-one-space))))
9269 (when org-trigger-hook
9270 (save-excursion
9271 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9273 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9274 "Block turning an entry into a TODO, using the hierarchy.
9275 This checks whether the current task should be blocked from state
9276 changes. Such blocking occurs when:
9278 1. The task has children which are not all in a completed state.
9280 2. A task has a parent with the property :ORDERED:, and there
9281 are siblings prior to the current task with incomplete
9282 status.
9284 3. The parent of the task is blocked because it has siblings that should
9285 be done first, or is child of a block grandparent TODO entry."
9287 (catch 'dont-block
9288 ;; If this is not a todo state change, or if this entry is already DONE,
9289 ;; do not block
9290 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9291 (member (plist-get change-plist :from)
9292 (cons 'done org-done-keywords))
9293 (member (plist-get change-plist :to)
9294 (cons 'todo org-not-done-keywords)))
9295 (throw 'dont-block t))
9296 ;; If this task has children, and any are undone, it's blocked
9297 (save-excursion
9298 (org-back-to-heading t)
9299 (let ((this-level (funcall outline-level)))
9300 (outline-next-heading)
9301 (let ((child-level (funcall outline-level)))
9302 (while (and (not (eobp))
9303 (> child-level this-level))
9304 ;; this todo has children, check whether they are all
9305 ;; completed
9306 (if (and (not (org-entry-is-done-p))
9307 (org-entry-is-todo-p))
9308 (throw 'dont-block nil))
9309 (outline-next-heading)
9310 (setq child-level (funcall outline-level))))))
9311 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9312 ;; any previous siblings are undone, it's blocked
9313 (save-excursion
9314 (org-back-to-heading t)
9315 (let* ((pos (point))
9316 (parent-pos (and (org-up-heading-safe) (point))))
9317 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9318 (when (and (org-entry-get (point) "ORDERED")
9319 (forward-line 1)
9320 (re-search-forward org-not-done-heading-regexp pos t))
9321 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9322 ;; Search further up the hierarchy, to see if an anchestor is blocked
9323 (while t
9324 (goto-char parent-pos)
9325 (if (not (looking-at org-not-done-heading-regexp))
9326 (throw 'dont-block t)) ; do not block, parent is not a TODO
9327 (setq pos (point))
9328 (setq parent-pos (and (org-up-heading-safe) (point)))
9329 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9330 (when (and (org-entry-get (point) "ORDERED")
9331 (forward-line 1)
9332 (re-search-forward org-not-done-heading-regexp pos t))
9333 (throw 'dont-block nil))))))) ; block, older sibling not done.
9335 (defcustom org-track-ordered-property-with-tag nil
9336 "Should the ORDERED property also be shown as a tag?
9337 The ORDERED property decides if an entry should require subtasks to be
9338 completed in sequence. Since a property is not very visible, setting
9339 this option means that toggling the ORDERED property with the command
9340 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9341 not relevant for the behavior, but it makes things more visible.
9343 Note that toggling the tag with tags commands will not change the property
9344 and therefore not influence behavior!
9346 This can be t, meaning the tag ORDERED should be used, It can also be a
9347 string to select a different tag for this task."
9348 :group 'org-todo
9349 :type '(choice
9350 (const :tag "No tracking" nil)
9351 (const :tag "Track with ORDERED tag" t)
9352 (string :tag "Use other tag")))
9354 (defun org-toggle-ordered-property ()
9355 "Toggle the ORDERED property of the current entry.
9356 For better visibility, you can track the value of this property with a tag.
9357 See variable `org-track-ordered-property-with-tag'."
9358 (interactive)
9359 (let* ((t1 org-track-ordered-property-with-tag)
9360 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9361 (save-excursion
9362 (org-back-to-heading)
9363 (if (org-entry-get nil "ORDERED")
9364 (progn
9365 (org-delete-property "ORDERED")
9366 (and tag (org-toggle-tag tag 'off))
9367 (message "Subtasks can be completed in arbitrary order"))
9368 (org-entry-put nil "ORDERED" "t")
9369 (and tag (org-toggle-tag tag 'on))
9370 (message "Subtasks must be completed in sequence")))))
9372 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9373 (defun org-block-todo-from-checkboxes (change-plist)
9374 "Block turning an entry into a TODO, using checkboxes.
9375 This checks whether the current task should be blocked from state
9376 changes because there are uncheckd boxes in this entry."
9377 (catch 'dont-block
9378 ;; If this is not a todo state change, or if this entry is already DONE,
9379 ;; do not block
9380 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9381 (member (plist-get change-plist :from)
9382 (cons 'done org-done-keywords))
9383 (member (plist-get change-plist :to)
9384 (cons 'todo org-not-done-keywords)))
9385 (throw 'dont-block t))
9386 ;; If this task has checkboxes that are not checked, it's blocked
9387 (save-excursion
9388 (org-back-to-heading t)
9389 (let ((beg (point)) end)
9390 (outline-next-heading)
9391 (setq end (point))
9392 (goto-char beg)
9393 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9394 end t)
9395 (progn
9396 (if (boundp 'org-blocked-by-checkboxes)
9397 (setq org-blocked-by-checkboxes t))
9398 (throw 'dont-block nil)))))
9399 t)) ; do not block
9401 (defvar org-entry-property-inherited-from) ;; defined below
9402 (defun org-update-parent-todo-statistics ()
9403 "Update any statistics cookie in the parent of the current headline.
9404 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9405 the entire subtree and this will travel up the hierarchy and update
9406 statistics everywhere."
9407 (interactive)
9408 (let* ((lim 0) prop
9409 (recursive (or (not org-hierarchical-todo-statistics)
9410 (string-match
9411 "\\<recursive\\>"
9412 (or (setq prop (org-entry-get
9413 nil "COOKIE_DATA" 'inherit)) ""))))
9414 (lim (or (and prop (marker-position
9415 org-entry-property-inherited-from))
9416 lim))
9417 (first t)
9418 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9419 level ltoggle l1
9420 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9421 (catch 'exit
9422 (save-excursion
9423 (beginning-of-line 1)
9424 (if (org-at-heading-p)
9425 (setq ltoggle (funcall outline-level))
9426 (error "This should not happen"))
9427 (while (and (setq level (org-up-heading-safe))
9428 (or recursive first)
9429 (>= (point) lim))
9430 (setq first nil)
9431 (unless (and level
9432 (not (string-match
9433 "\\<checkbox\\>"
9434 (downcase
9435 (or (org-entry-get
9436 nil "COOKIE_DATA")
9437 "")))))
9438 (throw 'exit nil))
9439 (while (re-search-forward box-re (point-at-eol) t)
9440 (setq cnt-all 0 cnt-done 0 cookie-present t)
9441 (setq is-percent (match-end 2))
9442 (save-match-data
9443 (unless (outline-next-heading) (throw 'exit nil))
9444 (while (and (looking-at org-complex-heading-regexp)
9445 (> (setq l1 (length (match-string 1))) level))
9446 (setq kwd (and (or recursive (= l1 ltoggle))
9447 (match-string 2)))
9448 (and kwd (setq cnt-all (1+ cnt-all)))
9449 (and (member kwd org-done-keywords)
9450 (setq cnt-done (1+ cnt-done)))
9451 (outline-next-heading)))
9452 (replace-match
9453 (if is-percent
9454 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9455 (format "[%d/%d]" cnt-done cnt-all)))))
9456 (when cookie-present
9457 (run-hook-with-args 'org-after-todo-statistics-hook
9458 cnt-done (- cnt-all cnt-done)))))
9459 (run-hooks 'org-todo-statistics-hook)))
9461 (defvar org-after-todo-statistics-hook nil
9462 "Hook that is called after a TODO statistics cookie has been updated.
9463 Each function is called with two arguments: the number of not-done entries
9464 and the number of done entries.
9466 For example, the following function, when added to this hook, will switch
9467 an entry to DONE when all children are done, and back to TODO when new
9468 entries are set to a TODO status. Note that this hook is only called
9469 when there is a statistics cookie in the headline!
9471 (defun org-summary-todo (n-done n-not-done)
9472 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9473 (let (org-log-done org-log-states) ; turn off logging
9474 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9477 (defvar org-todo-statistics-hook nil
9478 "Hook that is run whenever Org thinks TODO statistics should be updated.
9479 This hook runs even if there is no statisics cookie present, in which case
9480 `org-after-todo-statistics-hook' would not run.")
9482 (defun org-todo-trigger-tag-changes (state)
9483 "Apply the changes defined in `org-todo-state-tags-triggers'."
9484 (let ((l org-todo-state-tags-triggers)
9485 changes)
9486 (when (or (not state) (equal state ""))
9487 (setq changes (append changes (cdr (assoc "" l)))))
9488 (when (and (stringp state) (> (length state) 0))
9489 (setq changes (append changes (cdr (assoc state l)))))
9490 (when (member state org-not-done-keywords)
9491 (setq changes (append changes (cdr (assoc 'todo l)))))
9492 (when (member state org-done-keywords)
9493 (setq changes (append changes (cdr (assoc 'done l)))))
9494 (dolist (c changes)
9495 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9497 (defun org-local-logging (value)
9498 "Get logging settings from a property VALUE."
9499 (let* (words w a)
9500 ;; directly set the variables, they are already local.
9501 (setq org-log-done nil
9502 org-log-repeat nil
9503 org-todo-log-states nil)
9504 (setq words (org-split-string value))
9505 (while (setq w (pop words))
9506 (cond
9507 ((setq a (assoc w org-startup-options))
9508 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9509 (set (nth 1 a) (nth 2 a))))
9510 ((setq a (org-extract-log-state-settings w))
9511 (and (member (car a) org-todo-keywords-1)
9512 (push a org-todo-log-states)))))))
9514 (defun org-get-todo-sequence-head (kwd)
9515 "Return the head of the TODO sequence to which KWD belongs.
9516 If KWD is not set, check if there is a text property remembering the
9517 right sequence."
9518 (let (p)
9519 (cond
9520 ((not kwd)
9521 (or (get-text-property (point-at-bol) 'org-todo-head)
9522 (progn
9523 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9524 nil (point-at-eol)))
9525 (get-text-property p 'org-todo-head))))
9526 ((not (member kwd org-todo-keywords-1))
9527 (car org-todo-keywords-1))
9528 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9530 (defun org-fast-todo-selection ()
9531 "Fast TODO keyword selection with single keys.
9532 Returns the new TODO keyword, or nil if no state change should occur."
9533 (let* ((fulltable org-todo-key-alist)
9534 (done-keywords org-done-keywords) ;; needed for the faces.
9535 (maxlen (apply 'max (mapcar
9536 (lambda (x)
9537 (if (stringp (car x)) (string-width (car x)) 0))
9538 fulltable)))
9539 (expert nil)
9540 (fwidth (+ maxlen 3 1 3))
9541 (ncol (/ (- (window-width) 4) fwidth))
9542 tg cnt e c tbl
9543 groups ingroup)
9544 (save-excursion
9545 (save-window-excursion
9546 (if expert
9547 (set-buffer (get-buffer-create " *Org todo*"))
9548 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9549 (erase-buffer)
9550 (org-set-local 'org-done-keywords done-keywords)
9551 (setq tbl fulltable cnt 0)
9552 (while (setq e (pop tbl))
9553 (cond
9554 ((equal e '(:startgroup))
9555 (push '() groups) (setq ingroup t)
9556 (when (not (= cnt 0))
9557 (setq cnt 0)
9558 (insert "\n"))
9559 (insert "{ "))
9560 ((equal e '(:endgroup))
9561 (setq ingroup nil cnt 0)
9562 (insert "}\n"))
9563 ((equal e '(:newline))
9564 (when (not (= cnt 0))
9565 (setq cnt 0)
9566 (insert "\n")
9567 (setq e (car tbl))
9568 (while (equal (car tbl) '(:newline))
9569 (insert "\n")
9570 (setq tbl (cdr tbl)))))
9572 (setq tg (car e) c (cdr e))
9573 (if ingroup (push tg (car groups)))
9574 (setq tg (org-add-props tg nil 'face
9575 (org-get-todo-face tg)))
9576 (if (and (= cnt 0) (not ingroup)) (insert " "))
9577 (insert "[" c "] " tg (make-string
9578 (- fwidth 4 (length tg)) ?\ ))
9579 (when (= (setq cnt (1+ cnt)) ncol)
9580 (insert "\n")
9581 (if ingroup (insert " "))
9582 (setq cnt 0)))))
9583 (insert "\n")
9584 (goto-char (point-min))
9585 (if (not expert) (org-fit-window-to-buffer))
9586 (message "[a-z..]:Set [SPC]:clear")
9587 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9588 (cond
9589 ((or (= c ?\C-g)
9590 (and (= c ?q) (not (rassoc c fulltable))))
9591 (setq quit-flag t))
9592 ((= c ?\ ) nil)
9593 ((setq e (rassoc c fulltable) tg (car e))
9595 (t (setq quit-flag t)))))))
9597 (defun org-entry-is-todo-p ()
9598 (member (org-get-todo-state) org-not-done-keywords))
9600 (defun org-entry-is-done-p ()
9601 (member (org-get-todo-state) org-done-keywords))
9603 (defun org-get-todo-state ()
9604 (save-excursion
9605 (org-back-to-heading t)
9606 (and (looking-at org-todo-line-regexp)
9607 (match-end 2)
9608 (match-string 2))))
9610 (defun org-at-date-range-p (&optional inactive-ok)
9611 "Is the cursor inside a date range?"
9612 (interactive)
9613 (save-excursion
9614 (catch 'exit
9615 (let ((pos (point)))
9616 (skip-chars-backward "^[<\r\n")
9617 (skip-chars-backward "<[")
9618 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9619 (>= (match-end 0) pos)
9620 (throw 'exit t))
9621 (skip-chars-backward "^<[\r\n")
9622 (skip-chars-backward "<[")
9623 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9624 (>= (match-end 0) pos)
9625 (throw 'exit t)))
9626 nil)))
9628 (defun org-get-repeat ()
9629 "Check if there is a deadline/schedule with repeater in this entry."
9630 (save-match-data
9631 (save-excursion
9632 (org-back-to-heading t)
9633 (if (re-search-forward
9634 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9635 (match-string 1)))))
9637 (defvar org-last-changed-timestamp)
9638 (defvar org-last-inserted-timestamp)
9639 (defvar org-log-post-message)
9640 (defvar org-log-note-purpose)
9641 (defvar org-log-note-how)
9642 (defvar org-log-note-extra)
9643 (defun org-auto-repeat-maybe (done-word)
9644 "Check if the current headline contains a repeated deadline/schedule.
9645 If yes, set TODO state back to what it was and change the base date
9646 of repeating deadline/scheduled time stamps to new date.
9647 This function is run automatically after each state change to a DONE state."
9648 ;; last-state is dynamically scoped into this function
9649 (let* ((repeat (org-get-repeat))
9650 (aa (assoc last-state org-todo-kwd-alist))
9651 (interpret (nth 1 aa))
9652 (head (nth 2 aa))
9653 (whata '(("d" . day) ("m" . month) ("y" . year)))
9654 (msg "Entry repeats: ")
9655 (org-log-done nil)
9656 (org-todo-log-states nil)
9657 (nshiftmax 10) (nshift 0)
9658 re type n what ts time)
9659 (when repeat
9660 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9661 (org-todo (if (eq interpret 'type) last-state head))
9662 (org-entry-put nil "LAST_REPEAT" (format-time-string
9663 (org-time-stamp-format t t)))
9664 (when org-log-repeat
9665 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9666 (memq 'org-add-log-note post-command-hook))
9667 ;; OK, we are already setup for some record
9668 (if (eq org-log-repeat 'note)
9669 ;; make sure we take a note, not only a time stamp
9670 (setq org-log-note-how 'note))
9671 ;; Set up for taking a record
9672 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9673 last-state
9674 'findpos org-log-repeat)))
9675 (org-back-to-heading t)
9676 (org-add-planning-info nil nil 'closed)
9677 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9678 org-deadline-time-regexp "\\)\\|\\("
9679 org-ts-regexp "\\)"))
9680 (while (re-search-forward
9681 re (save-excursion (outline-next-heading) (point)) t)
9682 (setq type (if (match-end 1) org-scheduled-string
9683 (if (match-end 3) org-deadline-string "Plain:"))
9684 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9685 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9686 (setq n (string-to-number (match-string 2 ts))
9687 what (match-string 3 ts))
9688 (if (equal what "w") (setq n (* n 7) what "d"))
9689 ;; Preparation, see if we need to modify the start date for the change
9690 (when (match-end 1)
9691 (setq time (save-match-data (org-time-string-to-time ts)))
9692 (cond
9693 ((equal (match-string 1 ts) ".")
9694 ;; Shift starting date to today
9695 (org-timestamp-change
9696 (- (time-to-days (current-time)) (time-to-days time))
9697 'day))
9698 ((equal (match-string 1 ts) "+")
9699 (while (or (= nshift 0)
9700 (<= (time-to-days time) (time-to-days (current-time))))
9701 (when (= (incf nshift) nshiftmax)
9702 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9703 (error "Abort")))
9704 (org-timestamp-change n (cdr (assoc what whata)))
9705 (org-at-timestamp-p t)
9706 (setq ts (match-string 1))
9707 (setq time (save-match-data (org-time-string-to-time ts))))
9708 (org-timestamp-change (- n) (cdr (assoc what whata)))
9709 ;; rematch, so that we have everything in place for the real shift
9710 (org-at-timestamp-p t)
9711 (setq ts (match-string 1))
9712 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9713 (org-timestamp-change n (cdr (assoc what whata)))
9714 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9715 (setq org-log-post-message msg)
9716 (message "%s" msg))))
9718 (defun org-show-todo-tree (arg)
9719 "Make a compact tree which shows all headlines marked with TODO.
9720 The tree will show the lines where the regexp matches, and all higher
9721 headlines above the match.
9722 With a \\[universal-argument] prefix, prompt for a regexp to match.
9723 With a numeric prefix N, construct a sparse tree for the Nth element
9724 of `org-todo-keywords-1'."
9725 (interactive "P")
9726 (let ((case-fold-search nil)
9727 (kwd-re
9728 (cond ((null arg) org-not-done-regexp)
9729 ((equal arg '(4))
9730 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9731 (mapcar 'list org-todo-keywords-1))))
9732 (concat "\\("
9733 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9734 "\\)\\>")))
9735 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9736 (regexp-quote (nth (1- (prefix-numeric-value arg))
9737 org-todo-keywords-1)))
9738 (t (error "Invalid prefix argument: %s" arg)))))
9739 (message "%d TODO entries found"
9740 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9742 (defun org-deadline (&optional remove time)
9743 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9744 With argument REMOVE, remove any deadline from the item.
9745 When TIME is set, it should be an internal time specification, and the
9746 scheduling will use the corresponding date."
9747 (interactive "P")
9748 (if remove
9749 (progn
9750 (org-remove-timestamp-with-keyword org-deadline-string)
9751 (message "Item no longer has a deadline."))
9752 (if (org-get-repeat)
9753 (error "Cannot change deadline on task with repeater, please do that by hand")
9754 (org-add-planning-info 'deadline time 'closed)
9755 (message "Deadline on %s" org-last-inserted-timestamp))))
9757 (defun org-schedule (&optional remove time)
9758 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9759 With argument REMOVE, remove any scheduling date from the item.
9760 When TIME is set, it should be an internal time specification, and the
9761 scheduling will use the corresponding date."
9762 (interactive "P")
9763 (if remove
9764 (progn
9765 (org-remove-timestamp-with-keyword org-scheduled-string)
9766 (message "Item is no longer scheduled."))
9767 (if (org-get-repeat)
9768 (error "Cannot reschedule task with repeater, please do that by hand")
9769 (org-add-planning-info 'scheduled time 'closed)
9770 (message "Scheduled to %s" org-last-inserted-timestamp))))
9772 (defun org-get-scheduled-time (pom &optional inherit)
9773 "Get the scheduled time as a time tuple, of a format suitable
9774 for calling org-schedule with, or if there is no scheduling,
9775 returns nil."
9776 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9777 (when time
9778 (apply 'encode-time (org-parse-time-string time)))))
9780 (defun org-get-deadline-time (pom &optional inherit)
9781 "Get the deadine as a time tuple, of a format suitable for
9782 calling org-deadlin with, or if there is no scheduling, returns
9783 nil."
9784 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9785 (when time
9786 (apply 'encode-time (org-parse-time-string time)))))
9788 (defun org-remove-timestamp-with-keyword (keyword)
9789 "Remove all time stamps with KEYWORD in the current entry."
9790 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9791 beg)
9792 (save-excursion
9793 (org-back-to-heading t)
9794 (setq beg (point))
9795 (org-end-of-subtree t t)
9796 (while (re-search-backward re beg t)
9797 (replace-match "")
9798 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9799 (equal (char-before) ?\ ))
9800 (backward-delete-char 1)
9801 (if (string-match "^[ \t]*$" (buffer-substring
9802 (point-at-bol) (point-at-eol)))
9803 (delete-region (point-at-bol)
9804 (min (point-max) (1+ (point-at-eol))))))))))
9806 (defun org-add-planning-info (what &optional time &rest remove)
9807 "Insert new timestamp with keyword in the line directly after the headline.
9808 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9809 If non is given, the user is prompted for a date.
9810 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9811 be removed."
9812 (interactive)
9813 (let (org-time-was-given org-end-time-was-given ts
9814 end default-time default-input)
9816 (catch 'exit
9817 (when (and (not time) (memq what '(scheduled deadline)))
9818 ;; Try to get a default date/time from existing timestamp
9819 (save-excursion
9820 (org-back-to-heading t)
9821 (setq end (save-excursion (outline-next-heading) (point)))
9822 (when (re-search-forward (if (eq what 'scheduled)
9823 org-scheduled-time-regexp
9824 org-deadline-time-regexp)
9825 end t)
9826 (setq ts (match-string 1)
9827 default-time
9828 (apply 'encode-time (org-parse-time-string ts))
9829 default-input (and ts (org-get-compact-tod ts))))))
9830 (when what
9831 ;; If necessary, get the time from the user
9832 (setq time (or time (org-read-date nil 'to-time nil nil
9833 default-time default-input))))
9835 (when (and org-insert-labeled-timestamps-at-point
9836 (member what '(scheduled deadline)))
9837 (insert
9838 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9839 (org-insert-time-stamp time org-time-was-given
9840 nil nil nil (list org-end-time-was-given))
9841 (setq what nil))
9842 (save-excursion
9843 (save-restriction
9844 (let (col list elt ts buffer-invisibility-spec)
9845 (org-back-to-heading t)
9846 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9847 (goto-char (match-end 1))
9848 (setq col (current-column))
9849 (goto-char (match-end 0))
9850 (if (eobp) (insert "\n") (forward-char 1))
9851 (when (and (not what)
9852 (not (looking-at
9853 (concat "[ \t]*"
9854 org-keyword-time-not-clock-regexp))))
9855 ;; Nothing to add, nothing to remove...... :-)
9856 (throw 'exit nil))
9857 (if (and (not (looking-at outline-regexp))
9858 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9859 "[^\r\n]*"))
9860 (not (equal (match-string 1) org-clock-string)))
9861 (narrow-to-region (match-beginning 0) (match-end 0))
9862 (insert-before-markers "\n")
9863 (backward-char 1)
9864 (narrow-to-region (point) (point))
9865 (and org-adapt-indentation (org-indent-to-column col)))
9866 ;; Check if we have to remove something.
9867 (setq list (cons what remove))
9868 (while list
9869 (setq elt (pop list))
9870 (goto-char (point-min))
9871 (when (or (and (eq elt 'scheduled)
9872 (re-search-forward org-scheduled-time-regexp nil t))
9873 (and (eq elt 'deadline)
9874 (re-search-forward org-deadline-time-regexp nil t))
9875 (and (eq elt 'closed)
9876 (re-search-forward org-closed-time-regexp nil t)))
9877 (replace-match "")
9878 (if (looking-at "--+<[^>]+>") (replace-match ""))
9879 (if (looking-at " +") (replace-match ""))))
9880 (goto-char (point-max))
9881 (when what
9882 (insert
9883 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9884 (cond ((eq what 'scheduled) org-scheduled-string)
9885 ((eq what 'deadline) org-deadline-string)
9886 ((eq what 'closed) org-closed-string))
9887 " ")
9888 (setq ts (org-insert-time-stamp
9889 time
9890 (or org-time-was-given
9891 (and (eq what 'closed) org-log-done-with-time))
9892 (eq what 'closed)
9893 nil nil (list org-end-time-was-given)))
9894 (end-of-line 1))
9895 (goto-char (point-min))
9896 (widen)
9897 (if (and (looking-at "[ \t]+\n")
9898 (equal (char-before) ?\n))
9899 (delete-region (1- (point)) (point-at-eol)))
9900 ts))))))
9902 (defvar org-log-note-marker (make-marker))
9903 (defvar org-log-note-purpose nil)
9904 (defvar org-log-note-state nil)
9905 (defvar org-log-note-previous-state nil)
9906 (defvar org-log-note-how nil)
9907 (defvar org-log-note-extra nil)
9908 (defvar org-log-note-window-configuration nil)
9909 (defvar org-log-note-return-to (make-marker))
9910 (defvar org-log-post-message nil
9911 "Message to be displayed after a log note has been stored.
9912 The auto-repeater uses this.")
9914 (defun org-add-note ()
9915 "Add a note to the current entry.
9916 This is done in the same way as adding a state change note."
9917 (interactive)
9918 (org-add-log-setup 'note nil nil 'findpos nil))
9920 (defvar org-property-end-re)
9921 (defun org-add-log-setup (&optional purpose state prev-state
9922 findpos how &optional extra)
9923 "Set up the post command hook to take a note.
9924 If this is about to TODO state change, the new state is expected in STATE.
9925 When FINDPOS is non-nil, find the correct position for the note in
9926 the current entry. If not, assume that it can be inserted at point.
9927 HOW is an indicator what kind of note should be created.
9928 EXTRA is additional text that will be inserted into the notes buffer."
9929 (let* ((org-log-into-drawer (org-log-into-drawer))
9930 (drawer (cond ((stringp org-log-into-drawer)
9931 org-log-into-drawer)
9932 (org-log-into-drawer "LOGBOOK")
9933 (t nil))))
9934 (save-restriction
9935 (save-excursion
9936 (when findpos
9937 (org-back-to-heading t)
9938 (narrow-to-region (point) (save-excursion
9939 (outline-next-heading) (point)))
9940 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9941 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9942 "[^\r\n]*\\)?"))
9943 (goto-char (match-end 0))
9944 (cond
9945 (drawer
9946 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9947 nil t)
9948 (progn
9949 (goto-char (match-end 0))
9950 (or org-log-states-order-reversed
9951 (and (re-search-forward org-property-end-re nil t)
9952 (goto-char (1- (match-beginning 0))))))
9953 (insert "\n:" drawer ":\n:END:")
9954 (beginning-of-line 0)
9955 (org-indent-line-function)
9956 (beginning-of-line 2)
9957 (org-indent-line-function)
9958 (end-of-line 0)))
9959 ((and org-log-state-notes-insert-after-drawers
9960 (save-excursion
9961 (forward-line) (looking-at org-drawer-regexp)))
9962 (forward-line)
9963 (while (looking-at org-drawer-regexp)
9964 (goto-char (match-end 0))
9965 (re-search-forward org-property-end-re (point-max) t)
9966 (forward-line))
9967 (forward-line -1)))
9968 (unless org-log-states-order-reversed
9969 (and (= (char-after) ?\n) (forward-char 1))
9970 (org-skip-over-state-notes)
9971 (skip-chars-backward " \t\n\r")))
9972 (move-marker org-log-note-marker (point))
9973 (setq org-log-note-purpose purpose
9974 org-log-note-state state
9975 org-log-note-previous-state prev-state
9976 org-log-note-how how
9977 org-log-note-extra extra)
9978 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9980 (defun org-skip-over-state-notes ()
9981 "Skip past the list of State notes in an entry."
9982 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9983 (while (looking-at "[ \t]*- State")
9984 (condition-case nil
9985 (org-next-item)
9986 (error (org-end-of-item)))))
9988 (defun org-add-log-note (&optional purpose)
9989 "Pop up a window for taking a note, and add this note later at point."
9990 (remove-hook 'post-command-hook 'org-add-log-note)
9991 (setq org-log-note-window-configuration (current-window-configuration))
9992 (delete-other-windows)
9993 (move-marker org-log-note-return-to (point))
9994 (switch-to-buffer (marker-buffer org-log-note-marker))
9995 (goto-char org-log-note-marker)
9996 (org-switch-to-buffer-other-window "*Org Note*")
9997 (erase-buffer)
9998 (if (memq org-log-note-how '(time state))
9999 (let (current-prefix-arg) (org-store-log-note))
10000 (let ((org-inhibit-startup t)) (org-mode))
10001 (insert (format "# Insert note for %s.
10002 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10003 (cond
10004 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10005 ((eq org-log-note-purpose 'done) "closed todo item")
10006 ((eq org-log-note-purpose 'state)
10007 (format "state change from \"%s\" to \"%s\""
10008 (or org-log-note-previous-state "")
10009 (or org-log-note-state "")))
10010 ((eq org-log-note-purpose 'note)
10011 "this entry")
10012 (t (error "This should not happen")))))
10013 (if org-log-note-extra (insert org-log-note-extra))
10014 (org-set-local 'org-finish-function 'org-store-log-note)))
10016 (defvar org-note-abort nil) ; dynamically scoped
10017 (defun org-store-log-note ()
10018 "Finish taking a log note, and insert it to where it belongs."
10019 (let ((txt (buffer-string))
10020 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10021 lines ind)
10022 (kill-buffer (current-buffer))
10023 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10024 (setq txt (replace-match "" t t txt)))
10025 (if (string-match "\\s-+\\'" txt)
10026 (setq txt (replace-match "" t t txt)))
10027 (setq lines (org-split-string txt "\n"))
10028 (when (and note (string-match "\\S-" note))
10029 (setq note
10030 (org-replace-escapes
10031 note
10032 (list (cons "%u" (user-login-name))
10033 (cons "%U" user-full-name)
10034 (cons "%t" (format-time-string
10035 (org-time-stamp-format 'long 'inactive)
10036 (current-time)))
10037 (cons "%s" (if org-log-note-state
10038 (concat "\"" org-log-note-state "\"")
10039 ""))
10040 (cons "%S" (if org-log-note-previous-state
10041 (concat "\"" org-log-note-previous-state "\"")
10042 "\"\"")))))
10043 (if lines (setq note (concat note " \\\\")))
10044 (push note lines))
10045 (when (or current-prefix-arg org-note-abort)
10046 (when org-log-into-drawer
10047 (org-remove-empty-drawer-at
10048 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10049 org-log-note-marker))
10050 (setq lines nil))
10051 (when lines
10052 (save-excursion
10053 (set-buffer (marker-buffer org-log-note-marker))
10054 (save-excursion
10055 (goto-char org-log-note-marker)
10056 (move-marker org-log-note-marker nil)
10057 (end-of-line 1)
10058 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10059 (insert "- " (pop lines))
10060 (org-indent-line-function)
10061 (beginning-of-line 1)
10062 (looking-at "[ \t]*")
10063 (setq ind (concat (match-string 0) " "))
10064 (end-of-line 1)
10065 (while lines (insert "\n" ind (pop lines)))
10066 (message "Note stored")
10067 (org-back-to-heading t)
10068 (org-cycle-hide-drawers 'children)))))
10069 (set-window-configuration org-log-note-window-configuration)
10070 (with-current-buffer (marker-buffer org-log-note-return-to)
10071 (goto-char org-log-note-return-to))
10072 (move-marker org-log-note-return-to nil)
10073 (and org-log-post-message (message "%s" org-log-post-message)))
10075 (defun org-remove-empty-drawer-at (drawer pos)
10076 "Remove an emptyr DARWER drawer at position POS.
10077 POS may also be a marker."
10078 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10079 (save-excursion
10080 (save-restriction
10081 (widen)
10082 (goto-char pos)
10083 (if (org-in-regexp
10084 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10085 (replace-match ""))))))
10087 (defun org-sparse-tree (&optional arg)
10088 "Create a sparse tree, prompt for the details.
10089 This command can create sparse trees. You first need to select the type
10090 of match used to create the tree:
10092 t Show entries with a specific TODO keyword.
10093 m Show entries selected by a tags/property match.
10094 p Enter a property name and its value (both with completion on existing
10095 names/values) and show entries with that property.
10096 r Show entries matching a regular expression.
10097 d Show deadlines due within `org-deadline-warning-days'.
10098 b Show deadlines and scheduled items before a date.
10099 a Show deadlines and scheduled items after a date."
10100 (interactive "P")
10101 (let (ans kwd value)
10102 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10103 (setq ans (read-char-exclusive))
10104 (cond
10105 ((equal ans ?d)
10106 (call-interactively 'org-check-deadlines))
10107 ((equal ans ?b)
10108 (call-interactively 'org-check-before-date))
10109 ((equal ans ?a)
10110 (call-interactively 'org-check-after-date))
10111 ((equal ans ?t)
10112 (org-show-todo-tree '(4)))
10113 ((member ans '(?T ?m))
10114 (call-interactively 'org-match-sparse-tree))
10115 ((member ans '(?p ?P))
10116 (setq kwd (org-ido-completing-read "Property: "
10117 (mapcar 'list (org-buffer-property-keys))))
10118 (setq value (org-ido-completing-read "Value: "
10119 (mapcar 'list (org-property-values kwd))))
10120 (unless (string-match "\\`{.*}\\'" value)
10121 (setq value (concat "\"" value "\"")))
10122 (org-match-sparse-tree arg (concat kwd "=" value)))
10123 ((member ans '(?r ?R ?/))
10124 (call-interactively 'org-occur))
10125 (t (error "No such sparse tree command \"%c\"" ans)))))
10127 (defvar org-occur-highlights nil
10128 "List of overlays used for occur matches.")
10129 (make-variable-buffer-local 'org-occur-highlights)
10130 (defvar org-occur-parameters nil
10131 "Parameters of the active org-occur calls.
10132 This is a list, each call to org-occur pushes as cons cell,
10133 containing the regular expression and the callback, onto the list.
10134 The list can contain several entries if `org-occur' has been called
10135 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10136 will only contain one set of parameters. When the highlights are
10137 removed (for example with `C-c C-c', or with the next edit (depending
10138 on `org-remove-highlights-with-change'), this variable is emptied
10139 as well.")
10140 (make-variable-buffer-local 'org-occur-parameters)
10142 (defun org-occur (regexp &optional keep-previous callback)
10143 "Make a compact tree which shows all matches of REGEXP.
10144 The tree will show the lines where the regexp matches, and all higher
10145 headlines above the match. It will also show the heading after the match,
10146 to make sure editing the matching entry is easy.
10147 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10148 call to `org-occur' will be kept, to allow stacking of calls to this
10149 command.
10150 If CALLBACK is non-nil, it is a function which is called to confirm
10151 that the match should indeed be shown."
10152 (interactive "sRegexp: \nP")
10153 (unless keep-previous
10154 (org-remove-occur-highlights nil nil t))
10155 (push (cons regexp callback) org-occur-parameters)
10156 (let ((cnt 0))
10157 (save-excursion
10158 (goto-char (point-min))
10159 (if (or (not keep-previous) ; do not want to keep
10160 (not org-occur-highlights)) ; no previous matches
10161 ;; hide everything
10162 (org-overview))
10163 (while (re-search-forward regexp nil t)
10164 (when (or (not callback)
10165 (save-match-data (funcall callback)))
10166 (setq cnt (1+ cnt))
10167 (when org-highlight-sparse-tree-matches
10168 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10169 (org-show-context 'occur-tree))))
10170 (when org-remove-highlights-with-change
10171 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10172 nil 'local))
10173 (unless org-sparse-tree-open-archived-trees
10174 (org-hide-archived-subtrees (point-min) (point-max)))
10175 (run-hooks 'org-occur-hook)
10176 (if (interactive-p)
10177 (message "%d match(es) for regexp %s" cnt regexp))
10178 cnt))
10180 (defun org-show-context (&optional key)
10181 "Make sure point and context and visible.
10182 How much context is shown depends upon the variables
10183 `org-show-hierarchy-above', `org-show-following-heading'. and
10184 `org-show-siblings'."
10185 (let ((heading-p (org-on-heading-p t))
10186 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10187 (following-p (org-get-alist-option org-show-following-heading key))
10188 (entry-p (org-get-alist-option org-show-entry-below key))
10189 (siblings-p (org-get-alist-option org-show-siblings key)))
10190 (catch 'exit
10191 ;; Show heading or entry text
10192 (if (and heading-p (not entry-p))
10193 (org-flag-heading nil) ; only show the heading
10194 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10195 (org-show-hidden-entry))) ; show entire entry
10196 (when following-p
10197 ;; Show next sibling, or heading below text
10198 (save-excursion
10199 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10200 (org-flag-heading nil))))
10201 (when siblings-p (org-show-siblings))
10202 (when hierarchy-p
10203 ;; show all higher headings, possibly with siblings
10204 (save-excursion
10205 (while (and (condition-case nil
10206 (progn (org-up-heading-all 1) t)
10207 (error nil))
10208 (not (bobp)))
10209 (org-flag-heading nil)
10210 (when siblings-p (org-show-siblings))))))))
10212 (defun org-reveal (&optional siblings)
10213 "Show current entry, hierarchy above it, and the following headline.
10214 This can be used to show a consistent set of context around locations
10215 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10216 not t for the search context.
10218 With optional argument SIBLINGS, on each level of the hierarchy all
10219 siblings are shown. This repairs the tree structure to what it would
10220 look like when opened with hierarchical calls to `org-cycle'."
10221 (interactive "P")
10222 (let ((org-show-hierarchy-above t)
10223 (org-show-following-heading t)
10224 (org-show-siblings (if siblings t org-show-siblings)))
10225 (org-show-context nil)))
10227 (defun org-highlight-new-match (beg end)
10228 "Highlight from BEG to END and mark the highlight is an occur headline."
10229 (let ((ov (org-make-overlay beg end)))
10230 (org-overlay-put ov 'face 'secondary-selection)
10231 (push ov org-occur-highlights)))
10233 (defun org-remove-occur-highlights (&optional beg end noremove)
10234 "Remove the occur highlights from the buffer.
10235 BEG and END are ignored. If NOREMOVE is nil, remove this function
10236 from the `before-change-functions' in the current buffer."
10237 (interactive)
10238 (unless org-inhibit-highlight-removal
10239 (mapc 'org-delete-overlay org-occur-highlights)
10240 (setq org-occur-highlights nil)
10241 (setq org-occur-parameters nil)
10242 (unless noremove
10243 (remove-hook 'before-change-functions
10244 'org-remove-occur-highlights 'local))))
10246 ;;;; Priorities
10248 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10249 "Regular expression matching the priority indicator.")
10251 (defvar org-remove-priority-next-time nil)
10253 (defun org-priority-up ()
10254 "Increase the priority of the current item."
10255 (interactive)
10256 (org-priority 'up))
10258 (defun org-priority-down ()
10259 "Decrease the priority of the current item."
10260 (interactive)
10261 (org-priority 'down))
10263 (defun org-priority (&optional action)
10264 "Change the priority of an item by ARG.
10265 ACTION can be `set', `up', `down', or a character."
10266 (interactive)
10267 (unless org-enable-priority-commands
10268 (error "Priority commands are disabled"))
10269 (setq action (or action 'set))
10270 (let (current new news have remove)
10271 (save-excursion
10272 (org-back-to-heading t)
10273 (if (looking-at org-priority-regexp)
10274 (setq current (string-to-char (match-string 2))
10275 have t)
10276 (setq current org-default-priority))
10277 (cond
10278 ((or (eq action 'set)
10279 (if (featurep 'xemacs) (characterp action) (integerp action)))
10280 (if (not (eq action 'set))
10281 (setq new action)
10282 (message "Priority %c-%c, SPC to remove: "
10283 org-highest-priority org-lowest-priority)
10284 (setq new (read-char-exclusive)))
10285 (if (and (= (upcase org-highest-priority) org-highest-priority)
10286 (= (upcase org-lowest-priority) org-lowest-priority))
10287 (setq new (upcase new)))
10288 (cond ((equal new ?\ ) (setq remove t))
10289 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10290 (error "Priority must be between `%c' and `%c'"
10291 org-highest-priority org-lowest-priority))))
10292 ((eq action 'up)
10293 (if (and (not have) (eq last-command this-command))
10294 (setq new org-lowest-priority)
10295 (setq new (if (and org-priority-start-cycle-with-default (not have))
10296 org-default-priority (1- current)))))
10297 ((eq action 'down)
10298 (if (and (not have) (eq last-command this-command))
10299 (setq new org-highest-priority)
10300 (setq new (if (and org-priority-start-cycle-with-default (not have))
10301 org-default-priority (1+ current)))))
10302 (t (error "Invalid action")))
10303 (if (or (< (upcase new) org-highest-priority)
10304 (> (upcase new) org-lowest-priority))
10305 (setq remove t))
10306 (setq news (format "%c" new))
10307 (if have
10308 (if remove
10309 (replace-match "" t t nil 1)
10310 (replace-match news t t nil 2))
10311 (if remove
10312 (error "No priority cookie found in line")
10313 (let ((case-fold-search nil))
10314 (looking-at org-todo-line-regexp))
10315 (if (match-end 2)
10316 (progn
10317 (goto-char (match-end 2))
10318 (insert " [#" news "]"))
10319 (goto-char (match-beginning 3))
10320 (insert "[#" news "] ")))))
10321 (org-preserve-lc (org-set-tags nil 'align))
10322 (if remove
10323 (message "Priority removed")
10324 (message "Priority of current item set to %s" news))))
10327 (defun org-get-priority (s)
10328 "Find priority cookie and return priority."
10329 (save-match-data
10330 (if (not (string-match org-priority-regexp s))
10331 (* 1000 (- org-lowest-priority org-default-priority))
10332 (* 1000 (- org-lowest-priority
10333 (string-to-char (match-string 2 s)))))))
10335 ;;;; Tags
10337 (defvar org-agenda-archives-mode)
10338 (defvar org-map-continue-from nil
10339 "Position from where mapping should continue.
10340 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10342 (defvar org-scanner-tags nil
10343 "The current tag list while the tags scanner is running.")
10344 (defvar org-trust-scanner-tags nil
10345 "Should `org-get-tags-at' use the tags fro the scanner.
10346 This is for internal dynamical scoping only.
10347 When this is non-nil, the function `org-get-tags-at' will return the value
10348 of `org-scanner-tags' instead of building the list by itself. This
10349 can lead to large speed-ups when the tags scanner is used in a file with
10350 many entries, and when the list of tags is retrieved, for example to
10351 obtain a list of properties. Building the tags list for each entry in such
10352 a file becomes an N^2 operation - but with this variable set, it scales
10353 as N.")
10355 (defun org-scan-tags (action matcher &optional todo-only)
10356 "Scan headline tags with inheritance and produce output ACTION.
10358 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10359 or `agenda' to produce an entry list for an agenda view. It can also be
10360 a Lisp form or a function that should be called at each matched headline, in
10361 this case the return value is a list of all return values from these calls.
10363 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10364 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10365 only lines with a TODO keyword are included in the output."
10366 (require 'org-agenda)
10367 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10368 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10369 (org-re
10370 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10371 (props (list 'face 'default
10372 'done-face 'org-agenda-done
10373 'undone-face 'default
10374 'mouse-face 'highlight
10375 'org-not-done-regexp org-not-done-regexp
10376 'org-todo-regexp org-todo-regexp
10377 'keymap org-agenda-keymap
10378 'help-echo
10379 (format "mouse-2 or RET jump to org file %s"
10380 (abbreviate-file-name
10381 (or (buffer-file-name (buffer-base-buffer))
10382 (buffer-name (buffer-base-buffer)))))))
10383 (case-fold-search nil)
10384 (org-map-continue-from nil)
10385 lspos tags tags-list
10386 (tags-alist (list (cons 0 org-file-tags)))
10387 (llast 0) rtn rtn1 level category i txt
10388 todo marker entry priority)
10389 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10390 (setq action (list 'lambda nil action)))
10391 (save-excursion
10392 (goto-char (point-min))
10393 (when (eq action 'sparse-tree)
10394 (org-overview)
10395 (org-remove-occur-highlights))
10396 (while (re-search-forward re nil t)
10397 (catch :skip
10398 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10399 tags (if (match-end 4) (org-match-string-no-properties 4)))
10400 (goto-char (setq lspos (match-beginning 0)))
10401 (setq level (org-reduced-level (funcall outline-level))
10402 category (org-get-category))
10403 (setq i llast llast level)
10404 ;; remove tag lists from same and sublevels
10405 (while (>= i level)
10406 (when (setq entry (assoc i tags-alist))
10407 (setq tags-alist (delete entry tags-alist)))
10408 (setq i (1- i)))
10409 ;; add the next tags
10410 (when tags
10411 (setq tags (org-split-string tags ":")
10412 tags-alist
10413 (cons (cons level tags) tags-alist)))
10414 ;; compile tags for current headline
10415 (setq tags-list
10416 (if org-use-tag-inheritance
10417 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10418 tags)
10419 org-scanner-tags tags-list)
10420 (when org-use-tag-inheritance
10421 (setcdr (car tags-alist)
10422 (mapcar (lambda (x)
10423 (setq x (copy-sequence x))
10424 (org-add-prop-inherited x))
10425 (cdar tags-alist))))
10426 (when (and tags org-use-tag-inheritance
10427 (or (not (eq t org-use-tag-inheritance))
10428 org-tags-exclude-from-inheritance))
10429 ;; selective inheritance, remove uninherited ones
10430 (setcdr (car tags-alist)
10431 (org-remove-uniherited-tags (cdar tags-alist))))
10432 (when (and (or (not todo-only)
10433 (and (member todo org-not-done-keywords)
10434 (or (not org-agenda-tags-todo-honor-ignore-options)
10435 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10436 (let ((case-fold-search t)) (eval matcher))
10438 (not (member org-archive-tag tags-list))
10439 ;; we have an archive tag, should we use this anyway?
10440 (or (not org-agenda-skip-archived-trees)
10441 (and (eq action 'agenda) org-agenda-archives-mode))))
10442 (unless (eq action 'sparse-tree) (org-agenda-skip))
10444 ;; select this headline
10446 (cond
10447 ((eq action 'sparse-tree)
10448 (and org-highlight-sparse-tree-matches
10449 (org-get-heading) (match-end 0)
10450 (org-highlight-new-match
10451 (match-beginning 0) (match-beginning 1)))
10452 (org-show-context 'tags-tree))
10453 ((eq action 'agenda)
10454 (setq txt (org-format-agenda-item
10456 (concat
10457 (if (eq org-tags-match-list-sublevels 'indented)
10458 (make-string (1- level) ?.) "")
10459 (org-get-heading))
10460 category
10461 tags-list
10463 priority (org-get-priority txt))
10464 (goto-char lspos)
10465 (setq marker (org-agenda-new-marker))
10466 (org-add-props txt props
10467 'org-marker marker 'org-hd-marker marker 'org-category category
10468 'todo-state todo
10469 'priority priority 'type "tagsmatch")
10470 (push txt rtn))
10471 ((functionp action)
10472 (setq org-map-continue-from nil)
10473 (save-excursion
10474 (setq rtn1 (funcall action))
10475 (push rtn1 rtn)))
10476 (t (error "Invalid action")))
10478 ;; if we are to skip sublevels, jump to end of subtree
10479 (unless org-tags-match-list-sublevels
10480 (org-end-of-subtree t)
10481 (backward-char 1))))
10482 ;; Get the correct position from where to continue
10483 (if org-map-continue-from
10484 (goto-char org-map-continue-from)
10485 (and (= (point) lspos) (end-of-line 1)))))
10486 (when (and (eq action 'sparse-tree)
10487 (not org-sparse-tree-open-archived-trees))
10488 (org-hide-archived-subtrees (point-min) (point-max)))
10489 (nreverse rtn)))
10491 (defun org-remove-uniherited-tags (tags)
10492 "Remove all tags that are not inherited from the list TAGS."
10493 (cond
10494 ((eq org-use-tag-inheritance t)
10495 (if org-tags-exclude-from-inheritance
10496 (org-delete-all org-tags-exclude-from-inheritance tags)
10497 tags))
10498 ((not org-use-tag-inheritance) nil)
10499 ((stringp org-use-tag-inheritance)
10500 (delq nil (mapcar
10501 (lambda (x)
10502 (if (and (string-match org-use-tag-inheritance x)
10503 (not (member x org-tags-exclude-from-inheritance)))
10504 x nil))
10505 tags)))
10506 ((listp org-use-tag-inheritance)
10507 (delq nil (mapcar
10508 (lambda (x)
10509 (if (member x org-use-tag-inheritance) x nil))
10510 tags)))))
10512 (defvar todo-only) ;; dynamically scoped
10514 (defun org-match-sparse-tree (&optional todo-only match)
10515 "Create a sparse tree according to tags string MATCH.
10516 MATCH can contain positive and negative selection of tags, like
10517 \"+WORK+URGENT-WITHBOSS\".
10518 If optional argument TODO-ONLY is non-nil, only select lines that are
10519 also TODO lines."
10520 (interactive "P")
10521 (org-prepare-agenda-buffers (list (current-buffer)))
10522 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10524 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10526 (defvar org-cached-props nil)
10527 (defun org-cached-entry-get (pom property)
10528 (if (or (eq t org-use-property-inheritance)
10529 (and (stringp org-use-property-inheritance)
10530 (string-match org-use-property-inheritance property))
10531 (and (listp org-use-property-inheritance)
10532 (member property org-use-property-inheritance)))
10533 ;; Caching is not possible, check it directly
10534 (org-entry-get pom property 'inherit)
10535 ;; Get all properties, so that we can do complicated checks easily
10536 (cdr (assoc property (or org-cached-props
10537 (setq org-cached-props
10538 (org-entry-properties pom)))))))
10540 (defun org-global-tags-completion-table (&optional files)
10541 "Return the list of all tags in all agenda buffer/files."
10542 (save-excursion
10543 (org-uniquify
10544 (delq nil
10545 (apply 'append
10546 (mapcar
10547 (lambda (file)
10548 (set-buffer (find-file-noselect file))
10549 (append (org-get-buffer-tags)
10550 (mapcar (lambda (x) (if (stringp (car-safe x))
10551 (list (car-safe x)) nil))
10552 org-tag-alist)))
10553 (if (and files (car files))
10554 files
10555 (org-agenda-files))))))))
10557 (defun org-make-tags-matcher (match)
10558 "Create the TAGS//TODO matcher form for the selection string MATCH."
10559 ;; todo-only is scoped dynamically into this function, and the function
10560 ;; may change it if the matcher asks for it.
10561 (unless match
10562 ;; Get a new match request, with completion
10563 (let ((org-last-tags-completion-table
10564 (org-global-tags-completion-table)))
10565 (setq match (org-completing-read-no-ido
10566 "Match: " 'org-tags-completion-function nil nil nil
10567 'org-tags-history))))
10569 ;; Parse the string and create a lisp form
10570 (let ((match0 match)
10571 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10572 minus tag mm
10573 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10574 orterms term orlist re-p str-p level-p level-op time-p
10575 prop-p pn pv po cat-p gv rest)
10576 (if (string-match "/+" match)
10577 ;; match contains also a todo-matching request
10578 (progn
10579 (setq tagsmatch (substring match 0 (match-beginning 0))
10580 todomatch (substring match (match-end 0)))
10581 (if (string-match "^!" todomatch)
10582 (setq todo-only t todomatch (substring todomatch 1)))
10583 (if (string-match "^\\s-*$" todomatch)
10584 (setq todomatch nil)))
10585 ;; only matching tags
10586 (setq tagsmatch match todomatch nil))
10588 ;; Make the tags matcher
10589 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10590 (setq tagsmatcher t)
10591 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10592 (while (setq term (pop orterms))
10593 (while (and (equal (substring term -1) "\\") orterms)
10594 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10595 (while (string-match re term)
10596 (setq rest (substring term (match-end 0))
10597 minus (and (match-end 1)
10598 (equal (match-string 1 term) "-"))
10599 tag (match-string 2 term)
10600 re-p (equal (string-to-char tag) ?{)
10601 level-p (match-end 4)
10602 prop-p (match-end 5)
10603 mm (cond
10604 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10605 (level-p
10606 (setq level-op (org-op-to-function (match-string 3 term)))
10607 `(,level-op level ,(string-to-number
10608 (match-string 4 term))))
10609 (prop-p
10610 (setq pn (match-string 5 term)
10611 po (match-string 6 term)
10612 pv (match-string 7 term)
10613 cat-p (equal pn "CATEGORY")
10614 re-p (equal (string-to-char pv) ?{)
10615 str-p (equal (string-to-char pv) ?\")
10616 time-p (save-match-data
10617 (string-match "^\"[[<].*[]>]\"$" pv))
10618 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10619 (if time-p (setq pv (org-matcher-time pv)))
10620 (setq po (org-op-to-function po (if time-p 'time str-p)))
10621 (cond
10622 ((equal pn "CATEGORY")
10623 (setq gv '(get-text-property (point) 'org-category)))
10624 ((equal pn "TODO")
10625 (setq gv 'todo))
10627 (setq gv `(org-cached-entry-get nil ,pn))))
10628 (if re-p
10629 (if (eq po 'org<>)
10630 `(not (string-match ,pv (or ,gv "")))
10631 `(string-match ,pv (or ,gv "")))
10632 (if str-p
10633 `(,po (or ,gv "") ,pv)
10634 `(,po (string-to-number (or ,gv ""))
10635 ,(string-to-number pv) ))))
10636 (t `(member ,tag tags-list)))
10637 mm (if minus (list 'not mm) mm)
10638 term rest)
10639 (push mm tagsmatcher))
10640 (push (if (> (length tagsmatcher) 1)
10641 (cons 'and tagsmatcher)
10642 (car tagsmatcher))
10643 orlist)
10644 (setq tagsmatcher nil))
10645 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10646 (setq tagsmatcher
10647 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10648 ;; Make the todo matcher
10649 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10650 (setq todomatcher t)
10651 (setq orterms (org-split-string todomatch "|") orlist nil)
10652 (while (setq term (pop orterms))
10653 (while (string-match re term)
10654 (setq minus (and (match-end 1)
10655 (equal (match-string 1 term) "-"))
10656 kwd (match-string 2 term)
10657 re-p (equal (string-to-char kwd) ?{)
10658 term (substring term (match-end 0))
10659 mm (if re-p
10660 `(string-match ,(substring kwd 1 -1) todo)
10661 (list 'equal 'todo kwd))
10662 mm (if minus (list 'not mm) mm))
10663 (push mm todomatcher))
10664 (push (if (> (length todomatcher) 1)
10665 (cons 'and todomatcher)
10666 (car todomatcher))
10667 orlist)
10668 (setq todomatcher nil))
10669 (setq todomatcher (if (> (length orlist) 1)
10670 (cons 'or orlist) (car orlist))))
10672 ;; Return the string and lisp forms of the matcher
10673 (setq matcher (if todomatcher
10674 (list 'and tagsmatcher todomatcher)
10675 tagsmatcher))
10676 (cons match0 matcher)))
10678 (defun org-op-to-function (op &optional stringp)
10679 "Turn an operator into the appropriate function."
10680 (setq op
10681 (cond
10682 ((equal op "<" ) '(< string< org-time<))
10683 ((equal op ">" ) '(> org-string> org-time>))
10684 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10685 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10686 ((member op '("=" "==")) '(= string= org-time=))
10687 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10688 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10690 (defun org<> (a b) (not (= a b)))
10691 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10692 (defun org-string>= (a b) (not (string< a b)))
10693 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10694 (defun org-string<> (a b) (not (string= a b)))
10695 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10696 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10697 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10698 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10699 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10700 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10701 (defun org-2ft (s)
10702 "Convert S to a floating point time.
10703 If S is already a number, just return it. If it is a string, parse
10704 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10705 (cond
10706 ((numberp s) s)
10707 ((stringp s)
10708 (condition-case nil
10709 (float-time (apply 'encode-time (org-parse-time-string s)))
10710 (error 0.)))
10711 (t 0.)))
10713 (defun org-time-today ()
10714 "Time in seconds today at 0:00.
10715 Returns the float number of seconds since the beginning of the
10716 epoch to the beginning of today (00:00)."
10717 (float-time (apply 'encode-time
10718 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10720 (defun org-matcher-time (s)
10721 "Interpret a time comparison value."
10722 (save-match-data
10723 (cond
10724 ((string= s "<now>") (float-time))
10725 ((string= s "<today>") (org-time-today))
10726 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10727 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10728 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10729 (+ (org-time-today)
10730 (* (string-to-number (match-string 1 s))
10731 (cdr (assoc (match-string 2 s)
10732 '(("d" . 86400.0) ("w" . 604800.0)
10733 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10734 (t (org-2ft s)))))
10736 (defun org-match-any-p (re list)
10737 "Does re match any element of list?"
10738 (setq list (mapcar (lambda (x) (string-match re x)) list))
10739 (delq nil list))
10741 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10742 (defvar org-tags-overlay (org-make-overlay 1 1))
10743 (org-detach-overlay org-tags-overlay)
10745 (defun org-get-local-tags-at (&optional pos)
10746 "Get a list of tags defined in the current headline."
10747 (org-get-tags-at pos 'local))
10749 (defun org-get-local-tags ()
10750 "Get a list of tags defined in the current headline."
10751 (org-get-tags-at nil 'local))
10753 (defun org-get-tags-at (&optional pos local)
10754 "Get a list of all headline tags applicable at POS.
10755 POS defaults to point. If tags are inherited, the list contains
10756 the targets in the same sequence as the headlines appear, i.e.
10757 the tags of the current headline come last.
10758 When LOCAL is non-nil, only return tags from the current headline,
10759 ignore inherited ones."
10760 (interactive)
10761 (if (and org-trust-scanner-tags
10762 (or (not pos) (equal pos (point)))
10763 (not local))
10764 org-scanner-tags
10765 (let (tags ltags lastpos parent)
10766 (save-excursion
10767 (save-restriction
10768 (widen)
10769 (goto-char (or pos (point)))
10770 (save-match-data
10771 (catch 'done
10772 (condition-case nil
10773 (progn
10774 (org-back-to-heading t)
10775 (while (not (equal lastpos (point)))
10776 (setq lastpos (point))
10777 (when (looking-at
10778 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10779 (setq ltags (org-split-string
10780 (org-match-string-no-properties 1) ":"))
10781 (when parent
10782 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10783 (setq tags (append
10784 (if parent
10785 (org-remove-uniherited-tags ltags)
10786 ltags)
10787 tags)))
10788 (or org-use-tag-inheritance (throw 'done t))
10789 (if local (throw 'done t))
10790 (or (org-up-heading-safe) (error nil))
10791 (setq parent t)))
10792 (error nil)))))
10793 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10795 (defun org-add-prop-inherited (s)
10796 (add-text-properties 0 (length s) '(inherited t) s)
10799 (defun org-toggle-tag (tag &optional onoff)
10800 "Toggle the tag TAG for the current line.
10801 If ONOFF is `on' or `off', don't toggle but set to this state."
10802 (let (res current)
10803 (save-excursion
10804 (org-back-to-heading t)
10805 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10806 (point-at-eol) t)
10807 (progn
10808 (setq current (match-string 1))
10809 (replace-match ""))
10810 (setq current ""))
10811 (setq current (nreverse (org-split-string current ":")))
10812 (cond
10813 ((eq onoff 'on)
10814 (setq res t)
10815 (or (member tag current) (push tag current)))
10816 ((eq onoff 'off)
10817 (or (not (member tag current)) (setq current (delete tag current))))
10818 (t (if (member tag current)
10819 (setq current (delete tag current))
10820 (setq res t)
10821 (push tag current))))
10822 (end-of-line 1)
10823 (if current
10824 (progn
10825 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10826 (org-set-tags nil t))
10827 (delete-horizontal-space))
10828 (run-hooks 'org-after-tags-change-hook))
10829 res))
10831 (defun org-align-tags-here (to-col)
10832 ;; Assumes that this is a headline
10833 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10834 (beginning-of-line 1)
10835 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10836 (< pos (match-beginning 2)))
10837 (progn
10838 (setq tags-l (- (match-end 2) (match-beginning 2)))
10839 (goto-char (match-beginning 1))
10840 (insert " ")
10841 (delete-region (point) (1+ (match-beginning 2)))
10842 (setq ncol (max (1+ (current-column))
10843 (1+ col)
10844 (if (> to-col 0)
10845 to-col
10846 (- (abs to-col) tags-l))))
10847 (setq p (point))
10848 (insert (make-string (- ncol (current-column)) ?\ ))
10849 (setq ncol (current-column))
10850 (when indent-tabs-mode (tabify p (point-at-eol)))
10851 (org-move-to-column (min ncol col) t))
10852 (goto-char pos))))
10854 (defun org-set-tags-command (&optional arg just-align)
10855 "Call the set-tags command for the current entry."
10856 (interactive "P")
10857 (if (org-on-heading-p)
10858 (org-set-tags arg just-align)
10859 (save-excursion
10860 (org-back-to-heading t)
10861 (org-set-tags arg just-align))))
10863 (defun org-set-tags (&optional arg just-align)
10864 "Set the tags for the current headline.
10865 With prefix ARG, realign all tags in headings in the current buffer."
10866 (interactive "P")
10867 (let* ((re (concat "^" outline-regexp))
10868 (current (org-get-tags-string))
10869 (col (current-column))
10870 (org-setting-tags t)
10871 table current-tags inherited-tags ; computed below when needed
10872 tags p0 c0 c1 rpl)
10873 (if arg
10874 (save-excursion
10875 (goto-char (point-min))
10876 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10877 (while (re-search-forward re nil t)
10878 (org-set-tags nil t)
10879 (end-of-line 1)))
10880 (message "All tags realigned to column %d" org-tags-column))
10881 (if just-align
10882 (setq tags current)
10883 ;; Get a new set of tags from the user
10884 (save-excursion
10885 (setq table (append org-tag-persistent-alist
10886 (or org-tag-alist (org-get-buffer-tags)))
10887 org-last-tags-completion-table table
10888 current-tags (org-split-string current ":")
10889 inherited-tags (nreverse
10890 (nthcdr (length current-tags)
10891 (nreverse (org-get-tags-at))))
10892 tags
10893 (if (or (eq t org-use-fast-tag-selection)
10894 (and org-use-fast-tag-selection
10895 (delq nil (mapcar 'cdr table))))
10896 (org-fast-tag-selection
10897 current-tags inherited-tags table
10898 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10899 (let ((org-add-colon-after-tag-completion t))
10900 (org-trim
10901 (org-without-partial-completion
10902 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10903 nil nil current 'org-tags-history)))))))
10904 (while (string-match "[-+&]+" tags)
10905 ;; No boolean logic, just a list
10906 (setq tags (replace-match ":" t t tags))))
10908 (if (string-match "\\`[\t ]*\\'" tags)
10909 (setq tags "")
10910 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10911 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10913 ;; Insert new tags at the correct column
10914 (beginning-of-line 1)
10915 (cond
10916 ((and (equal current "") (equal tags "")))
10917 ((re-search-forward
10918 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10919 (point-at-eol) t)
10920 (if (equal tags "")
10921 (setq rpl "")
10922 (goto-char (match-beginning 0))
10923 (setq c0 (current-column) p0 (point)
10924 c1 (max (1+ c0) (if (> org-tags-column 0)
10925 org-tags-column
10926 (- (- org-tags-column) (length tags))))
10927 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10928 (replace-match rpl t t)
10929 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10930 tags)
10931 (t (error "Tags alignment failed")))
10932 (org-move-to-column col)
10933 (unless just-align
10934 (run-hooks 'org-after-tags-change-hook)))))
10936 (defun org-change-tag-in-region (beg end tag off)
10937 "Add or remove TAG for each entry in the region.
10938 This works in the agenda, and also in an org-mode buffer."
10939 (interactive
10940 (list (region-beginning) (region-end)
10941 (let ((org-last-tags-completion-table
10942 (if (org-mode-p)
10943 (org-get-buffer-tags)
10944 (org-global-tags-completion-table))))
10945 (org-ido-completing-read
10946 "Tag: " 'org-tags-completion-function nil nil nil
10947 'org-tags-history))
10948 (progn
10949 (message "[s]et or [r]emove? ")
10950 (equal (read-char-exclusive) ?r))))
10951 (if (fboundp 'deactivate-mark) (deactivate-mark))
10952 (let ((agendap (equal major-mode 'org-agenda-mode))
10953 l1 l2 m buf pos newhead (cnt 0))
10954 (goto-char end)
10955 (setq l2 (1- (org-current-line)))
10956 (goto-char beg)
10957 (setq l1 (org-current-line))
10958 (loop for l from l1 to l2 do
10959 (goto-line l)
10960 (setq m (get-text-property (point) 'org-hd-marker))
10961 (when (or (and (org-mode-p) (org-on-heading-p))
10962 (and agendap m))
10963 (setq buf (if agendap (marker-buffer m) (current-buffer))
10964 pos (if agendap m (point)))
10965 (with-current-buffer buf
10966 (save-excursion
10967 (save-restriction
10968 (goto-char pos)
10969 (setq cnt (1+ cnt))
10970 (org-toggle-tag tag (if off 'off 'on))
10971 (setq newhead (org-get-heading)))))
10972 (and agendap (org-agenda-change-all-lines newhead m))))
10973 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10975 (defun org-tags-completion-function (string predicate &optional flag)
10976 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10977 (confirm (lambda (x) (stringp (car x)))))
10978 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10979 (setq s1 (match-string 1 string)
10980 s2 (match-string 2 string))
10981 (setq s1 "" s2 string))
10982 (cond
10983 ((eq flag nil)
10984 ;; try completion
10985 (setq rtn (try-completion s2 ctable confirm))
10986 (if (stringp rtn)
10987 (setq rtn
10988 (concat s1 s2 (substring rtn (length s2))
10989 (if (and org-add-colon-after-tag-completion
10990 (assoc rtn ctable))
10991 ":" ""))))
10992 rtn)
10993 ((eq flag t)
10994 ;; all-completions
10995 (all-completions s2 ctable confirm)
10997 ((eq flag 'lambda)
10998 ;; exact match?
10999 (assoc s2 ctable)))
11002 (defun org-fast-tag-insert (kwd tags face &optional end)
11003 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11004 (insert (format "%-12s" (concat kwd ":"))
11005 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11006 (or end "")))
11008 (defun org-fast-tag-show-exit (flag)
11009 (save-excursion
11010 (goto-line 3)
11011 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11012 (replace-match ""))
11013 (when flag
11014 (end-of-line 1)
11015 (org-move-to-column (- (window-width) 19) t)
11016 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11018 (defun org-set-current-tags-overlay (current prefix)
11019 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11020 (if (featurep 'xemacs)
11021 (org-overlay-display org-tags-overlay (concat prefix s)
11022 'secondary-selection)
11023 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11024 (org-overlay-display org-tags-overlay (concat prefix s)))))
11026 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11027 "Fast tag selection with single keys.
11028 CURRENT is the current list of tags in the headline, INHERITED is the
11029 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11030 possibly with grouping information. TODO-TABLE is a similar table with
11031 TODO keywords, should these have keys assigned to them.
11032 If the keys are nil, a-z are automatically assigned.
11033 Returns the new tags string, or nil to not change the current settings."
11034 (let* ((fulltable (append table todo-table))
11035 (maxlen (apply 'max (mapcar
11036 (lambda (x)
11037 (if (stringp (car x)) (string-width (car x)) 0))
11038 fulltable)))
11039 (buf (current-buffer))
11040 (expert (eq org-fast-tag-selection-single-key 'expert))
11041 (buffer-tags nil)
11042 (fwidth (+ maxlen 3 1 3))
11043 (ncol (/ (- (window-width) 4) fwidth))
11044 (i-face 'org-done)
11045 (c-face 'org-todo)
11046 tg cnt e c char c1 c2 ntable tbl rtn
11047 ov-start ov-end ov-prefix
11048 (exit-after-next org-fast-tag-selection-single-key)
11049 (done-keywords org-done-keywords)
11050 groups ingroup)
11051 (save-excursion
11052 (beginning-of-line 1)
11053 (if (looking-at
11054 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11055 (setq ov-start (match-beginning 1)
11056 ov-end (match-end 1)
11057 ov-prefix "")
11058 (setq ov-start (1- (point-at-eol))
11059 ov-end (1+ ov-start))
11060 (skip-chars-forward "^\n\r")
11061 (setq ov-prefix
11062 (concat
11063 (buffer-substring (1- (point)) (point))
11064 (if (> (current-column) org-tags-column)
11066 (make-string (- org-tags-column (current-column)) ?\ ))))))
11067 (org-move-overlay org-tags-overlay ov-start ov-end)
11068 (save-window-excursion
11069 (if expert
11070 (set-buffer (get-buffer-create " *Org tags*"))
11071 (delete-other-windows)
11072 (split-window-vertically)
11073 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11074 (erase-buffer)
11075 (org-set-local 'org-done-keywords done-keywords)
11076 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11077 (org-fast-tag-insert "Current" current c-face "\n\n")
11078 (org-fast-tag-show-exit exit-after-next)
11079 (org-set-current-tags-overlay current ov-prefix)
11080 (setq tbl fulltable char ?a cnt 0)
11081 (while (setq e (pop tbl))
11082 (cond
11083 ((equal e '(:startgroup))
11084 (push '() groups) (setq ingroup t)
11085 (when (not (= cnt 0))
11086 (setq cnt 0)
11087 (insert "\n"))
11088 (insert "{ "))
11089 ((equal e '(:endgroup))
11090 (setq ingroup nil cnt 0)
11091 (insert "}\n"))
11092 ((equal e '(:newline))
11093 (when (not (= cnt 0))
11094 (setq cnt 0)
11095 (insert "\n")
11096 (setq e (car tbl))
11097 (while (equal (car tbl) '(:newline))
11098 (insert "\n")
11099 (setq tbl (cdr tbl)))))
11101 (setq tg (car e) c2 nil)
11102 (if (cdr e)
11103 (setq c (cdr e))
11104 ;; automatically assign a character.
11105 (setq c1 (string-to-char
11106 (downcase (substring
11107 tg (if (= (string-to-char tg) ?@) 1 0)))))
11108 (if (or (rassoc c1 ntable) (rassoc c1 table))
11109 (while (or (rassoc char ntable) (rassoc char table))
11110 (setq char (1+ char)))
11111 (setq c2 c1))
11112 (setq c (or c2 char)))
11113 (if ingroup (push tg (car groups)))
11114 (setq tg (org-add-props tg nil 'face
11115 (cond
11116 ((not (assoc tg table))
11117 (org-get-todo-face tg))
11118 ((member tg current) c-face)
11119 ((member tg inherited) i-face)
11120 (t nil))))
11121 (if (and (= cnt 0) (not ingroup)) (insert " "))
11122 (insert "[" c "] " tg (make-string
11123 (- fwidth 4 (length tg)) ?\ ))
11124 (push (cons tg c) ntable)
11125 (when (= (setq cnt (1+ cnt)) ncol)
11126 (insert "\n")
11127 (if ingroup (insert " "))
11128 (setq cnt 0)))))
11129 (setq ntable (nreverse ntable))
11130 (insert "\n")
11131 (goto-char (point-min))
11132 (if (not expert) (org-fit-window-to-buffer))
11133 (setq rtn
11134 (catch 'exit
11135 (while t
11136 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11137 (if groups " [!] no groups" " [!]groups")
11138 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11139 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11140 (cond
11141 ((= c ?\r) (throw 'exit t))
11142 ((= c ?!)
11143 (setq groups (not groups))
11144 (goto-char (point-min))
11145 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11146 ((= c ?\C-c)
11147 (if (not expert)
11148 (org-fast-tag-show-exit
11149 (setq exit-after-next (not exit-after-next)))
11150 (setq expert nil)
11151 (delete-other-windows)
11152 (split-window-vertically)
11153 (org-switch-to-buffer-other-window " *Org tags*")
11154 (org-fit-window-to-buffer)))
11155 ((or (= c ?\C-g)
11156 (and (= c ?q) (not (rassoc c ntable))))
11157 (org-detach-overlay org-tags-overlay)
11158 (setq quit-flag t))
11159 ((= c ?\ )
11160 (setq current nil)
11161 (if exit-after-next (setq exit-after-next 'now)))
11162 ((= c ?\t)
11163 (condition-case nil
11164 (setq tg (org-ido-completing-read
11165 "Tag: "
11166 (or buffer-tags
11167 (with-current-buffer buf
11168 (org-get-buffer-tags)))))
11169 (quit (setq tg "")))
11170 (when (string-match "\\S-" tg)
11171 (add-to-list 'buffer-tags (list tg))
11172 (if (member tg current)
11173 (setq current (delete tg current))
11174 (push tg current)))
11175 (if exit-after-next (setq exit-after-next 'now)))
11176 ((setq e (rassoc c todo-table) tg (car e))
11177 (with-current-buffer buf
11178 (save-excursion (org-todo tg)))
11179 (if exit-after-next (setq exit-after-next 'now)))
11180 ((setq e (rassoc c ntable) tg (car e))
11181 (if (member tg current)
11182 (setq current (delete tg current))
11183 (loop for g in groups do
11184 (if (member tg g)
11185 (mapc (lambda (x)
11186 (setq current (delete x current)))
11187 g)))
11188 (push tg current))
11189 (if exit-after-next (setq exit-after-next 'now))))
11191 ;; Create a sorted list
11192 (setq current
11193 (sort current
11194 (lambda (a b)
11195 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11196 (if (eq exit-after-next 'now) (throw 'exit t))
11197 (goto-char (point-min))
11198 (beginning-of-line 2)
11199 (delete-region (point) (point-at-eol))
11200 (org-fast-tag-insert "Current" current c-face)
11201 (org-set-current-tags-overlay current ov-prefix)
11202 (while (re-search-forward
11203 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11204 (setq tg (match-string 1))
11205 (add-text-properties
11206 (match-beginning 1) (match-end 1)
11207 (list 'face
11208 (cond
11209 ((member tg current) c-face)
11210 ((member tg inherited) i-face)
11211 (t (get-text-property (match-beginning 1) 'face))))))
11212 (goto-char (point-min)))))
11213 (org-detach-overlay org-tags-overlay)
11214 (if rtn
11215 (mapconcat 'identity current ":")
11216 nil))))
11218 (defun org-get-tags-string ()
11219 "Get the TAGS string in the current headline."
11220 (unless (org-on-heading-p t)
11221 (error "Not on a heading"))
11222 (save-excursion
11223 (beginning-of-line 1)
11224 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11225 (org-match-string-no-properties 1)
11226 "")))
11228 (defun org-get-tags ()
11229 "Get the list of tags specified in the current headline."
11230 (org-split-string (org-get-tags-string) ":"))
11232 (defun org-get-buffer-tags ()
11233 "Get a table of all tags used in the buffer, for completion."
11234 (let (tags)
11235 (save-excursion
11236 (goto-char (point-min))
11237 (while (re-search-forward
11238 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11239 (when (equal (char-after (point-at-bol 0)) ?*)
11240 (mapc (lambda (x) (add-to-list 'tags x))
11241 (org-split-string (org-match-string-no-properties 1) ":")))))
11242 (mapcar 'list tags)))
11244 ;;;; The mapping API
11246 ;;;###autoload
11247 (defun org-map-entries (func &optional match scope &rest skip)
11248 "Call FUNC at each headline selected by MATCH in SCOPE.
11250 FUNC is a function or a lisp form. The function will be called without
11251 arguments, with the cursor positioned at the beginning of the headline.
11252 The return values of all calls to the function will be collected and
11253 returned as a list.
11255 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11256 does not need to preserve point. After evaluaton, the cursor will be
11257 moved to the end of the line (presumably of the headline of the
11258 processed entry) and search continues from there. Under some
11259 circumstances, this may not produce the wanted results. For example,
11260 if you have removed (e.g. archived) the current (sub)tree it could
11261 mean that the next entry will be skipped entirely. In such cases, you
11262 can specify the position from where search should continue by making
11263 FUNC set the variable `org-map-continue-from' to the desired buffer
11264 position.
11266 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11267 Only headlines that are matched by this query will be considered during
11268 the iteration. When MATCH is nil or t, all headlines will be
11269 visited by the iteration.
11271 SCOPE determines the scope of this command. It can be any of:
11273 nil The current buffer, respecting the restriction if any
11274 tree The subtree started with the entry at point
11275 file The current buffer, without restriction
11276 file-with-archives
11277 The current buffer, and any archives associated with it
11278 agenda All agenda files
11279 agenda-with-archives
11280 All agenda files with any archive files associated with them
11281 \(file1 file2 ...)
11282 If this is a list, all files in the list will be scanned
11284 The remaining args are treated as settings for the skipping facilities of
11285 the scanner. The following items can be given here:
11287 archive skip trees with the archive tag.
11288 comment skip trees with the COMMENT keyword
11289 function or Emacs Lisp form:
11290 will be used as value for `org-agenda-skip-function', so whenever
11291 the the function returns t, FUNC will not be called for that
11292 entry and search will continue from the point where the
11293 function leaves it.
11295 If your function needs to retrieve the tags including inherited tags
11296 at the *current* entry, you can use the value of the variable
11297 `org-scanner-tags' which will be much faster than getting the value
11298 with `org-get-tags-at'. If your function gets properties with
11299 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11300 to t around the call to `org-entry-properties' to get the same speedup.
11301 Note that if your function moves around to retrieve tags and properties at
11302 a *different* entry, you cannot use these techniques."
11303 (let* ((org-agenda-archives-mode nil) ; just to make sure
11304 (org-agenda-skip-archived-trees (memq 'archive skip))
11305 (org-agenda-skip-comment-trees (memq 'comment skip))
11306 (org-agenda-skip-function
11307 (car (org-delete-all '(comment archive) skip)))
11308 (org-tags-match-list-sublevels t)
11309 matcher file res
11310 org-todo-keywords-for-agenda
11311 org-done-keywords-for-agenda
11312 org-todo-keyword-alist-for-agenda
11313 org-tag-alist-for-agenda)
11315 (cond
11316 ((eq match t) (setq matcher t))
11317 ((eq match nil) (setq matcher t))
11318 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11320 (save-excursion
11321 (save-restriction
11322 (when (eq scope 'tree)
11323 (org-back-to-heading t)
11324 (org-narrow-to-subtree)
11325 (setq scope nil))
11327 (if (not scope)
11328 (progn
11329 (org-prepare-agenda-buffers
11330 (list (buffer-file-name (current-buffer))))
11331 (setq res (org-scan-tags func matcher)))
11332 ;; Get the right scope
11333 (cond
11334 ((and scope (listp scope) (symbolp (car scope)))
11335 (setq scope (eval scope)))
11336 ((eq scope 'agenda)
11337 (setq scope (org-agenda-files t)))
11338 ((eq scope 'agenda-with-archives)
11339 (setq scope (org-agenda-files t))
11340 (setq scope (org-add-archive-files scope)))
11341 ((eq scope 'file)
11342 (setq scope (list (buffer-file-name))))
11343 ((eq scope 'file-with-archives)
11344 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11345 (org-prepare-agenda-buffers scope)
11346 (while (setq file (pop scope))
11347 (with-current-buffer (org-find-base-buffer-visiting file)
11348 (save-excursion
11349 (save-restriction
11350 (widen)
11351 (goto-char (point-min))
11352 (setq res (append res (org-scan-tags func matcher))))))))))
11353 res))
11355 ;;;; Properties
11357 ;;; Setting and retrieving properties
11359 (defconst org-special-properties
11360 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11361 "TIMESTAMP" "TIMESTAMP_IA")
11362 "The special properties valid in Org-mode.
11364 These are properties that are not defined in the property drawer,
11365 but in some other way.")
11367 (defconst org-default-properties
11368 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11369 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11370 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11371 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11372 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11373 "CLOCK_MODELINE_TOTAL")
11374 "Some properties that are used by Org-mode for various purposes.
11375 Being in this list makes sure that they are offered for completion.")
11377 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11378 "Regular expression matching the first line of a property drawer.")
11380 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11381 "Regular expression matching the first line of a property drawer.")
11383 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11384 "Regular expression matching the first line of a property drawer.")
11386 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11387 "Regular expression matching the first line of a property drawer.")
11389 (defconst org-property-drawer-re
11390 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11391 org-property-end-re "\\)\n?")
11392 "Matches an entire property drawer.")
11394 (defconst org-clock-drawer-re
11395 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11396 org-property-end-re "\\)\n?")
11397 "Matches an entire clock drawer.")
11399 (defun org-property-action ()
11400 "Do an action on properties."
11401 (interactive)
11402 (let (c)
11403 (org-at-property-p)
11404 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11405 (setq c (read-char-exclusive))
11406 (cond
11407 ((equal c ?s)
11408 (call-interactively 'org-set-property))
11409 ((equal c ?d)
11410 (call-interactively 'org-delete-property))
11411 ((equal c ?D)
11412 (call-interactively 'org-delete-property-globally))
11413 ((equal c ?c)
11414 (call-interactively 'org-compute-property-at-point))
11415 (t (error "No such property action %c" c)))))
11417 (defun org-at-property-p ()
11418 "Is the cursor in a property line?"
11419 ;; FIXME: Does not check if we are actually in the drawer.
11420 ;; FIXME: also returns true on any drawers.....
11421 ;; This is used by C-c C-c for property action.
11422 (save-excursion
11423 (beginning-of-line 1)
11424 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11426 (defun org-get-property-block (&optional beg end force)
11427 "Return the (beg . end) range of the body of the property drawer.
11428 BEG and END can be beginning and end of subtree, if not given
11429 they will be found.
11430 If the drawer does not exist and FORCE is non-nil, create the drawer."
11431 (catch 'exit
11432 (save-excursion
11433 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11434 (end (or end (progn (outline-next-heading) (point)))))
11435 (goto-char beg)
11436 (if (re-search-forward org-property-start-re end t)
11437 (setq beg (1+ (match-end 0)))
11438 (if force
11439 (save-excursion
11440 (org-insert-property-drawer)
11441 (setq end (progn (outline-next-heading) (point))))
11442 (throw 'exit nil))
11443 (goto-char beg)
11444 (if (re-search-forward org-property-start-re end t)
11445 (setq beg (1+ (match-end 0)))))
11446 (if (re-search-forward org-property-end-re end t)
11447 (setq end (match-beginning 0))
11448 (or force (throw 'exit nil))
11449 (goto-char beg)
11450 (setq end beg)
11451 (org-indent-line-function)
11452 (insert ":END:\n"))
11453 (cons beg end)))))
11455 (defun org-entry-properties (&optional pom which)
11456 "Get all properties of the entry at point-or-marker POM.
11457 This includes the TODO keyword, the tags, time strings for deadline,
11458 scheduled, and clocking, and any additional properties defined in the
11459 entry. The return value is an alist, keys may occur multiple times
11460 if the property key was used several times.
11461 POM may also be nil, in which case the current entry is used.
11462 If WHICH is nil or `all', get all properties. If WHICH is
11463 `special' or `standard', only get that subclass."
11464 (setq which (or which 'all))
11465 (org-with-point-at pom
11466 (let ((clockstr (substring org-clock-string 0 -1))
11467 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11468 beg end range props sum-props key value string clocksum)
11469 (save-excursion
11470 (when (condition-case nil
11471 (and (org-mode-p) (org-back-to-heading t))
11472 (error nil))
11473 (setq beg (point))
11474 (setq sum-props (get-text-property (point) 'org-summaries))
11475 (setq clocksum (get-text-property (point) :org-clock-minutes))
11476 (outline-next-heading)
11477 (setq end (point))
11478 (when (memq which '(all special))
11479 ;; Get the special properties, like TODO and tags
11480 (goto-char beg)
11481 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11482 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11483 (when (looking-at org-priority-regexp)
11484 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11485 (when (and (setq value (org-get-tags-string))
11486 (string-match "\\S-" value))
11487 (push (cons "TAGS" value) props))
11488 (when (setq value (org-get-tags-at))
11489 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11490 props))
11491 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11492 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11493 string (if (equal key clockstr)
11494 (org-no-properties
11495 (org-trim
11496 (buffer-substring
11497 (match-beginning 3) (goto-char (point-at-eol)))))
11498 (substring (org-match-string-no-properties 3) 1 -1)))
11499 (unless key
11500 (if (= (char-after (match-beginning 3)) ?\[)
11501 (setq key "TIMESTAMP_IA")
11502 (setq key "TIMESTAMP")))
11503 (when (or (equal key clockstr) (not (assoc key props)))
11504 (push (cons key string) props)))
11508 (when (memq which '(all standard))
11509 ;; Get the standard properties, like :PROP: ...
11510 (setq range (org-get-property-block beg end))
11511 (when range
11512 (goto-char (car range))
11513 (while (re-search-forward
11514 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11515 (cdr range) t)
11516 (setq key (org-match-string-no-properties 1)
11517 value (org-trim (or (org-match-string-no-properties 2) "")))
11518 (unless (member key excluded)
11519 (push (cons key (or value "")) props)))))
11520 (if clocksum
11521 (push (cons "CLOCKSUM"
11522 (org-columns-number-to-string (/ (float clocksum) 60.)
11523 'add_times))
11524 props))
11525 (unless (assoc "CATEGORY" props)
11526 (setq value (or (org-get-category)
11527 (progn (org-refresh-category-properties)
11528 (org-get-category))))
11529 (push (cons "CATEGORY" value) props))
11530 (append sum-props (nreverse props)))))))
11532 (defun org-entry-get (pom property &optional inherit)
11533 "Get value of PROPERTY for entry at point-or-marker POM.
11534 If INHERIT is non-nil and the entry does not have the property,
11535 then also check higher levels of the hierarchy.
11536 If INHERIT is the symbol `selective', use inheritance only if the setting
11537 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11538 If the property is present but empty, the return value is the empty string.
11539 If the property is not present at all, nil is returned."
11540 (org-with-point-at pom
11541 (if (and inherit (if (eq inherit 'selective)
11542 (org-property-inherit-p property)
11544 (org-entry-get-with-inheritance property)
11545 (if (member property org-special-properties)
11546 ;; We need a special property. Use brute force, get all properties.
11547 (cdr (assoc property (org-entry-properties nil 'special)))
11548 (let ((range (org-get-property-block)))
11549 (if (and range
11550 (goto-char (car range))
11551 (re-search-forward
11552 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11553 (cdr range) t))
11554 ;; Found the property, return it.
11555 (if (match-end 1)
11556 (org-match-string-no-properties 1)
11557 "")))))))
11559 (defun org-property-or-variable-value (var &optional inherit)
11560 "Check if there is a property fixing the value of VAR.
11561 If yes, return this value. If not, return the current value of the variable."
11562 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11563 (if (and prop (stringp prop) (string-match "\\S-" prop))
11564 (read prop)
11565 (symbol-value var))))
11567 (defun org-entry-delete (pom property)
11568 "Delete the property PROPERTY from entry at point-or-marker POM."
11569 (org-with-point-at pom
11570 (if (member property org-special-properties)
11571 nil ; cannot delete these properties.
11572 (let ((range (org-get-property-block)))
11573 (if (and range
11574 (goto-char (car range))
11575 (re-search-forward
11576 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11577 (cdr range) t))
11578 (progn
11579 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11581 nil)))))
11583 ;; Multi-values properties are properties that contain multiple values
11584 ;; These values are assumed to be single words, separated by whitespace.
11585 (defun org-entry-add-to-multivalued-property (pom property value)
11586 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11587 (let* ((old (org-entry-get pom property))
11588 (values (and old (org-split-string old "[ \t]"))))
11589 (setq value (org-entry-protect-space value))
11590 (unless (member value values)
11591 (setq values (cons value values))
11592 (org-entry-put pom property
11593 (mapconcat 'identity values " ")))))
11595 (defun org-entry-remove-from-multivalued-property (pom property value)
11596 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11597 (let* ((old (org-entry-get pom property))
11598 (values (and old (org-split-string old "[ \t]"))))
11599 (setq value (org-entry-protect-space value))
11600 (when (member value values)
11601 (setq values (delete value values))
11602 (org-entry-put pom property
11603 (mapconcat 'identity values " ")))))
11605 (defun org-entry-member-in-multivalued-property (pom property value)
11606 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11607 (let* ((old (org-entry-get pom property))
11608 (values (and old (org-split-string old "[ \t]"))))
11609 (setq value (org-entry-protect-space value))
11610 (member value values)))
11612 (defun org-entry-get-multivalued-property (pom property)
11613 "Return a list of values in a multivalued property."
11614 (let* ((value (org-entry-get pom property))
11615 (values (and value (org-split-string value "[ \t]"))))
11616 (mapcar 'org-entry-restore-space values)))
11618 (defun org-entry-put-multivalued-property (pom property &rest values)
11619 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11620 VALUES should be a list of strings. Spaces will be protected."
11621 (org-entry-put pom property
11622 (mapconcat 'org-entry-protect-space values " "))
11623 (let* ((value (org-entry-get pom property))
11624 (values (and value (org-split-string value "[ \t]"))))
11625 (mapcar 'org-entry-restore-space values)))
11627 (defun org-entry-protect-space (s)
11628 "Protect spaces and newline in string S."
11629 (while (string-match " " s)
11630 (setq s (replace-match "%20" t t s)))
11631 (while (string-match "\n" s)
11632 (setq s (replace-match "%0A" t t s)))
11635 (defun org-entry-restore-space (s)
11636 "Restore spaces and newline in string S."
11637 (while (string-match "%20" s)
11638 (setq s (replace-match " " t t s)))
11639 (while (string-match "%0A" s)
11640 (setq s (replace-match "\n" t t s)))
11643 (defvar org-entry-property-inherited-from (make-marker)
11644 "Marker pointing to the entry from where a property was inherited.
11645 Each call to `org-entry-get-with-inheritance' will set this marker to the
11646 location of the entry where the inheritance search matched. If there was
11647 no match, the marker will point nowhere.
11648 Note that also `org-entry-get' calls this function, if the INHERIT flag
11649 is set.")
11651 (defun org-entry-get-with-inheritance (property)
11652 "Get entry property, and search higher levels if not present."
11653 (move-marker org-entry-property-inherited-from nil)
11654 (let (tmp)
11655 (save-excursion
11656 (save-restriction
11657 (widen)
11658 (catch 'ex
11659 (while t
11660 (when (setq tmp (org-entry-get nil property))
11661 (org-back-to-heading t)
11662 (move-marker org-entry-property-inherited-from (point))
11663 (throw 'ex tmp))
11664 (or (org-up-heading-safe) (throw 'ex nil)))))
11665 (or tmp
11666 (cdr (assoc property org-file-properties))
11667 (cdr (assoc property org-global-properties))
11668 (cdr (assoc property org-global-properties-fixed))))))
11670 (defun org-entry-put (pom property value)
11671 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11672 (org-with-point-at pom
11673 (org-back-to-heading t)
11674 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11675 range)
11676 (cond
11677 ((equal property "TODO")
11678 (when (and (stringp value) (string-match "\\S-" value)
11679 (not (member value org-todo-keywords-1)))
11680 (error "\"%s\" is not a valid TODO state" value))
11681 (if (or (not value)
11682 (not (string-match "\\S-" value)))
11683 (setq value 'none))
11684 (org-todo value)
11685 (org-set-tags nil 'align))
11686 ((equal property "PRIORITY")
11687 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11688 (string-to-char value) ?\ ))
11689 (org-set-tags nil 'align))
11690 ((equal property "SCHEDULED")
11691 (if (re-search-forward org-scheduled-time-regexp end t)
11692 (cond
11693 ((eq value 'earlier) (org-timestamp-change -1 'day))
11694 ((eq value 'later) (org-timestamp-change 1 'day))
11695 (t (call-interactively 'org-schedule)))
11696 (call-interactively 'org-schedule)))
11697 ((equal property "DEADLINE")
11698 (if (re-search-forward org-deadline-time-regexp end t)
11699 (cond
11700 ((eq value 'earlier) (org-timestamp-change -1 'day))
11701 ((eq value 'later) (org-timestamp-change 1 'day))
11702 (t (call-interactively 'org-deadline)))
11703 (call-interactively 'org-deadline)))
11704 ((member property org-special-properties)
11705 (error "The %s property can not yet be set with `org-entry-put'"
11706 property))
11707 (t ; a non-special property
11708 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11709 (setq range (org-get-property-block beg end 'force))
11710 (goto-char (car range))
11711 (if (re-search-forward
11712 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11713 (progn
11714 (delete-region (match-beginning 1) (match-end 1))
11715 (goto-char (match-beginning 1)))
11716 (goto-char (cdr range))
11717 (insert "\n")
11718 (backward-char 1)
11719 (org-indent-line-function)
11720 (insert ":" property ":"))
11721 (and value (insert " " value))
11722 (org-indent-line-function)))))))
11724 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11725 "Get all property keys in the current buffer.
11726 With INCLUDE-SPECIALS, also list the special properties that reflect things
11727 like tags and TODO state.
11728 With INCLUDE-DEFAULTS, also include properties that has special meaning
11729 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11730 With INCLUDE-COLUMNS, also include property names given in COLUMN
11731 formats in the current buffer."
11732 (let (rtn range cfmt s p)
11733 (save-excursion
11734 (save-restriction
11735 (widen)
11736 (goto-char (point-min))
11737 (while (re-search-forward org-property-start-re nil t)
11738 (setq range (org-get-property-block))
11739 (goto-char (car range))
11740 (while (re-search-forward
11741 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11742 (cdr range) t)
11743 (add-to-list 'rtn (org-match-string-no-properties 1)))
11744 (outline-next-heading))))
11746 (when include-specials
11747 (setq rtn (append org-special-properties rtn)))
11749 (when include-defaults
11750 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
11751 (add-to-list 'rtn org-effort-property))
11753 (when include-columns
11754 (save-excursion
11755 (save-restriction
11756 (widen)
11757 (goto-char (point-min))
11758 (while (re-search-forward
11759 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11760 nil t)
11761 (setq cfmt (match-string 2) s 0)
11762 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11763 cfmt s)
11764 (setq s (match-end 0)
11765 p (match-string 1 cfmt))
11766 (unless (or (equal p "ITEM")
11767 (member p org-special-properties))
11768 (add-to-list 'rtn (match-string 1 cfmt))))))))
11770 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11772 (defun org-property-values (key)
11773 "Return a list of all values of property KEY."
11774 (save-excursion
11775 (save-restriction
11776 (widen)
11777 (goto-char (point-min))
11778 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11779 values)
11780 (while (re-search-forward re nil t)
11781 (add-to-list 'values (org-trim (match-string 1))))
11782 (delete "" values)))))
11784 (defun org-insert-property-drawer ()
11785 "Insert a property drawer into the current entry."
11786 (interactive)
11787 (org-back-to-heading t)
11788 (looking-at outline-regexp)
11789 (let ((indent (if org-adapt-indentation
11790 (- (match-end 0)(match-beginning 0))
11792 (beg (point))
11793 (re (concat "^[ \t]*" org-keyword-time-regexp))
11794 end hiddenp)
11795 (outline-next-heading)
11796 (setq end (point))
11797 (goto-char beg)
11798 (while (re-search-forward re end t))
11799 (setq hiddenp (org-invisible-p))
11800 (end-of-line 1)
11801 (and (equal (char-after) ?\n) (forward-char 1))
11802 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11803 (if (member (match-string 1) '("CLOCK:" ":END:"))
11804 ;; just skip this line
11805 (beginning-of-line 2)
11806 ;; Drawer start, find the end
11807 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11808 (beginning-of-line 1)))
11809 (org-skip-over-state-notes)
11810 (skip-chars-backward " \t\n\r")
11811 (if (eq (char-before) ?*) (forward-char 1))
11812 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11813 (beginning-of-line 0)
11814 (org-indent-to-column indent)
11815 (beginning-of-line 2)
11816 (org-indent-to-column indent)
11817 (beginning-of-line 0)
11818 (if hiddenp
11819 (save-excursion
11820 (org-back-to-heading t)
11821 (hide-entry))
11822 (org-flag-drawer t))))
11824 (defun org-set-property (property value)
11825 "In the current entry, set PROPERTY to VALUE.
11826 When called interactively, this will prompt for a property name, offering
11827 completion on existing and default properties. And then it will prompt
11828 for a value, offering completion either on allowed values (via an inherited
11829 xxx_ALL property) or on existing values in other instances of this property
11830 in the current file."
11831 (interactive
11832 (let* ((completion-ignore-case t)
11833 (keys (org-buffer-property-keys nil t t))
11834 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11835 (prop (if (member prop0 keys)
11836 prop0
11837 (or (cdr (assoc (downcase prop0)
11838 (mapcar (lambda (x) (cons (downcase x) x))
11839 keys)))
11840 prop0)))
11841 (cur (org-entry-get nil prop))
11842 (allowed (org-property-get-allowed-values nil prop 'table))
11843 (existing (mapcar 'list (org-property-values prop)))
11844 (val (if allowed
11845 (org-completing-read "Value: " allowed nil 'req-match)
11846 (let (org-completion-use-ido)
11847 (org-completing-read
11848 (concat "Value" (if (and cur (string-match "\\S-" cur))
11849 (concat "[" cur "]") "")
11850 ": ")
11851 existing nil nil "" nil cur)))))
11852 (list prop (if (equal val "") cur val))))
11853 (unless (equal (org-entry-get nil property) value)
11854 (org-entry-put nil property value)))
11856 (defun org-delete-property (property)
11857 "In the current entry, delete PROPERTY."
11858 (interactive
11859 (let* ((completion-ignore-case t)
11860 (prop (org-ido-completing-read
11861 "Property: " (org-entry-properties nil 'standard))))
11862 (list prop)))
11863 (message "Property %s %s" property
11864 (if (org-entry-delete nil property)
11865 "deleted"
11866 "was not present in the entry")))
11868 (defun org-delete-property-globally (property)
11869 "Remove PROPERTY globally, from all entries."
11870 (interactive
11871 (let* ((completion-ignore-case t)
11872 (prop (org-ido-completing-read
11873 "Globally remove property: "
11874 (mapcar 'list (org-buffer-property-keys)))))
11875 (list prop)))
11876 (save-excursion
11877 (save-restriction
11878 (widen)
11879 (goto-char (point-min))
11880 (let ((cnt 0))
11881 (while (re-search-forward
11882 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11883 nil t)
11884 (setq cnt (1+ cnt))
11885 (replace-match ""))
11886 (message "Property \"%s\" removed from %d entries" property cnt)))))
11888 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11890 (defun org-compute-property-at-point ()
11891 "Compute the property at point.
11892 This looks for an enclosing column format, extracts the operator and
11893 then applies it to the property in the column format's scope."
11894 (interactive)
11895 (unless (org-at-property-p)
11896 (error "Not at a property"))
11897 (let ((prop (org-match-string-no-properties 2)))
11898 (org-columns-get-format-and-top-level)
11899 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11900 (error "No operator defined for property %s" prop))
11901 (org-columns-compute prop)))
11903 (defun org-property-get-allowed-values (pom property &optional table)
11904 "Get allowed values for the property PROPERTY.
11905 When TABLE is non-nil, return an alist that can directly be used for
11906 completion."
11907 (let (vals)
11908 (cond
11909 ((equal property "TODO")
11910 (setq vals (org-with-point-at pom
11911 (append org-todo-keywords-1 '("")))))
11912 ((equal property "PRIORITY")
11913 (let ((n org-lowest-priority))
11914 (while (>= n org-highest-priority)
11915 (push (char-to-string n) vals)
11916 (setq n (1- n)))))
11917 ((member property org-special-properties))
11919 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11921 (when (and vals (string-match "\\S-" vals))
11922 (setq vals (car (read-from-string (concat "(" vals ")"))))
11923 (setq vals (mapcar (lambda (x)
11924 (cond ((stringp x) x)
11925 ((numberp x) (number-to-string x))
11926 ((symbolp x) (symbol-name x))
11927 (t "???")))
11928 vals)))))
11929 (if table (mapcar 'list vals) vals)))
11931 (defun org-property-previous-allowed-value (&optional previous)
11932 "Switch to the next allowed value for this property."
11933 (interactive)
11934 (org-property-next-allowed-value t))
11936 (defun org-property-next-allowed-value (&optional previous)
11937 "Switch to the next allowed value for this property."
11938 (interactive)
11939 (unless (org-at-property-p)
11940 (error "Not at a property"))
11941 (let* ((key (match-string 2))
11942 (value (match-string 3))
11943 (allowed (or (org-property-get-allowed-values (point) key)
11944 (and (member value '("[ ]" "[-]" "[X]"))
11945 '("[ ]" "[X]"))))
11946 nval)
11947 (unless allowed
11948 (error "Allowed values for this property have not been defined"))
11949 (if previous (setq allowed (reverse allowed)))
11950 (if (member value allowed)
11951 (setq nval (car (cdr (member value allowed)))))
11952 (setq nval (or nval (car allowed)))
11953 (if (equal nval value)
11954 (error "Only one allowed value for this property"))
11955 (org-at-property-p)
11956 (replace-match (concat " :" key ": " nval) t t)
11957 (org-indent-line-function)
11958 (beginning-of-line 1)
11959 (skip-chars-forward " \t")))
11961 (defun org-find-entry-with-id (ident)
11962 "Locate the entry that contains the ID property with exact value IDENT.
11963 IDENT can be a string, a symbol or a number, this function will search for
11964 the string representation of it.
11965 Return the position where this entry starts, or nil if there is no such entry."
11966 (interactive "sID: ")
11967 (let ((id (cond
11968 ((stringp ident) ident)
11969 ((symbol-name ident) (symbol-name ident))
11970 ((numberp ident) (number-to-string ident))
11971 (t (error "IDENT %s must be a string, symbol or number" ident))))
11972 (case-fold-search nil))
11973 (save-excursion
11974 (save-restriction
11975 (widen)
11976 (goto-char (point-min))
11977 (when (re-search-forward
11978 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11979 nil t)
11980 (org-back-to-heading t)
11981 (point))))))
11983 ;;;; Timestamps
11985 (defvar org-last-changed-timestamp nil)
11986 (defvar org-last-inserted-timestamp nil
11987 "The last time stamp inserted with `org-insert-time-stamp'.")
11988 (defvar org-time-was-given) ; dynamically scoped parameter
11989 (defvar org-end-time-was-given) ; dynamically scoped parameter
11990 (defvar org-ts-what) ; dynamically scoped parameter
11992 (defun org-time-stamp (arg &optional inactive)
11993 "Prompt for a date/time and insert a time stamp.
11994 If the user specifies a time like HH:MM, or if this command is called
11995 with a prefix argument, the time stamp will contain date and time.
11996 Otherwise, only the date will be included. All parts of a date not
11997 specified by the user will be filled in from the current date/time.
11998 So if you press just return without typing anything, the time stamp
11999 will represent the current date/time. If there is already a timestamp
12000 at the cursor, it will be modified."
12001 (interactive "P")
12002 (let* ((ts nil)
12003 (default-time
12004 ;; Default time is either today, or, when entering a range,
12005 ;; the range start.
12006 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12007 (save-excursion
12008 (re-search-backward
12009 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12010 (- (point) 20) t)))
12011 (apply 'encode-time (org-parse-time-string (match-string 1)))
12012 (current-time)))
12013 (default-input (and ts (org-get-compact-tod ts)))
12014 org-time-was-given org-end-time-was-given time)
12015 (cond
12016 ((and (org-at-timestamp-p t)
12017 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12018 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12019 (insert "--")
12020 (setq time (let ((this-command this-command))
12021 (org-read-date arg 'totime nil nil
12022 default-time default-input)))
12023 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12024 ((org-at-timestamp-p t)
12025 (setq time (let ((this-command this-command))
12026 (org-read-date arg 'totime nil nil default-time default-input)))
12027 (when (org-at-timestamp-p t) ; just to get the match data
12028 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12029 (replace-match "")
12030 (setq org-last-changed-timestamp
12031 (org-insert-time-stamp
12032 time (or org-time-was-given arg)
12033 inactive nil nil (list org-end-time-was-given))))
12034 (message "Timestamp updated"))
12036 (setq time (let ((this-command this-command))
12037 (org-read-date arg 'totime nil nil default-time default-input)))
12038 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12039 nil nil (list org-end-time-was-given))))))
12041 ;; FIXME: can we use this for something else, like computing time differences?
12042 (defun org-get-compact-tod (s)
12043 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12044 (let* ((t1 (match-string 1 s))
12045 (h1 (string-to-number (match-string 2 s)))
12046 (m1 (string-to-number (match-string 3 s)))
12047 (t2 (and (match-end 4) (match-string 5 s)))
12048 (h2 (and t2 (string-to-number (match-string 6 s))))
12049 (m2 (and t2 (string-to-number (match-string 7 s))))
12050 dh dm)
12051 (if (not t2)
12053 (setq dh (- h2 h1) dm (- m2 m1))
12054 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12055 (concat t1 "+" (number-to-string dh)
12056 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12058 (defun org-time-stamp-inactive (&optional arg)
12059 "Insert an inactive time stamp.
12060 An inactive time stamp is enclosed in square brackets instead of angle
12061 brackets. It is inactive in the sense that it does not trigger agenda entries,
12062 does not link to the calendar and cannot be changed with the S-cursor keys.
12063 So these are more for recording a certain time/date."
12064 (interactive "P")
12065 (org-time-stamp arg 'inactive))
12067 (defvar org-date-ovl (org-make-overlay 1 1))
12068 (org-overlay-put org-date-ovl 'face 'org-warning)
12069 (org-detach-overlay org-date-ovl)
12071 (defvar org-ans1) ; dynamically scoped parameter
12072 (defvar org-ans2) ; dynamically scoped parameter
12074 (defvar org-plain-time-of-day-regexp) ; defined below
12076 (defvar org-overriding-default-time nil) ; dynamically scoped
12077 (defvar org-read-date-overlay nil)
12078 (defvar org-dcst nil) ; dynamically scoped
12079 (defvar org-read-date-history nil)
12080 (defvar org-read-date-final-answer nil)
12082 (defun org-read-date (&optional with-time to-time from-string prompt
12083 default-time default-input)
12084 "Read a date, possibly a time, and make things smooth for the user.
12085 The prompt will suggest to enter an ISO date, but you can also enter anything
12086 which will at least partially be understood by `parse-time-string'.
12087 Unrecognized parts of the date will default to the current day, month, year,
12088 hour and minute. If this command is called to replace a timestamp at point,
12089 of to enter the second timestamp of a range, the default time is taken from the
12090 existing stamp. For example,
12091 3-2-5 --> 2003-02-05
12092 feb 15 --> currentyear-02-15
12093 sep 12 9 --> 2009-09-12
12094 12:45 --> today 12:45
12095 22 sept 0:34 --> currentyear-09-22 0:34
12096 12 --> currentyear-currentmonth-12
12097 Fri --> nearest Friday (today or later)
12098 etc.
12100 Furthermore you can specify a relative date by giving, as the *first* thing
12101 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12102 change in days weeks, months, years.
12103 With a single plus or minus, the date is relative to today. With a double
12104 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12105 +4d --> four days from today
12106 +4 --> same as above
12107 +2w --> two weeks from today
12108 ++5 --> five days from default date
12110 The function understands only English month and weekday abbreviations,
12111 but this can be configured with the variables `parse-time-months' and
12112 `parse-time-weekdays'.
12114 While prompting, a calendar is popped up - you can also select the
12115 date with the mouse (button 1). The calendar shows a period of three
12116 months. To scroll it to other months, use the keys `>' and `<'.
12117 If you don't like the calendar, turn it off with
12118 \(setq org-read-date-popup-calendar nil)
12120 With optional argument TO-TIME, the date will immediately be converted
12121 to an internal time.
12122 With an optional argument WITH-TIME, the prompt will suggest to also
12123 insert a time. Note that when WITH-TIME is not set, you can still
12124 enter a time, and this function will inform the calling routine about
12125 this change. The calling routine may then choose to change the format
12126 used to insert the time stamp into the buffer to include the time.
12127 With optional argument FROM-STRING, read from this string instead from
12128 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12129 the time/date that is used for everything that is not specified by the
12130 user."
12131 (require 'parse-time)
12132 (let* ((org-time-stamp-rounding-minutes
12133 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12134 (org-dcst org-display-custom-times)
12135 (ct (org-current-time))
12136 (def (or org-overriding-default-time default-time ct))
12137 (defdecode (decode-time def))
12138 (dummy (progn
12139 (when (< (nth 2 defdecode) org-extend-today-until)
12140 (setcar (nthcdr 2 defdecode) -1)
12141 (setcar (nthcdr 1 defdecode) 59)
12142 (setq def (apply 'encode-time defdecode)
12143 defdecode (decode-time def)))))
12144 (calendar-move-hook nil)
12145 (calendar-view-diary-initially-flag nil)
12146 (view-diary-entries-initially nil)
12147 (calendar-view-holidays-initially-flag nil)
12148 (view-calendar-holidays-initially nil)
12149 (timestr (format-time-string
12150 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12151 (prompt (concat (if prompt (concat prompt " ") "")
12152 (format "Date+time [%s]: " timestr)))
12153 ans (org-ans0 "") org-ans1 org-ans2 final)
12155 (cond
12156 (from-string (setq ans from-string))
12157 (org-read-date-popup-calendar
12158 (save-excursion
12159 (save-window-excursion
12160 (calendar)
12161 (calendar-forward-day (- (time-to-days def)
12162 (calendar-absolute-from-gregorian
12163 (calendar-current-date))))
12164 (org-eval-in-calendar nil t)
12165 (let* ((old-map (current-local-map))
12166 (map (copy-keymap calendar-mode-map))
12167 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12168 (org-defkey map (kbd "RET") 'org-calendar-select)
12169 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12170 'org-calendar-select-mouse)
12171 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12172 'org-calendar-select-mouse)
12173 (org-defkey minibuffer-local-map [(meta shift left)]
12174 (lambda () (interactive)
12175 (org-eval-in-calendar '(calendar-backward-month 1))))
12176 (org-defkey minibuffer-local-map [(meta shift right)]
12177 (lambda () (interactive)
12178 (org-eval-in-calendar '(calendar-forward-month 1))))
12179 (org-defkey minibuffer-local-map [(meta shift up)]
12180 (lambda () (interactive)
12181 (org-eval-in-calendar '(calendar-backward-year 1))))
12182 (org-defkey minibuffer-local-map [(meta shift down)]
12183 (lambda () (interactive)
12184 (org-eval-in-calendar '(calendar-forward-year 1))))
12185 (org-defkey minibuffer-local-map [?\e (shift left)]
12186 (lambda () (interactive)
12187 (org-eval-in-calendar '(calendar-backward-month 1))))
12188 (org-defkey minibuffer-local-map [?\e (shift right)]
12189 (lambda () (interactive)
12190 (org-eval-in-calendar '(calendar-forward-month 1))))
12191 (org-defkey minibuffer-local-map [?\e (shift up)]
12192 (lambda () (interactive)
12193 (org-eval-in-calendar '(calendar-backward-year 1))))
12194 (org-defkey minibuffer-local-map [?\e (shift down)]
12195 (lambda () (interactive)
12196 (org-eval-in-calendar '(calendar-forward-year 1))))
12197 (org-defkey minibuffer-local-map [(shift up)]
12198 (lambda () (interactive)
12199 (org-eval-in-calendar '(calendar-backward-week 1))))
12200 (org-defkey minibuffer-local-map [(shift down)]
12201 (lambda () (interactive)
12202 (org-eval-in-calendar '(calendar-forward-week 1))))
12203 (org-defkey minibuffer-local-map [(shift left)]
12204 (lambda () (interactive)
12205 (org-eval-in-calendar '(calendar-backward-day 1))))
12206 (org-defkey minibuffer-local-map [(shift right)]
12207 (lambda () (interactive)
12208 (org-eval-in-calendar '(calendar-forward-day 1))))
12209 (org-defkey minibuffer-local-map ">"
12210 (lambda () (interactive)
12211 (org-eval-in-calendar '(scroll-calendar-left 1))))
12212 (org-defkey minibuffer-local-map "<"
12213 (lambda () (interactive)
12214 (org-eval-in-calendar '(scroll-calendar-right 1))))
12215 (run-hooks 'org-read-date-minibuffer-setup-hook)
12216 (unwind-protect
12217 (progn
12218 (use-local-map map)
12219 (add-hook 'post-command-hook 'org-read-date-display)
12220 (setq org-ans0 (read-string prompt default-input
12221 'org-read-date-history nil))
12222 ;; org-ans0: from prompt
12223 ;; org-ans1: from mouse click
12224 ;; org-ans2: from calendar motion
12225 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12226 (remove-hook 'post-command-hook 'org-read-date-display)
12227 (use-local-map old-map)
12228 (when org-read-date-overlay
12229 (org-delete-overlay org-read-date-overlay)
12230 (setq org-read-date-overlay nil)))))))
12232 (t ; Naked prompt only
12233 (unwind-protect
12234 (setq ans (read-string prompt default-input
12235 'org-read-date-history timestr))
12236 (when org-read-date-overlay
12237 (org-delete-overlay org-read-date-overlay)
12238 (setq org-read-date-overlay nil)))))
12240 (setq final (org-read-date-analyze ans def defdecode))
12241 (setq org-read-date-final-answer ans)
12243 (if to-time
12244 (apply 'encode-time final)
12245 (if (and (boundp 'org-time-was-given) org-time-was-given)
12246 (format "%04d-%02d-%02d %02d:%02d"
12247 (nth 5 final) (nth 4 final) (nth 3 final)
12248 (nth 2 final) (nth 1 final))
12249 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12250 (defvar def)
12251 (defvar defdecode)
12252 (defvar with-time)
12253 (defun org-read-date-display ()
12254 "Display the current date prompt interpretation in the minibuffer."
12255 (when org-read-date-display-live
12256 (when org-read-date-overlay
12257 (org-delete-overlay org-read-date-overlay))
12258 (let ((p (point)))
12259 (end-of-line 1)
12260 (while (not (equal (buffer-substring
12261 (max (point-min) (- (point) 4)) (point))
12262 " "))
12263 (insert " "))
12264 (goto-char p))
12265 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12266 " " (or org-ans1 org-ans2)))
12267 (org-end-time-was-given nil)
12268 (f (org-read-date-analyze ans def defdecode))
12269 (fmts (if org-dcst
12270 org-time-stamp-custom-formats
12271 org-time-stamp-formats))
12272 (fmt (if (or with-time
12273 (and (boundp 'org-time-was-given) org-time-was-given))
12274 (cdr fmts)
12275 (car fmts)))
12276 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12277 (when (and org-end-time-was-given
12278 (string-match org-plain-time-of-day-regexp txt))
12279 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12280 org-end-time-was-given
12281 (substring txt (match-end 0)))))
12282 (setq org-read-date-overlay
12283 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12284 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12286 (defun org-read-date-analyze (ans def defdecode)
12287 "Analyse the combined answer of the date prompt."
12288 ;; FIXME: cleanup and comment
12289 (let (delta deltan deltaw deltadef year month day
12290 hour minute second wday pm h2 m2 tl wday1
12291 iso-year iso-weekday iso-week iso-year iso-date)
12293 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12294 (setq ans "+0"))
12296 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12297 (setq ans (replace-match "" t t ans)
12298 deltan (car delta)
12299 deltaw (nth 1 delta)
12300 deltadef (nth 2 delta)))
12302 ;; Check if there is an iso week date in there
12303 ;; If yes, sore the info and postpone interpreting it until the rest
12304 ;; of the parsing is done
12305 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12306 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12307 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12308 iso-week (string-to-number (match-string 2 ans)))
12309 (setq ans (replace-match "" t t ans)))
12311 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12312 (when (string-match
12313 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12314 (setq year (if (match-end 2)
12315 (string-to-number (match-string 2 ans))
12316 (string-to-number (format-time-string "%Y")))
12317 month (string-to-number (match-string 3 ans))
12318 day (string-to-number (match-string 4 ans)))
12319 (if (< year 100) (setq year (+ 2000 year)))
12320 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12321 t nil ans)))
12322 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12323 ;; If there is a time with am/pm, and *no* time without it, we convert
12324 ;; so that matching will be successful.
12325 (loop for i from 1 to 2 do ; twice, for end time as well
12326 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12327 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12328 (setq hour (string-to-number (match-string 1 ans))
12329 minute (if (match-end 3)
12330 (string-to-number (match-string 3 ans))
12332 pm (equal ?p
12333 (string-to-char (downcase (match-string 4 ans)))))
12334 (if (and (= hour 12) (not pm))
12335 (setq hour 0)
12336 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12337 (setq ans (replace-match (format "%02d:%02d" hour minute)
12338 t t ans))))
12340 ;; Check if a time range is given as a duration
12341 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12342 (setq hour (string-to-number (match-string 1 ans))
12343 h2 (+ hour (string-to-number (match-string 3 ans)))
12344 minute (string-to-number (match-string 2 ans))
12345 m2 (+ minute (if (match-end 5) (string-to-number
12346 (match-string 5 ans))0)))
12347 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12348 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12349 t t ans)))
12351 ;; Check if there is a time range
12352 (when (boundp 'org-end-time-was-given)
12353 (setq org-time-was-given nil)
12354 (when (and (string-match org-plain-time-of-day-regexp ans)
12355 (match-end 8))
12356 (setq org-end-time-was-given (match-string 8 ans))
12357 (setq ans (concat (substring ans 0 (match-beginning 7))
12358 (substring ans (match-end 7))))))
12360 (setq tl (parse-time-string ans)
12361 day (or (nth 3 tl) (nth 3 defdecode))
12362 month (or (nth 4 tl)
12363 (if (and org-read-date-prefer-future
12364 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12365 (1+ (nth 4 defdecode))
12366 (nth 4 defdecode)))
12367 year (or (nth 5 tl)
12368 (if (and org-read-date-prefer-future
12369 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12370 (1+ (nth 5 defdecode))
12371 (nth 5 defdecode)))
12372 hour (or (nth 2 tl) (nth 2 defdecode))
12373 minute (or (nth 1 tl) (nth 1 defdecode))
12374 second (or (nth 0 tl) 0)
12375 wday (nth 6 tl))
12377 ;; Special date definitions below
12378 (cond
12379 (iso-week
12380 ;; There was an iso week
12381 (setq year (or iso-year year)
12382 day (or iso-weekday wday 1)
12383 wday nil ; to make sure that the trigger below does not match
12384 iso-date (calendar-gregorian-from-absolute
12385 (calendar-absolute-from-iso
12386 (list iso-week day year))))
12387 ; FIXME: Should we also push ISO weeks into the future?
12388 ; (when (and org-read-date-prefer-future
12389 ; (not iso-year)
12390 ; (< (calendar-absolute-from-gregorian iso-date)
12391 ; (time-to-days (current-time))))
12392 ; (setq year (1+ year)
12393 ; iso-date (calendar-gregorian-from-absolute
12394 ; (calendar-absolute-from-iso
12395 ; (list iso-week day year)))))
12396 (setq month (car iso-date)
12397 year (nth 2 iso-date)
12398 day (nth 1 iso-date)))
12399 (deltan
12400 (unless deltadef
12401 (let ((now (decode-time (current-time))))
12402 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12403 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12404 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12405 ((equal deltaw "m") (setq month (+ month deltan)))
12406 ((equal deltaw "y") (setq year (+ year deltan)))))
12407 ((and wday (not (nth 3 tl)))
12408 ;; Weekday was given, but no day, so pick that day in the week
12409 ;; on or after the derived date.
12410 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12411 (unless (equal wday wday1)
12412 (setq day (+ day (% (- wday wday1 -7) 7))))))
12413 (if (and (boundp 'org-time-was-given)
12414 (nth 2 tl))
12415 (setq org-time-was-given t))
12416 (if (< year 100) (setq year (+ 2000 year)))
12417 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12418 (list second minute hour day month year)))
12420 (defvar parse-time-weekdays)
12422 (defun org-read-date-get-relative (s today default)
12423 "Check string S for special relative date string.
12424 TODAY and DEFAULT are internal times, for today and for a default.
12425 Return shift list (N what def-flag)
12426 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12427 N is the number of WHATs to shift.
12428 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12429 the DEFAULT date rather than TODAY."
12430 (when (and
12431 (string-match
12432 (concat
12433 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12434 "\\([0-9]+\\)?"
12435 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12436 "\\([ \t]\\|$\\)") s)
12437 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12438 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12439 (string-to-char (substring (match-string 1 s) -1))
12440 ?+))
12441 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12442 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12443 (what (if (match-end 3) (match-string 3 s) "d"))
12444 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12445 (date (if rel default today))
12446 (wday (nth 6 (decode-time date)))
12447 delta)
12448 (if wday1
12449 (progn
12450 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12451 (if (= dir ?-) (setq delta (- delta 7)))
12452 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12453 (list delta "d" rel))
12454 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12456 (defun org-eval-in-calendar (form &optional keepdate)
12457 "Eval FORM in the calendar window and return to current window.
12458 Also, store the cursor date in variable org-ans2."
12459 (let ((sw (selected-window)))
12460 (select-window (get-buffer-window "*Calendar*"))
12461 (eval form)
12462 (when (and (not keepdate) (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-ans2 (format-time-string "%Y-%m-%d" time))))
12466 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12467 (select-window sw)))
12469 (defun org-calendar-select ()
12470 "Return to `org-read-date' with the date currently selected.
12471 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12472 (interactive)
12473 (when (calendar-cursor-to-date)
12474 (let* ((date (calendar-cursor-to-date))
12475 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12476 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12477 (if (active-minibuffer-window) (exit-minibuffer))))
12479 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12480 "Insert a date stamp for the date given by the internal TIME.
12481 WITH-HM means, use the stamp format that includes the time of the day.
12482 INACTIVE means use square brackets instead of angular ones, so that the
12483 stamp will not contribute to the agenda.
12484 PRE and POST are optional strings to be inserted before and after the
12485 stamp.
12486 The command returns the inserted time stamp."
12487 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12488 stamp)
12489 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12490 (insert-before-markers (or pre ""))
12491 (insert-before-markers (setq stamp (format-time-string fmt time)))
12492 (when (listp extra)
12493 (setq extra (car extra))
12494 (if (and (stringp extra)
12495 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12496 (setq extra (format "-%02d:%02d"
12497 (string-to-number (match-string 1 extra))
12498 (string-to-number (match-string 2 extra))))
12499 (setq extra nil)))
12500 (when extra
12501 (backward-char 1)
12502 (insert-before-markers extra)
12503 (forward-char 1))
12504 (insert-before-markers (or post ""))
12505 (setq org-last-inserted-timestamp stamp)))
12507 (defun org-toggle-time-stamp-overlays ()
12508 "Toggle the use of custom time stamp formats."
12509 (interactive)
12510 (setq org-display-custom-times (not org-display-custom-times))
12511 (unless org-display-custom-times
12512 (let ((p (point-min)) (bmp (buffer-modified-p)))
12513 (while (setq p (next-single-property-change p 'display))
12514 (if (and (get-text-property p 'display)
12515 (eq (get-text-property p 'face) 'org-date))
12516 (remove-text-properties
12517 p (setq p (next-single-property-change p 'display))
12518 '(display t))))
12519 (set-buffer-modified-p bmp)))
12520 (if (featurep 'xemacs)
12521 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12522 (org-restart-font-lock)
12523 (setq org-table-may-need-update t)
12524 (if org-display-custom-times
12525 (message "Time stamps are overlayed with custom format")
12526 (message "Time stamp overlays removed")))
12528 (defun org-display-custom-time (beg end)
12529 "Overlay modified time stamp format over timestamp between BEG and END."
12530 (let* ((ts (buffer-substring beg end))
12531 t1 w1 with-hm tf time str w2 (off 0))
12532 (save-match-data
12533 (setq t1 (org-parse-time-string ts t))
12534 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12535 (setq off (- (match-end 0) (match-beginning 0)))))
12536 (setq end (- end off))
12537 (setq w1 (- end beg)
12538 with-hm (and (nth 1 t1) (nth 2 t1))
12539 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12540 time (org-fix-decoded-time t1)
12541 str (org-add-props
12542 (format-time-string
12543 (substring tf 1 -1) (apply 'encode-time time))
12544 nil 'mouse-face 'highlight)
12545 w2 (length str))
12546 (if (not (= w2 w1))
12547 (add-text-properties (1+ beg) (+ 2 beg)
12548 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12549 (if (featurep 'xemacs)
12550 (progn
12551 (put-text-property beg end 'invisible t)
12552 (put-text-property beg end 'end-glyph (make-glyph str)))
12553 (put-text-property beg end 'display str))))
12555 (defun org-translate-time (string)
12556 "Translate all timestamps in STRING to custom format.
12557 But do this only if the variable `org-display-custom-times' is set."
12558 (when org-display-custom-times
12559 (save-match-data
12560 (let* ((start 0)
12561 (re org-ts-regexp-both)
12562 t1 with-hm inactive tf time str beg end)
12563 (while (setq start (string-match re string start))
12564 (setq beg (match-beginning 0)
12565 end (match-end 0)
12566 t1 (save-match-data
12567 (org-parse-time-string (substring string beg end) t))
12568 with-hm (and (nth 1 t1) (nth 2 t1))
12569 inactive (equal (substring string beg (1+ beg)) "[")
12570 tf (funcall (if with-hm 'cdr 'car)
12571 org-time-stamp-custom-formats)
12572 time (org-fix-decoded-time t1)
12573 str (format-time-string
12574 (concat
12575 (if inactive "[" "<") (substring tf 1 -1)
12576 (if inactive "]" ">"))
12577 (apply 'encode-time time))
12578 string (replace-match str t t string)
12579 start (+ start (length str)))))))
12580 string)
12582 (defun org-fix-decoded-time (time)
12583 "Set 0 instead of nil for the first 6 elements of time.
12584 Don't touch the rest."
12585 (let ((n 0))
12586 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12588 (defun org-days-to-time (timestamp-string)
12589 "Difference between TIMESTAMP-STRING and now in days."
12590 (- (time-to-days (org-time-string-to-time timestamp-string))
12591 (time-to-days (current-time))))
12593 (defun org-deadline-close (timestamp-string &optional ndays)
12594 "Is the time in TIMESTAMP-STRING close to the current date?"
12595 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12596 (and (< (org-days-to-time timestamp-string) ndays)
12597 (not (org-entry-is-done-p))))
12599 (defun org-get-wdays (ts)
12600 "Get the deadline lead time appropriate for timestring TS."
12601 (cond
12602 ((<= org-deadline-warning-days 0)
12603 ;; 0 or negative, enforce this value no matter what
12604 (- org-deadline-warning-days))
12605 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12606 ;; lead time is specified.
12607 (floor (* (string-to-number (match-string 1 ts))
12608 (cdr (assoc (match-string 2 ts)
12609 '(("d" . 1) ("w" . 7)
12610 ("m" . 30.4) ("y" . 365.25)))))))
12611 ;; go for the default.
12612 (t org-deadline-warning-days)))
12614 (defun org-calendar-select-mouse (ev)
12615 "Return to `org-read-date' with the date currently selected.
12616 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12617 (interactive "e")
12618 (mouse-set-point ev)
12619 (when (calendar-cursor-to-date)
12620 (let* ((date (calendar-cursor-to-date))
12621 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12622 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12623 (if (active-minibuffer-window) (exit-minibuffer))))
12625 (defun org-check-deadlines (ndays)
12626 "Check if there are any deadlines due or past due.
12627 A deadline is considered due if it happens within `org-deadline-warning-days'
12628 days from today's date. If the deadline appears in an entry marked DONE,
12629 it is not shown. The prefix arg NDAYS can be used to test that many
12630 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12631 (interactive "P")
12632 (let* ((org-warn-days
12633 (cond
12634 ((equal ndays '(4)) 100000)
12635 (ndays (prefix-numeric-value ndays))
12636 (t (abs org-deadline-warning-days))))
12637 (case-fold-search nil)
12638 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12639 (callback
12640 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12642 (message "%d deadlines past-due or due within %d days"
12643 (org-occur regexp nil callback)
12644 org-warn-days)))
12646 (defun org-check-before-date (date)
12647 "Check if there are deadlines or scheduled entries before DATE."
12648 (interactive (list (org-read-date)))
12649 (let ((case-fold-search nil)
12650 (regexp (concat "\\<\\(" org-deadline-string
12651 "\\|" org-scheduled-string
12652 "\\) *<\\([^>]+\\)>"))
12653 (callback
12654 (lambda () (time-less-p
12655 (org-time-string-to-time (match-string 2))
12656 (org-time-string-to-time date)))))
12657 (message "%d entries before %s"
12658 (org-occur regexp nil callback) date)))
12660 (defun org-check-after-date (date)
12661 "Check if there are deadlines or scheduled entries after DATE."
12662 (interactive (list (org-read-date)))
12663 (let ((case-fold-search nil)
12664 (regexp (concat "\\<\\(" org-deadline-string
12665 "\\|" org-scheduled-string
12666 "\\) *<\\([^>]+\\)>"))
12667 (callback
12668 (lambda () (not
12669 (time-less-p
12670 (org-time-string-to-time (match-string 2))
12671 (org-time-string-to-time date))))))
12672 (message "%d entries after %s"
12673 (org-occur regexp nil callback) date)))
12675 (defun org-evaluate-time-range (&optional to-buffer)
12676 "Evaluate a time range by computing the difference between start and end.
12677 Normally the result is just printed in the echo area, but with prefix arg
12678 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12679 If the time range is actually in a table, the result is inserted into the
12680 next column.
12681 For time difference computation, a year is assumed to be exactly 365
12682 days in order to avoid rounding problems."
12683 (interactive "P")
12685 (org-clock-update-time-maybe)
12686 (save-excursion
12687 (unless (org-at-date-range-p t)
12688 (goto-char (point-at-bol))
12689 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12690 (if (not (org-at-date-range-p t))
12691 (error "Not at a time-stamp range, and none found in current line")))
12692 (let* ((ts1 (match-string 1))
12693 (ts2 (match-string 2))
12694 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12695 (match-end (match-end 0))
12696 (time1 (org-time-string-to-time ts1))
12697 (time2 (org-time-string-to-time ts2))
12698 (t1 (time-to-seconds time1))
12699 (t2 (time-to-seconds time2))
12700 (diff (abs (- t2 t1)))
12701 (negative (< (- t2 t1) 0))
12702 ;; (ys (floor (* 365 24 60 60)))
12703 (ds (* 24 60 60))
12704 (hs (* 60 60))
12705 (fy "%dy %dd %02d:%02d")
12706 (fy1 "%dy %dd")
12707 (fd "%dd %02d:%02d")
12708 (fd1 "%dd")
12709 (fh "%02d:%02d")
12710 y d h m align)
12711 (if havetime
12712 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12714 d (floor (/ diff ds)) diff (mod diff ds)
12715 h (floor (/ diff hs)) diff (mod diff hs)
12716 m (floor (/ diff 60)))
12717 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12719 d (floor (+ (/ diff ds) 0.5))
12720 h 0 m 0))
12721 (if (not to-buffer)
12722 (message "%s" (org-make-tdiff-string y d h m))
12723 (if (org-at-table-p)
12724 (progn
12725 (goto-char match-end)
12726 (setq align t)
12727 (and (looking-at " *|") (goto-char (match-end 0))))
12728 (goto-char match-end))
12729 (if (looking-at
12730 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12731 (replace-match ""))
12732 (if negative (insert " -"))
12733 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12734 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12735 (insert " " (format fh h m))))
12736 (if align (org-table-align))
12737 (message "Time difference inserted")))))
12739 (defun org-make-tdiff-string (y d h m)
12740 (let ((fmt "")
12741 (l nil))
12742 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12743 l (push y l)))
12744 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12745 l (push d l)))
12746 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12747 l (push h l)))
12748 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12749 l (push m l)))
12750 (apply 'format fmt (nreverse l))))
12752 (defun org-time-string-to-time (s)
12753 (apply 'encode-time (org-parse-time-string s)))
12754 (defun org-time-string-to-seconds (s)
12755 (time-to-seconds (org-time-string-to-time s)))
12757 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12758 "Convert a time stamp to an absolute day number.
12759 If there is a specifyer for a cyclic time stamp, get the closest date to
12760 DAYNR.
12761 PREFER and SHOW-ALL are passed through to `org-closest-date'.
12762 the variable date is bound by the calendar when this is called."
12763 (cond
12764 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12765 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12766 daynr
12767 (+ daynr 1000)))
12768 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12769 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12770 (time-to-days (current-time))) (match-string 0 s)
12771 prefer show-all))
12772 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12774 (defun org-days-to-iso-week (days)
12775 "Return the iso week number."
12776 (require 'cal-iso)
12777 (car (calendar-iso-from-absolute days)))
12779 (defun org-small-year-to-year (year)
12780 "Convert 2-digit years into 4-digit years.
12781 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12782 The year 2000 cannot be abbreviated. Any year larger than 99
12783 is returned unchanged."
12784 (if (< year 38)
12785 (setq year (+ 2000 year))
12786 (if (< year 100)
12787 (setq year (+ 1900 year))))
12788 year)
12790 (defun org-time-from-absolute (d)
12791 "Return the time corresponding to date D.
12792 D may be an absolute day number, or a calendar-type list (month day year)."
12793 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12794 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12796 (defun org-calendar-holiday ()
12797 "List of holidays, for Diary display in Org-mode."
12798 (require 'holidays)
12799 (let ((hl (funcall
12800 (if (fboundp 'calendar-check-holidays)
12801 'calendar-check-holidays 'check-calendar-holidays) date)))
12802 (if hl (mapconcat 'identity hl "; "))))
12804 (defun org-diary-sexp-entry (sexp entry date)
12805 "Process a SEXP diary ENTRY for DATE."
12806 (require 'diary-lib)
12807 (let ((result (if calendar-debug-sexp
12808 (let ((stack-trace-on-error t))
12809 (eval (car (read-from-string sexp))))
12810 (condition-case nil
12811 (eval (car (read-from-string sexp)))
12812 (error
12813 (beep)
12814 (message "Bad sexp at line %d in %s: %s"
12815 (org-current-line)
12816 (buffer-file-name) sexp)
12817 (sleep-for 2))))))
12818 (cond ((stringp result) result)
12819 ((and (consp result)
12820 (stringp (cdr result))) (cdr result))
12821 (result entry)
12822 (t nil))))
12824 (defun org-diary-to-ical-string (frombuf)
12825 "Get iCalendar entries from diary entries in buffer FROMBUF.
12826 This uses the icalendar.el library."
12827 (let* ((tmpdir (if (featurep 'xemacs)
12828 (temp-directory)
12829 temporary-file-directory))
12830 (tmpfile (make-temp-name
12831 (expand-file-name "orgics" tmpdir)))
12832 buf rtn b e)
12833 (save-excursion
12834 (set-buffer frombuf)
12835 (icalendar-export-region (point-min) (point-max) tmpfile)
12836 (setq buf (find-buffer-visiting tmpfile))
12837 (set-buffer buf)
12838 (goto-char (point-min))
12839 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12840 (setq b (match-beginning 0)))
12841 (goto-char (point-max))
12842 (if (re-search-backward "^END:VEVENT" nil t)
12843 (setq e (match-end 0)))
12844 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12845 (kill-buffer buf)
12846 (delete-file tmpfile)
12847 rtn))
12849 (defun org-closest-date (start current change prefer show-all)
12850 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12851 When PREFER is `past' return a date that is either CURRENT or past.
12852 When PREFER is `future', return a date that is either CURRENT or future.
12853 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12854 ;; Make the proper lists from the dates
12855 (catch 'exit
12856 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12857 dn dw sday cday n1 n2 n0
12858 d m y y1 y2 date1 date2 nmonths nm ny m2)
12860 (setq start (org-date-to-gregorian start)
12861 current (org-date-to-gregorian
12862 (if show-all
12863 current
12864 (time-to-days (current-time))))
12865 sday (calendar-absolute-from-gregorian start)
12866 cday (calendar-absolute-from-gregorian current))
12868 (if (<= cday sday) (throw 'exit sday))
12870 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12871 (setq dn (string-to-number (match-string 1 change))
12872 dw (cdr (assoc (match-string 2 change) a1)))
12873 (error "Invalid change specifyer: %s" change))
12874 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12875 (cond
12876 ((eq dw 'day)
12877 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12878 n2 (+ n1 dn)))
12879 ((eq dw 'year)
12880 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12881 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12882 (setq date1 (list m d y1)
12883 n1 (calendar-absolute-from-gregorian date1)
12884 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12885 n2 (calendar-absolute-from-gregorian date2)))
12886 ((eq dw 'month)
12887 ;; approx number of month between the two dates
12888 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12889 ;; How often does dn fit in there?
12890 (setq d (nth 1 start) m (car start) y (nth 2 start)
12891 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12892 m (+ m nm)
12893 ny (floor (/ m 12))
12894 y (+ y ny)
12895 m (- m (* ny 12)))
12896 (while (> m 12) (setq m (- m 12) y (1+ y)))
12897 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12898 (setq m2 (+ m dn) y2 y)
12899 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12900 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12901 (while (<= n2 cday)
12902 (setq n1 n2 m m2 y y2)
12903 (setq m2 (+ m dn) y2 y)
12904 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12905 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12906 ;; Make sure n1 is the earlier date
12907 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12908 (if show-all
12909 (cond
12910 ((eq prefer 'past) n1)
12911 ((eq prefer 'future) (if (= cday n1) n1 n2))
12912 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12913 (cond
12914 ((eq prefer 'past) n1)
12915 ((eq prefer 'future) (if (= cday n1) n1 n2))
12916 (t (if (= cday n1) n1 n2)))))))
12918 (defun org-date-to-gregorian (date)
12919 "Turn any specification of DATE into a gregorian date for the calendar."
12920 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12921 ((and (listp date) (= (length date) 3)) date)
12922 ((stringp date)
12923 (setq date (org-parse-time-string date))
12924 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12925 ((listp date)
12926 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12928 (defun org-parse-time-string (s &optional nodefault)
12929 "Parse the standard Org-mode time string.
12930 This should be a lot faster than the normal `parse-time-string'.
12931 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12932 hour and minute fields will be nil if not given."
12933 (if (string-match org-ts-regexp0 s)
12934 (list 0
12935 (if (or (match-beginning 8) (not nodefault))
12936 (string-to-number (or (match-string 8 s) "0")))
12937 (if (or (match-beginning 7) (not nodefault))
12938 (string-to-number (or (match-string 7 s) "0")))
12939 (string-to-number (match-string 4 s))
12940 (string-to-number (match-string 3 s))
12941 (string-to-number (match-string 2 s))
12942 nil nil nil)
12943 (make-list 9 0)))
12945 (defun org-timestamp-up (&optional arg)
12946 "Increase the date item at the cursor by one.
12947 If the cursor is on the year, change the year. If it is on the month or
12948 the day, change that.
12949 With prefix ARG, change by that many units."
12950 (interactive "p")
12951 (org-timestamp-change (prefix-numeric-value arg)))
12953 (defun org-timestamp-down (&optional arg)
12954 "Decrease the date item at the cursor by one.
12955 If the cursor is on the year, change the year. If it is on the month or
12956 the day, change that.
12957 With prefix ARG, change by that many units."
12958 (interactive "p")
12959 (org-timestamp-change (- (prefix-numeric-value arg))))
12961 (defun org-timestamp-up-day (&optional arg)
12962 "Increase the date in the time stamp by one day.
12963 With prefix ARG, change that many days."
12964 (interactive "p")
12965 (if (and (not (org-at-timestamp-p t))
12966 (org-on-heading-p))
12967 (org-todo 'up)
12968 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12970 (defun org-timestamp-down-day (&optional arg)
12971 "Decrease the date in the time stamp by one day.
12972 With prefix ARG, change that many days."
12973 (interactive "p")
12974 (if (and (not (org-at-timestamp-p t))
12975 (org-on-heading-p))
12976 (org-todo 'down)
12977 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12979 (defun org-at-timestamp-p (&optional inactive-ok)
12980 "Determine if the cursor is in or at a timestamp."
12981 (interactive)
12982 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12983 (pos (point))
12984 (ans (or (looking-at tsr)
12985 (save-excursion
12986 (skip-chars-backward "^[<\n\r\t")
12987 (if (> (point) (point-min)) (backward-char 1))
12988 (and (looking-at tsr)
12989 (> (- (match-end 0) pos) -1))))))
12990 (and ans
12991 (boundp 'org-ts-what)
12992 (setq org-ts-what
12993 (cond
12994 ((= pos (match-beginning 0)) 'bracket)
12995 ((= pos (1- (match-end 0))) 'bracket)
12996 ((org-pos-in-match-range pos 2) 'year)
12997 ((org-pos-in-match-range pos 3) 'month)
12998 ((org-pos-in-match-range pos 7) 'hour)
12999 ((org-pos-in-match-range pos 8) 'minute)
13000 ((or (org-pos-in-match-range pos 4)
13001 (org-pos-in-match-range pos 5)) 'day)
13002 ((and (> pos (or (match-end 8) (match-end 5)))
13003 (< pos (match-end 0)))
13004 (- pos (or (match-end 8) (match-end 5))))
13005 (t 'day))))
13006 ans))
13008 (defun org-toggle-timestamp-type ()
13009 "Toggle the type (<active> or [inactive]) of a time stamp."
13010 (interactive)
13011 (when (org-at-timestamp-p t)
13012 (let ((beg (match-beginning 0)) (end (match-end 0))
13013 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13014 (save-excursion
13015 (goto-char beg)
13016 (while (re-search-forward "[][<>]" end t)
13017 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13018 t t)))
13019 (message "Timestamp is now %sactive"
13020 (if (equal (char-after beg) ?<) "" "in")))))
13022 (defun org-timestamp-change (n &optional what)
13023 "Change the date in the time stamp at point.
13024 The date will be changed by N times WHAT. WHAT can be `day', `month',
13025 `year', `minute', `second'. If WHAT is not given, the cursor position
13026 in the timestamp determines what will be changed."
13027 (let ((pos (point))
13028 with-hm inactive
13029 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13030 org-ts-what
13031 extra rem
13032 ts time time0)
13033 (if (not (org-at-timestamp-p t))
13034 (error "Not at a timestamp"))
13035 (if (and (not what) (eq org-ts-what 'bracket))
13036 (org-toggle-timestamp-type)
13037 (if (and (not what) (not (eq org-ts-what 'day))
13038 org-display-custom-times
13039 (get-text-property (point) 'display)
13040 (not (get-text-property (1- (point)) 'display)))
13041 (setq org-ts-what 'day))
13042 (setq org-ts-what (or what org-ts-what)
13043 inactive (= (char-after (match-beginning 0)) ?\[)
13044 ts (match-string 0))
13045 (replace-match "")
13046 (if (string-match
13047 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
13049 (setq extra (match-string 1 ts)))
13050 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13051 (setq with-hm t))
13052 (setq time0 (org-parse-time-string ts))
13053 (when (and (eq org-ts-what 'minute)
13054 (eq current-prefix-arg nil))
13055 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13056 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13057 (setcar (cdr time0) (+ (nth 1 time0)
13058 (if (> n 0) (- rem) (- dm rem))))))
13059 (setq time
13060 (encode-time (or (car time0) 0)
13061 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13062 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13063 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13064 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13065 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13066 (nthcdr 6 time0)))
13067 (when (and (member org-ts-what '(hour minute))
13068 extra
13069 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13070 (setq extra (org-modify-ts-extra
13071 extra
13072 (if (eq org-ts-what 'hour) 2 5)
13073 n dm)))
13074 (when (integerp org-ts-what)
13075 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13076 (if (eq what 'calendar)
13077 (let ((cal-date (org-get-date-from-calendar)))
13078 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13079 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13080 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13081 (setcar time0 (or (car time0) 0))
13082 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13083 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13084 (setq time (apply 'encode-time time0))))
13085 (setq org-last-changed-timestamp
13086 (org-insert-time-stamp time with-hm inactive nil nil extra))
13087 (org-clock-update-time-maybe)
13088 (goto-char pos)
13089 ;; Try to recenter the calendar window, if any
13090 (if (and org-calendar-follow-timestamp-change
13091 (get-buffer-window "*Calendar*" t)
13092 (memq org-ts-what '(day month year)))
13093 (org-recenter-calendar (time-to-days time))))))
13095 (defun org-modify-ts-extra (s pos n dm)
13096 "Change the different parts of the lead-time and repeat fields in timestamp."
13097 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13098 ng h m new rem)
13099 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13100 (cond
13101 ((or (org-pos-in-match-range pos 2)
13102 (org-pos-in-match-range pos 3))
13103 (setq m (string-to-number (match-string 3 s))
13104 h (string-to-number (match-string 2 s)))
13105 (if (org-pos-in-match-range pos 2)
13106 (setq h (+ h n))
13107 (setq n (* dm (org-no-warnings (signum n))))
13108 (when (not (= 0 (setq rem (% m dm))))
13109 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13110 (setq m (+ m n)))
13111 (if (< m 0) (setq m (+ m 60) h (1- h)))
13112 (if (> m 59) (setq m (- m 60) h (1+ h)))
13113 (setq h (min 24 (max 0 h)))
13114 (setq ng 1 new (format "-%02d:%02d" h m)))
13115 ((org-pos-in-match-range pos 6)
13116 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13117 ((org-pos-in-match-range pos 5)
13118 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13120 ((org-pos-in-match-range pos 9)
13121 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13122 ((org-pos-in-match-range pos 8)
13123 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13125 (when ng
13126 (setq s (concat
13127 (substring s 0 (match-beginning ng))
13129 (substring s (match-end ng))))))
13132 (defun org-recenter-calendar (date)
13133 "If the calendar is visible, recenter it to DATE."
13134 (let* ((win (selected-window))
13135 (cwin (get-buffer-window "*Calendar*" t))
13136 (calendar-move-hook nil))
13137 (when cwin
13138 (select-window cwin)
13139 (calendar-goto-date (if (listp date) date
13140 (calendar-gregorian-from-absolute date)))
13141 (select-window win))))
13143 (defun org-goto-calendar (&optional arg)
13144 "Go to the Emacs calendar at the current date.
13145 If there is a time stamp in the current line, go to that date.
13146 A prefix ARG can be used to force the current date."
13147 (interactive "P")
13148 (let ((tsr org-ts-regexp) diff
13149 (calendar-move-hook nil)
13150 (calendar-view-holidays-initially-flag nil)
13151 (view-calendar-holidays-initially nil)
13152 (calendar-view-diary-initially-flag nil)
13153 (view-diary-entries-initially nil))
13154 (if (or (org-at-timestamp-p)
13155 (save-excursion
13156 (beginning-of-line 1)
13157 (looking-at (concat ".*" tsr))))
13158 (let ((d1 (time-to-days (current-time)))
13159 (d2 (time-to-days
13160 (org-time-string-to-time (match-string 1)))))
13161 (setq diff (- d2 d1))))
13162 (calendar)
13163 (calendar-goto-today)
13164 (if (and diff (not arg)) (calendar-forward-day diff))))
13166 (defun org-get-date-from-calendar ()
13167 "Return a list (month day year) of date at point in calendar."
13168 (with-current-buffer "*Calendar*"
13169 (save-match-data
13170 (calendar-cursor-to-date))))
13172 (defun org-date-from-calendar ()
13173 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13174 If there is already a time stamp at the cursor position, update it."
13175 (interactive)
13176 (if (org-at-timestamp-p t)
13177 (org-timestamp-change 0 'calendar)
13178 (let ((cal-date (org-get-date-from-calendar)))
13179 (org-insert-time-stamp
13180 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13182 (defun org-minutes-to-hh:mm-string (m)
13183 "Compute H:MM from a number of minutes."
13184 (let ((h (/ m 60)))
13185 (setq m (- m (* 60 h)))
13186 (format org-time-clocksum-format h m)))
13188 (defun org-hh:mm-string-to-minutes (s)
13189 "Convert a string H:MM to a number of minutes.
13190 If the string is just a number, interprete it as minutes.
13191 In fact, the first hh:mm or number in the string will be taken,
13192 there can be extra stuff in the string.
13193 If no number is found, the return value is 0."
13194 (cond
13195 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13196 (+ (* (string-to-number (match-string 1 s)) 60)
13197 (string-to-number (match-string 2 s))))
13198 ((string-match "\\([0-9]+\\)" s)
13199 (string-to-number (match-string 1 s)))
13200 (t 0)))
13202 ;;;; Files
13204 (defun org-save-all-org-buffers ()
13205 "Save all Org-mode buffers without user confirmation."
13206 (interactive)
13207 (message "Saving all Org-mode buffers...")
13208 (save-some-buffers t 'org-mode-p)
13209 (when (featurep 'org-id) (org-id-locations-save))
13210 (message "Saving all Org-mode buffers... done"))
13212 (defun org-revert-all-org-buffers ()
13213 "Revert all Org-mode buffers.
13214 Prompt for confirmation when there are unsaved changes.
13215 Be sure you know what you are doing before letting this function
13216 overwrite your changes.
13218 This function is useful in a setup where one tracks org files
13219 with a version control system, to revert on one machine after pulling
13220 changes from another. I believe the procedure must be like this:
13222 1. M-x org-save-all-org-buffers
13223 2. Pull changes from the other machine, resolve conflicts
13224 3. M-x org-revert-all-org-buffers"
13225 (interactive)
13226 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13227 (error "Abort"))
13228 (save-excursion
13229 (save-window-excursion
13230 (mapc
13231 (lambda (b)
13232 (when (and (with-current-buffer b (org-mode-p))
13233 (with-current-buffer b buffer-file-name))
13234 (switch-to-buffer b)
13235 (revert-buffer t 'no-confirm)))
13236 (buffer-list))
13237 (when (and (featurep 'org-id) org-id-track-globally)
13238 (org-id-locations-load)))))
13240 ;;;; Agenda files
13242 ;;;###autoload
13243 (defun org-iswitchb (&optional arg)
13244 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13245 With a prefix argument, restrict available to files.
13246 With two prefix arguments, restrict available buffers to agenda files.
13248 Due to some yet unresolved reason, the global function
13249 `iswitchb-mode' needs to be active for this function to work."
13250 (interactive "P")
13251 (require 'iswitchb)
13252 (let ((enabled iswitchb-mode) blist)
13253 (or enabled (iswitchb-mode 1))
13254 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13255 ((equal arg '(16)) (org-buffer-list 'agenda))
13256 (t (org-buffer-list))))
13257 (unwind-protect
13258 (let ((iswitchb-make-buflist-hook
13259 (lambda ()
13260 (setq iswitchb-temp-buflist
13261 (mapcar 'buffer-name blist)))))
13262 (switch-to-buffer
13263 (iswitchb-read-buffer
13264 "Switch-to: " nil t))
13265 (or enabled (iswitchb-mode -1))))))
13267 ;;;###autoload
13268 (defun org-ido-switchb (&optional arg)
13269 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
13270 With a prefix argument, restrict available to files.
13271 With two prefix arguments, restrict available buffers to agenda files."
13272 (interactive "P")
13273 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13274 ((equal arg '(16)) (org-buffer-list 'agenda))
13275 (t (org-buffer-list)))))
13276 (switch-to-buffer
13277 (org-ido-completing-read "Org buffer: "
13278 (mapcar 'list (mapcar 'buffer-name blist))
13279 nil t))))
13281 (defun org-buffer-list (&optional predicate exclude-tmp)
13282 "Return a list of Org buffers.
13283 PREDICATE can be `export', `files' or `agenda'.
13285 export restrict the list to Export buffers.
13286 files restrict the list to buffers visiting Org files.
13287 agenda restrict the list to buffers visiting agenda files.
13289 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13290 (let* ((bfn nil)
13291 (agenda-files (and (eq predicate 'agenda)
13292 (mapcar 'file-truename (org-agenda-files t))))
13293 (filter
13294 (cond
13295 ((eq predicate 'files)
13296 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13297 ((eq predicate 'export)
13298 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13299 ((eq predicate 'agenda)
13300 (lambda (b)
13301 (with-current-buffer b
13302 (and (eq major-mode 'org-mode)
13303 (setq bfn (buffer-file-name b))
13304 (member (file-truename bfn) agenda-files)))))
13305 (t (lambda (b) (with-current-buffer b
13306 (or (eq major-mode 'org-mode)
13307 (string-match "\*Org .*Export"
13308 (buffer-name b)))))))))
13309 (delq nil
13310 (mapcar
13311 (lambda(b)
13312 (if (and (funcall filter b)
13313 (or (not exclude-tmp)
13314 (not (string-match "tmp" (buffer-name b)))))
13316 nil))
13317 (buffer-list)))))
13319 (defun org-agenda-files (&optional unrestricted archives)
13320 "Get the list of agenda files.
13321 Optional UNRESTRICTED means return the full list even if a restriction
13322 is currently in place.
13323 When ARCHIVES is t, include all archive files hat are really being
13324 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13325 `org-agenda-archives-mode' is t."
13326 (let ((files
13327 (cond
13328 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13329 ((stringp org-agenda-files) (org-read-agenda-file-list))
13330 ((listp org-agenda-files) org-agenda-files)
13331 (t (error "Invalid value of `org-agenda-files'")))))
13332 (setq files (apply 'append
13333 (mapcar (lambda (f)
13334 (if (file-directory-p f)
13335 (directory-files
13336 f t org-agenda-file-regexp)
13337 (list f)))
13338 files)))
13339 (when org-agenda-skip-unavailable-files
13340 (setq files (delq nil
13341 (mapcar (function
13342 (lambda (file)
13343 (and (file-readable-p file) file)))
13344 files))))
13345 (when (or (eq archives t)
13346 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13347 (setq files (org-add-archive-files files)))
13348 files))
13350 (defun org-edit-agenda-file-list ()
13351 "Edit the list of agenda files.
13352 Depending on setup, this either uses customize to edit the variable
13353 `org-agenda-files', or it visits the file that is holding the list. In the
13354 latter case, the buffer is set up in a way that saving it automatically kills
13355 the buffer and restores the previous window configuration."
13356 (interactive)
13357 (if (stringp org-agenda-files)
13358 (let ((cw (current-window-configuration)))
13359 (find-file org-agenda-files)
13360 (org-set-local 'org-window-configuration cw)
13361 (org-add-hook 'after-save-hook
13362 (lambda ()
13363 (set-window-configuration
13364 (prog1 org-window-configuration
13365 (kill-buffer (current-buffer))))
13366 (org-install-agenda-files-menu)
13367 (message "New agenda file list installed"))
13368 nil 'local)
13369 (message "%s" (substitute-command-keys
13370 "Edit list and finish with \\[save-buffer]")))
13371 (customize-variable 'org-agenda-files)))
13373 (defun org-store-new-agenda-file-list (list)
13374 "Set new value for the agenda file list and save it correctly."
13375 (if (stringp org-agenda-files)
13376 (let ((f org-agenda-files) b)
13377 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13378 (with-temp-file f
13379 (insert (mapconcat 'identity list "\n") "\n")))
13380 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13381 (setq org-agenda-files list)
13382 (customize-save-variable 'org-agenda-files org-agenda-files))))
13384 (defun org-read-agenda-file-list ()
13385 "Read the list of agenda files from a file."
13386 (when (file-directory-p org-agenda-files)
13387 (error "`org-agenda-files' cannot be a single directory"))
13388 (when (stringp org-agenda-files)
13389 (with-temp-buffer
13390 (insert-file-contents org-agenda-files)
13391 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13394 ;;;###autoload
13395 (defun org-cycle-agenda-files ()
13396 "Cycle through the files in `org-agenda-files'.
13397 If the current buffer visits an agenda file, find the next one in the list.
13398 If the current buffer does not, find the first agenda file."
13399 (interactive)
13400 (let* ((fs (org-agenda-files t))
13401 (files (append fs (list (car fs))))
13402 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13403 file)
13404 (unless files (error "No agenda files"))
13405 (catch 'exit
13406 (while (setq file (pop files))
13407 (if (equal (file-truename file) tcf)
13408 (when (car files)
13409 (find-file (car files))
13410 (throw 'exit t))))
13411 (find-file (car fs)))
13412 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13414 (defun org-agenda-file-to-front (&optional to-end)
13415 "Move/add the current file to the top of the agenda file list.
13416 If the file is not present in the list, it is added to the front. If it is
13417 present, it is moved there. With optional argument TO-END, add/move to the
13418 end of the list."
13419 (interactive "P")
13420 (let ((org-agenda-skip-unavailable-files nil)
13421 (file-alist (mapcar (lambda (x)
13422 (cons (file-truename x) x))
13423 (org-agenda-files t)))
13424 (ctf (file-truename buffer-file-name))
13425 x had)
13426 (setq x (assoc ctf file-alist) had x)
13428 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13429 (if to-end
13430 (setq file-alist (append (delq x file-alist) (list x)))
13431 (setq file-alist (cons x (delq x file-alist))))
13432 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13433 (org-install-agenda-files-menu)
13434 (message "File %s to %s of agenda file list"
13435 (if had "moved" "added") (if to-end "end" "front"))))
13437 (defun org-remove-file (&optional file)
13438 "Remove current file from the list of files in variable `org-agenda-files'.
13439 These are the files which are being checked for agenda entries.
13440 Optional argument FILE means, use this file instead of the current."
13441 (interactive)
13442 (let* ((org-agenda-skip-unavailable-files nil)
13443 (file (or file buffer-file-name))
13444 (true-file (file-truename file))
13445 (afile (abbreviate-file-name file))
13446 (files (delq nil (mapcar
13447 (lambda (x)
13448 (if (equal true-file
13449 (file-truename x))
13450 nil x))
13451 (org-agenda-files t)))))
13452 (if (not (= (length files) (length (org-agenda-files t))))
13453 (progn
13454 (org-store-new-agenda-file-list files)
13455 (org-install-agenda-files-menu)
13456 (message "Removed file: %s" afile))
13457 (message "File was not in list: %s (not removed)" afile))))
13459 (defun org-file-menu-entry (file)
13460 (vector file (list 'find-file file) t))
13462 (defun org-check-agenda-file (file)
13463 "Make sure FILE exists. If not, ask user what to do."
13464 (when (not (file-exists-p file))
13465 (message "non-existent file %s. [R]emove from list or [A]bort?"
13466 (abbreviate-file-name file))
13467 (let ((r (downcase (read-char-exclusive))))
13468 (cond
13469 ((equal r ?r)
13470 (org-remove-file file)
13471 (throw 'nextfile t))
13472 (t (error "Abort"))))))
13474 (defun org-get-agenda-file-buffer (file)
13475 "Get a buffer visiting FILE. If the buffer needs to be created, add
13476 it to the list of buffers which might be released later."
13477 (let ((buf (org-find-base-buffer-visiting file)))
13478 (if buf
13479 buf ; just return it
13480 ;; Make a new buffer and remember it
13481 (setq buf (find-file-noselect file))
13482 (if buf (push buf org-agenda-new-buffers))
13483 buf)))
13485 (defun org-release-buffers (blist)
13486 "Release all buffers in list, asking the user for confirmation when needed.
13487 When a buffer is unmodified, it is just killed. When modified, it is saved
13488 \(if the user agrees) and then killed."
13489 (let (buf file)
13490 (while (setq buf (pop blist))
13491 (setq file (buffer-file-name buf))
13492 (when (and (buffer-modified-p buf)
13493 file
13494 (y-or-n-p (format "Save file %s? " file)))
13495 (with-current-buffer buf (save-buffer)))
13496 (kill-buffer buf))))
13498 (defun org-prepare-agenda-buffers (files)
13499 "Create buffers for all agenda files, protect archived trees and comments."
13500 (interactive)
13501 (let ((pa '(:org-archived t))
13502 (pc '(:org-comment t))
13503 (pall '(:org-archived t :org-comment t))
13504 (inhibit-read-only t)
13505 (rea (concat ":" org-archive-tag ":"))
13506 bmp file re)
13507 (save-excursion
13508 (save-restriction
13509 (while (setq file (pop files))
13510 (catch 'nextfile
13511 (if (bufferp file)
13512 (set-buffer file)
13513 (org-check-agenda-file file)
13514 (set-buffer (org-get-agenda-file-buffer file)))
13515 (widen)
13516 (setq bmp (buffer-modified-p))
13517 (org-refresh-category-properties)
13518 (setq org-todo-keywords-for-agenda
13519 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13520 (setq org-done-keywords-for-agenda
13521 (append org-done-keywords-for-agenda org-done-keywords))
13522 (setq org-todo-keyword-alist-for-agenda
13523 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13524 (setq org-tag-alist-for-agenda
13525 (append org-tag-alist-for-agenda org-tag-alist))
13527 (save-excursion
13528 (remove-text-properties (point-min) (point-max) pall)
13529 (when org-agenda-skip-archived-trees
13530 (goto-char (point-min))
13531 (while (re-search-forward rea nil t)
13532 (if (org-on-heading-p t)
13533 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13534 (goto-char (point-min))
13535 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13536 (while (re-search-forward re nil t)
13537 (add-text-properties
13538 (match-beginning 0) (org-end-of-subtree t) pc)))
13539 (set-buffer-modified-p bmp)))))
13540 (setq org-todo-keyword-alist-for-agenda
13541 (org-uniquify org-todo-keyword-alist-for-agenda)
13542 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13544 ;;;; Embedded LaTeX
13546 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13547 "Keymap for the minor `org-cdlatex-mode'.")
13549 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13550 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13551 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13552 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13553 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13555 (defvar org-cdlatex-texmathp-advice-is-done nil
13556 "Flag remembering if we have applied the advice to texmathp already.")
13558 (define-minor-mode org-cdlatex-mode
13559 "Toggle the minor `org-cdlatex-mode'.
13560 This mode supports entering LaTeX environment and math in LaTeX fragments
13561 in Org-mode.
13562 \\{org-cdlatex-mode-map}"
13563 nil " OCDL" nil
13564 (when org-cdlatex-mode (require 'cdlatex))
13565 (unless org-cdlatex-texmathp-advice-is-done
13566 (setq org-cdlatex-texmathp-advice-is-done t)
13567 (defadvice texmathp (around org-math-always-on activate)
13568 "Always return t in org-mode buffers.
13569 This is because we want to insert math symbols without dollars even outside
13570 the LaTeX math segments. If Orgmode thinks that point is actually inside
13571 an embedded LaTeX fragment, let texmathp do its job.
13572 \\[org-cdlatex-mode-map]"
13573 (interactive)
13574 (let (p)
13575 (cond
13576 ((not (org-mode-p)) ad-do-it)
13577 ((eq this-command 'cdlatex-math-symbol)
13578 (setq ad-return-value t
13579 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13581 (let ((p (org-inside-LaTeX-fragment-p)))
13582 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13583 (setq ad-return-value t
13584 texmathp-why '("Org-mode embedded math" . 0))
13585 (if p ad-do-it)))))))))
13587 (defun turn-on-org-cdlatex ()
13588 "Unconditionally turn on `org-cdlatex-mode'."
13589 (org-cdlatex-mode 1))
13591 (defun org-inside-LaTeX-fragment-p ()
13592 "Test if point is inside a LaTeX fragment.
13593 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13594 sequence appearing also before point.
13595 Even though the matchers for math are configurable, this function assumes
13596 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13597 delimiters are skipped when they have been removed by customization.
13598 The return value is nil, or a cons cell with the delimiter and
13599 and the position of this delimiter.
13601 This function does a reasonably good job, but can locally be fooled by
13602 for example currency specifications. For example it will assume being in
13603 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13604 fragments that are properly closed, but during editing, we have to live
13605 with the uncertainty caused by missing closing delimiters. This function
13606 looks only before point, not after."
13607 (catch 'exit
13608 (let ((pos (point))
13609 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13610 (lim (progn
13611 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13612 (point)))
13613 dd-on str (start 0) m re)
13614 (goto-char pos)
13615 (when dodollar
13616 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13617 re (nth 1 (assoc "$" org-latex-regexps)))
13618 (while (string-match re str start)
13619 (cond
13620 ((= (match-end 0) (length str))
13621 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13622 ((= (match-end 0) (- (length str) 5))
13623 (throw 'exit nil))
13624 (t (setq start (match-end 0))))))
13625 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13626 (goto-char pos)
13627 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13628 (and (match-beginning 2) (throw 'exit nil))
13629 ;; count $$
13630 (while (re-search-backward "\\$\\$" lim t)
13631 (setq dd-on (not dd-on)))
13632 (goto-char pos)
13633 (if dd-on (cons "$$" m))))))
13636 (defun org-try-cdlatex-tab ()
13637 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13638 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13639 - inside a LaTeX fragment, or
13640 - after the first word in a line, where an abbreviation expansion could
13641 insert a LaTeX environment."
13642 (when org-cdlatex-mode
13643 (cond
13644 ((save-excursion
13645 (skip-chars-backward "a-zA-Z0-9*")
13646 (skip-chars-backward " \t")
13647 (bolp))
13648 (cdlatex-tab) t)
13649 ((org-inside-LaTeX-fragment-p)
13650 (cdlatex-tab) t)
13651 (t nil))))
13653 (defun org-cdlatex-underscore-caret (&optional arg)
13654 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13655 Revert to the normal definition outside of these fragments."
13656 (interactive "P")
13657 (if (org-inside-LaTeX-fragment-p)
13658 (call-interactively 'cdlatex-sub-superscript)
13659 (let (org-cdlatex-mode)
13660 (call-interactively (key-binding (vector last-input-event))))))
13662 (defun org-cdlatex-math-modify (&optional arg)
13663 "Execute `cdlatex-math-modify' in LaTeX fragments.
13664 Revert to the normal definition outside of these fragments."
13665 (interactive "P")
13666 (if (org-inside-LaTeX-fragment-p)
13667 (call-interactively 'cdlatex-math-modify)
13668 (let (org-cdlatex-mode)
13669 (call-interactively (key-binding (vector last-input-event))))))
13671 (defvar org-latex-fragment-image-overlays nil
13672 "List of overlays carrying the images of latex fragments.")
13673 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13675 (defun org-remove-latex-fragment-image-overlays ()
13676 "Remove all overlays with LaTeX fragment images in current buffer."
13677 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13678 (setq org-latex-fragment-image-overlays nil))
13680 (defun org-preview-latex-fragment (&optional subtree)
13681 "Preview the LaTeX fragment at point, or all locally or globally.
13682 If the cursor is in a LaTeX fragment, create the image and overlay
13683 it over the source code. If there is no fragment at point, display
13684 all fragments in the current text, from one headline to the next. With
13685 prefix SUBTREE, display all fragments in the current subtree. With a
13686 double prefix `C-u C-u', or when the cursor is before the first headline,
13687 display all fragments in the buffer.
13688 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13689 (interactive "P")
13690 (org-remove-latex-fragment-image-overlays)
13691 (save-excursion
13692 (save-restriction
13693 (let (beg end at msg)
13694 (cond
13695 ((or (equal subtree '(16))
13696 (not (save-excursion
13697 (re-search-backward (concat "^" outline-regexp) nil t))))
13698 (setq beg (point-min) end (point-max)
13699 msg "Creating images for buffer...%s"))
13700 ((equal subtree '(4))
13701 (org-back-to-heading)
13702 (setq beg (point) end (org-end-of-subtree t)
13703 msg "Creating images for subtree...%s"))
13705 (if (setq at (org-inside-LaTeX-fragment-p))
13706 (goto-char (max (point-min) (- (cdr at) 2)))
13707 (org-back-to-heading))
13708 (setq beg (point) end (progn (outline-next-heading) (point))
13709 msg (if at "Creating image...%s"
13710 "Creating images for entry...%s"))))
13711 (message msg "")
13712 (narrow-to-region beg end)
13713 (goto-char beg)
13714 (org-format-latex
13715 (concat "ltxpng/" (file-name-sans-extension
13716 (file-name-nondirectory
13717 buffer-file-name)))
13718 default-directory 'overlays msg at 'forbuffer)
13719 (message msg "done. Use `C-c C-c' to remove images.")))))
13721 (defvar org-latex-regexps
13722 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13723 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13724 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13725 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13726 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13727 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13728 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13729 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13730 "Regular expressions for matching embedded LaTeX.")
13732 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13733 "Replace LaTeX fragments with links to an image, and produce images."
13734 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13735 (let* ((prefixnodir (file-name-nondirectory prefix))
13736 (absprefix (expand-file-name prefix dir))
13737 (todir (file-name-directory absprefix))
13738 (opt org-format-latex-options)
13739 (matchers (plist-get opt :matchers))
13740 (re-list org-latex-regexps)
13741 (cnt 0) txt link beg end re e checkdir
13742 executables-checked
13743 m n block linkfile movefile ov)
13744 ;; Check if there are old images files with this prefix, and remove them
13745 (when (file-directory-p todir)
13746 (mapc 'delete-file
13747 (directory-files
13748 todir 'full
13749 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13750 ;; Check the different regular expressions
13751 (while (setq e (pop re-list))
13752 (setq m (car e) re (nth 1 e) n (nth 2 e)
13753 block (if (nth 3 e) "\n\n" ""))
13754 (when (member m matchers)
13755 (goto-char (point-min))
13756 (while (re-search-forward re nil t)
13757 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13758 (not (get-text-property (match-beginning n)
13759 'org-protected)))
13760 (setq txt (match-string n)
13761 beg (match-beginning n) end (match-end n)
13762 cnt (1+ cnt)
13763 linkfile (format "%s_%04d.png" prefix cnt)
13764 movefile (format "%s_%04d.png" absprefix cnt)
13765 link (concat block "[[file:" linkfile "]]" block))
13766 (if msg (message msg cnt))
13767 (goto-char beg)
13768 (unless checkdir ; make sure the directory exists
13769 (setq checkdir t)
13770 (or (file-directory-p todir) (make-directory todir)))
13772 (unless executables-checked
13773 (org-check-external-command
13774 "latex" "needed to convert LaTeX fragments to images")
13775 (org-check-external-command
13776 "dvipng" "needed to convert LaTeX fragments to images")
13777 (setq executables-checked t))
13779 (org-create-formula-image
13780 txt movefile opt forbuffer)
13781 (if overlays
13782 (progn
13783 (setq ov (org-make-overlay beg end))
13784 (if (featurep 'xemacs)
13785 (progn
13786 (org-overlay-put ov 'invisible t)
13787 (org-overlay-put
13788 ov 'end-glyph
13789 (make-glyph (vector 'png :file movefile))))
13790 (org-overlay-put
13791 ov 'display
13792 (list 'image :type 'png :file movefile :ascent 'center)))
13793 (push ov org-latex-fragment-image-overlays)
13794 (goto-char end))
13795 (delete-region beg end)
13796 (insert link))))))))
13798 ;; This function borrows from Ganesh Swami's latex2png.el
13799 (defun org-create-formula-image (string tofile options buffer)
13800 (let* ((tmpdir (if (featurep 'xemacs)
13801 (temp-directory)
13802 temporary-file-directory))
13803 (texfilebase (make-temp-name
13804 (expand-file-name "orgtex" tmpdir)))
13805 (texfile (concat texfilebase ".tex"))
13806 (dvifile (concat texfilebase ".dvi"))
13807 (pngfile (concat texfilebase ".png"))
13808 (fnh (if (featurep 'xemacs)
13809 (font-height (get-face-font 'default))
13810 (face-attribute 'default :height nil)))
13811 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13812 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13813 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13814 "Black"))
13815 (bg (or (plist-get options (if buffer :background :html-background))
13816 "Transparent")))
13817 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13818 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13819 (with-temp-file texfile
13820 (insert org-format-latex-header
13821 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13822 (let ((dir default-directory))
13823 (condition-case nil
13824 (progn
13825 (cd tmpdir)
13826 (call-process "latex" nil nil nil texfile))
13827 (error nil))
13828 (cd dir))
13829 (if (not (file-exists-p dvifile))
13830 (progn (message "Failed to create dvi file from %s" texfile) nil)
13831 (condition-case nil
13832 (call-process "dvipng" nil nil nil
13833 "-E" "-fg" fg "-bg" bg
13834 "-D" dpi
13835 ;;"-x" scale "-y" scale
13836 "-T" "tight"
13837 "-o" pngfile
13838 dvifile)
13839 (error nil))
13840 (if (not (file-exists-p pngfile))
13841 (progn (message "Failed to create png file from %s" texfile) nil)
13842 ;; Use the requested file name and clean up
13843 (copy-file pngfile tofile 'replace)
13844 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13845 (delete-file (concat texfilebase e)))
13846 pngfile))))
13848 (defun org-dvipng-color (attr)
13849 "Return an rgb color specification for dvipng."
13850 (apply 'format "rgb %s %s %s"
13851 (mapcar 'org-normalize-color
13852 (color-values (face-attribute 'default attr nil)))))
13854 (defun org-normalize-color (value)
13855 "Return string to be used as color value for an RGB component."
13856 (format "%g" (/ value 65535.0)))
13858 ;;;; Key bindings
13860 ;; Make `C-c C-x' a prefix key
13861 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13863 ;; TAB key with modifiers
13864 (org-defkey org-mode-map "\C-i" 'org-cycle)
13865 (org-defkey org-mode-map [(tab)] 'org-cycle)
13866 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13867 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13868 (org-defkey org-mode-map "\M-\t" 'org-complete)
13869 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13870 ;; The following line is necessary under Suse GNU/Linux
13871 (unless (featurep 'xemacs)
13872 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13873 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13874 (define-key org-mode-map [backtab] 'org-shifttab)
13876 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13877 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13878 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13880 ;; Cursor keys with modifiers
13881 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13882 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13883 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13884 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13886 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13887 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13888 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13889 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13891 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13892 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13893 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13894 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13896 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13897 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13899 ;;; Extra keys for tty access.
13900 ;; We only set them when really needed because otherwise the
13901 ;; menus don't show the simple keys
13903 (when (or org-use-extra-keys
13904 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13905 (not window-system))
13906 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13907 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13908 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13909 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13910 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13911 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13912 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13913 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13914 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13915 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13916 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13917 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13918 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13919 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13920 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13921 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13922 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13923 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13924 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13925 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13926 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13927 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
13928 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
13929 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
13930 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
13931 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
13932 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
13933 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
13935 ;; All the other keys
13937 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13938 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13939 (if (boundp 'narrow-map)
13940 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13941 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13942 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
13943 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
13944 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13945 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13946 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13947 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13948 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13949 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13950 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13951 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13952 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13953 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13954 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13955 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13956 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13957 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13958 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13959 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13960 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13961 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13962 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13963 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13964 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13965 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13966 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13967 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13968 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13969 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13970 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13971 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13972 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13973 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13974 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13975 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13976 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13977 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13978 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13979 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13980 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13981 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13982 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13983 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13984 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13985 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13986 (org-defkey org-mode-map "\C-c^" 'org-sort)
13987 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13988 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13989 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13990 (org-defkey org-mode-map "\C-m" 'org-return)
13991 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13992 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13993 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13994 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13995 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13996 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13997 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13998 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13999 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14000 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14001 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14002 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14003 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14004 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14005 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14006 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14007 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14009 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14010 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14011 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14012 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14014 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14015 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14016 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14017 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14018 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14019 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14020 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14021 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14022 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14023 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14024 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14025 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14026 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14028 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14029 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14030 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14031 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14033 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14035 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14037 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14038 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14040 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14043 (when (featurep 'xemacs)
14044 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14047 (defvar org-self-insert-command-undo-counter 0)
14049 (defvar org-table-auto-blank-field) ; defined in org-table.el
14050 (defun org-self-insert-command (N)
14051 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14052 If the cursor is in a table looking at whitespace, the whitespace is
14053 overwritten, and the table is not marked as requiring realignment."
14054 (interactive "p")
14055 (if (and
14056 (org-table-p)
14057 (progn
14058 ;; check if we blank the field, and if that triggers align
14059 (and (featurep 'org-table) org-table-auto-blank-field
14060 (member last-command
14061 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14062 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14063 ;; got extra space, this field does not determine column width
14064 (let (org-table-may-need-update) (org-table-blank-field))
14065 ;; no extra space, this field may determine column width
14066 (org-table-blank-field)))
14068 (eq N 1)
14069 (looking-at "[^|\n]* |"))
14070 (let (org-table-may-need-update)
14071 (goto-char (1- (match-end 0)))
14072 (delete-backward-char 1)
14073 (goto-char (match-beginning 0))
14074 (self-insert-command N))
14075 (setq org-table-may-need-update t)
14076 (self-insert-command N)
14077 (org-fix-tags-on-the-fly)
14078 (if org-self-insert-cluster-for-undo
14079 (if (not (eq last-command 'org-self-insert-command))
14080 (setq org-self-insert-command-undo-counter 1)
14081 (if (>= org-self-insert-command-undo-counter 20)
14082 (setq org-self-insert-command-undo-counter 1)
14083 (and (> org-self-insert-command-undo-counter 0)
14084 buffer-undo-list
14085 (not (cadr buffer-undo-list)) ; remove nil entry
14086 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14087 (setq org-self-insert-command-undo-counter
14088 (1+ org-self-insert-command-undo-counter)))))))
14090 (defun org-fix-tags-on-the-fly ()
14091 (when (and (equal (char-after (point-at-bol)) ?*)
14092 (org-on-heading-p))
14093 (org-align-tags-here org-tags-column)))
14095 (defun org-delete-backward-char (N)
14096 "Like `delete-backward-char', insert whitespace at field end in tables.
14097 When deleting backwards, in tables this function will insert whitespace in
14098 front of the next \"|\" separator, to keep the table aligned. The table will
14099 still be marked for re-alignment if the field did fill the entire column,
14100 because, in this case the deletion might narrow the column."
14101 (interactive "p")
14102 (if (and (org-table-p)
14103 (eq N 1)
14104 (string-match "|" (buffer-substring (point-at-bol) (point)))
14105 (looking-at ".*?|"))
14106 (let ((pos (point))
14107 (noalign (looking-at "[^|\n\r]* |"))
14108 (c org-table-may-need-update))
14109 (backward-delete-char N)
14110 (skip-chars-forward "^|")
14111 (insert " ")
14112 (goto-char (1- pos))
14113 ;; noalign: if there were two spaces at the end, this field
14114 ;; does not determine the width of the column.
14115 (if noalign (setq org-table-may-need-update c)))
14116 (backward-delete-char N)
14117 (org-fix-tags-on-the-fly)))
14119 (defun org-delete-char (N)
14120 "Like `delete-char', but insert whitespace at field end in tables.
14121 When deleting characters, in tables this function will insert whitespace in
14122 front of the next \"|\" separator, to keep the table aligned. The table will
14123 still be marked for re-alignment if the field did fill the entire column,
14124 because, in this case the deletion might narrow the column."
14125 (interactive "p")
14126 (if (and (org-table-p)
14127 (not (bolp))
14128 (not (= (char-after) ?|))
14129 (eq N 1))
14130 (if (looking-at ".*?|")
14131 (let ((pos (point))
14132 (noalign (looking-at "[^|\n\r]* |"))
14133 (c org-table-may-need-update))
14134 (replace-match (concat
14135 (substring (match-string 0) 1 -1)
14136 " |"))
14137 (goto-char pos)
14138 ;; noalign: if there were two spaces at the end, this field
14139 ;; does not determine the width of the column.
14140 (if noalign (setq org-table-may-need-update c)))
14141 (delete-char N))
14142 (delete-char N)
14143 (org-fix-tags-on-the-fly)))
14145 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14146 (put 'org-self-insert-command 'delete-selection t)
14147 (put 'orgtbl-self-insert-command 'delete-selection t)
14148 (put 'org-delete-char 'delete-selection 'supersede)
14149 (put 'org-delete-backward-char 'delete-selection 'supersede)
14150 (put 'org-yank 'delete-selection 'yank)
14152 ;; Make `flyspell-mode' delay after some commands
14153 (put 'org-self-insert-command 'flyspell-delayed t)
14154 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14155 (put 'org-delete-char 'flyspell-delayed t)
14156 (put 'org-delete-backward-char 'flyspell-delayed t)
14158 ;; Make pabbrev-mode expand after org-mode commands
14159 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14160 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14162 ;; How to do this: Measure non-white length of current string
14163 ;; If equal to column width, we should realign.
14165 (defun org-remap (map &rest commands)
14166 "In MAP, remap the functions given in COMMANDS.
14167 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14168 (let (new old)
14169 (while commands
14170 (setq old (pop commands) new (pop commands))
14171 (if (fboundp 'command-remapping)
14172 (org-defkey map (vector 'remap old) new)
14173 (substitute-key-definition old new map global-map)))))
14175 (when (eq org-enable-table-editor 'optimized)
14176 ;; If the user wants maximum table support, we need to hijack
14177 ;; some standard editing functions
14178 (org-remap org-mode-map
14179 'self-insert-command 'org-self-insert-command
14180 'delete-char 'org-delete-char
14181 'delete-backward-char 'org-delete-backward-char)
14182 (org-defkey org-mode-map "|" 'org-force-self-insert))
14184 (defvar org-ctrl-c-ctrl-c-hook nil
14185 "Hook for functions attaching themselves to `C-c C-c'.
14186 This can be used to add additional functionality to the C-c C-c key which
14187 executes context-dependent commands.
14188 Each function will be called with no arguments. The function must check
14189 if the context is appropriate for it to act. If yes, it should do its
14190 thing and then return a non-nil value. If the context is wrong,
14191 just do nothing and return nil.")
14193 (defvar org-tab-first-hook nil
14194 "Hook for functions to attach themselves to TAB.
14195 See `org-ctrl-c-ctrl-c-hook' for more information.
14196 This hook runs as the first action when TAB is pressed, even before
14197 `org-cycle' messes around with the `outline-regexp' to cater for
14198 inline tasks and plain list item folding.
14199 If any function in this hook returns t, not other actions like table
14200 field motion visibility cycling will be done.")
14202 (defvar org-tab-after-check-for-table-hook nil
14203 "Hook for functions to attach themselves to TAB.
14204 See `org-ctrl-c-ctrl-c-hook' for more information.
14205 This hook runs after it has been established that the cursor is not in a
14206 table, but before checking if the cursor is in a headline or if global cycling
14207 should be done.
14208 If any function in this hook returns t, not other actions like visibility
14209 cycling will be done.")
14211 (defvar org-tab-after-check-for-cycling-hook nil
14212 "Hook for functions to attach themselves to TAB.
14213 See `org-ctrl-c-ctrl-c-hook' for more information.
14214 This hook runs after it has been established that not table field motion and
14215 not visibility should be done because of current context. This is probably
14216 the place where a package like yasnippets can hook in.")
14218 (defvar org-metaleft-hook nil
14219 "Hook for functions attaching themselves to `M-left'.
14220 See `org-ctrl-c-ctrl-c-hook' for more information.")
14221 (defvar org-metaright-hook nil
14222 "Hook for functions attaching themselves to `M-right'.
14223 See `org-ctrl-c-ctrl-c-hook' for more information.")
14224 (defvar org-metaup-hook nil
14225 "Hook for functions attaching themselves to `M-up'.
14226 See `org-ctrl-c-ctrl-c-hook' for more information.")
14227 (defvar org-metadown-hook nil
14228 "Hook for functions attaching themselves to `M-down'.
14229 See `org-ctrl-c-ctrl-c-hook' for more information.")
14230 (defvar org-shiftmetaleft-hook nil
14231 "Hook for functions attaching themselves to `M-S-left'.
14232 See `org-ctrl-c-ctrl-c-hook' for more information.")
14233 (defvar org-shiftmetaright-hook nil
14234 "Hook for functions attaching themselves to `M-S-right'.
14235 See `org-ctrl-c-ctrl-c-hook' for more information.")
14236 (defvar org-shiftmetaup-hook nil
14237 "Hook for functions attaching themselves to `M-S-up'.
14238 See `org-ctrl-c-ctrl-c-hook' for more information.")
14239 (defvar org-shiftmetadown-hook nil
14240 "Hook for functions attaching themselves to `M-S-down'.
14241 See `org-ctrl-c-ctrl-c-hook' for more information.")
14242 (defvar org-metareturn-hook nil
14243 "Hook for functions attaching themselves to `M-RET'.
14244 See `org-ctrl-c-ctrl-c-hook' for more information.")
14246 (defun org-modifier-cursor-error ()
14247 "Throw an error, a modified cursor command was applied in wrong context."
14248 (error "This command is active in special context like tables, headlines or items"))
14250 (defun org-shiftselect-error ()
14251 "Throw an error because Shift-Cursor command was applied in wrong context."
14252 (if (and (boundp 'shift-select-mode) shift-select-mode)
14253 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14254 (error "This command works only in special context like headlines or timestamps.")))
14256 (defun org-call-for-shift-select (cmd)
14257 (let ((this-command-keys-shift-translated t))
14258 (call-interactively cmd)))
14260 (defun org-shifttab (&optional arg)
14261 "Global visibility cycling or move to previous table field.
14262 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14263 on context.
14264 See the individual commands for more information."
14265 (interactive "P")
14266 (cond
14267 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14268 ((integerp arg)
14269 (message "Content view to level: %d" arg)
14270 (org-content (prefix-numeric-value arg))
14271 (setq org-cycle-global-status 'overview))
14272 (t (call-interactively 'org-global-cycle))))
14274 (defun org-shiftmetaleft ()
14275 "Promote subtree or delete table column.
14276 Calls `org-promote-subtree', `org-outdent-item',
14277 or `org-table-delete-column', depending on context.
14278 See the individual commands for more information."
14279 (interactive)
14280 (cond
14281 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14282 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14283 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14284 ((org-at-item-p) (call-interactively 'org-outdent-item))
14285 (t (org-modifier-cursor-error))))
14287 (defun org-shiftmetaright ()
14288 "Demote subtree or insert table column.
14289 Calls `org-demote-subtree', `org-indent-item',
14290 or `org-table-insert-column', depending on context.
14291 See the individual commands for more information."
14292 (interactive)
14293 (cond
14294 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14295 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14296 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14297 ((org-at-item-p) (call-interactively 'org-indent-item))
14298 (t (org-modifier-cursor-error))))
14300 (defun org-shiftmetaup (&optional arg)
14301 "Move subtree up or kill table row.
14302 Calls `org-move-subtree-up' or `org-table-kill-row' or
14303 `org-move-item-up' depending on context. See the individual commands
14304 for more information."
14305 (interactive "P")
14306 (cond
14307 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14308 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14309 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14310 ((org-at-item-p) (call-interactively 'org-move-item-up))
14311 (t (org-modifier-cursor-error))))
14313 (defun org-shiftmetadown (&optional arg)
14314 "Move subtree down or insert table row.
14315 Calls `org-move-subtree-down' or `org-table-insert-row' or
14316 `org-move-item-down', depending on context. See the individual
14317 commands for more information."
14318 (interactive "P")
14319 (cond
14320 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14321 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14322 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14323 ((org-at-item-p) (call-interactively 'org-move-item-down))
14324 (t (org-modifier-cursor-error))))
14326 (defun org-metaleft (&optional arg)
14327 "Promote heading or move table column to left.
14328 Calls `org-do-promote' or `org-table-move-column', depending on context.
14329 With no specific context, calls the Emacs default `backward-word'.
14330 See the individual commands for more information."
14331 (interactive "P")
14332 (cond
14333 ((run-hook-with-args-until-success 'org-metaleft-hook))
14334 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14335 ((or (org-on-heading-p)
14336 (and (org-region-active-p)
14337 (save-excursion
14338 (goto-char (region-beginning))
14339 (org-on-heading-p))))
14340 (call-interactively 'org-do-promote))
14341 ((or (org-at-item-p)
14342 (and (org-region-active-p)
14343 (save-excursion
14344 (goto-char (region-beginning))
14345 (org-at-item-p))))
14346 (call-interactively 'org-outdent-item))
14347 (t (call-interactively 'backward-word))))
14349 (defun org-metaright (&optional arg)
14350 "Demote subtree or move table column to right.
14351 Calls `org-do-demote' or `org-table-move-column', depending on context.
14352 With no specific context, calls the Emacs default `forward-word'.
14353 See the individual commands for more information."
14354 (interactive "P")
14355 (cond
14356 ((run-hook-with-args-until-success 'org-metaright-hook))
14357 ((org-at-table-p) (call-interactively 'org-table-move-column))
14358 ((or (org-on-heading-p)
14359 (and (org-region-active-p)
14360 (save-excursion
14361 (goto-char (region-beginning))
14362 (org-on-heading-p))))
14363 (call-interactively 'org-do-demote))
14364 ((or (org-at-item-p)
14365 (and (org-region-active-p)
14366 (save-excursion
14367 (goto-char (region-beginning))
14368 (org-at-item-p))))
14369 (call-interactively 'org-indent-item))
14370 (t (call-interactively 'forward-word))))
14372 (defun org-metaup (&optional arg)
14373 "Move subtree up or move table row up.
14374 Calls `org-move-subtree-up' or `org-table-move-row' or
14375 `org-move-item-up', depending on context. See the individual commands
14376 for more information."
14377 (interactive "P")
14378 (cond
14379 ((run-hook-with-args-until-success 'org-metaup-hook))
14380 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14381 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14382 ((org-at-item-p) (call-interactively 'org-move-item-up))
14383 (t (transpose-lines 1) (beginning-of-line -1))))
14385 (defun org-metadown (&optional arg)
14386 "Move subtree down or move table row down.
14387 Calls `org-move-subtree-down' or `org-table-move-row' or
14388 `org-move-item-down', depending on context. See the individual
14389 commands for more information."
14390 (interactive "P")
14391 (cond
14392 ((run-hook-with-args-until-success 'org-metadown-hook))
14393 ((org-at-table-p) (call-interactively 'org-table-move-row))
14394 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14395 ((org-at-item-p) (call-interactively 'org-move-item-down))
14396 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14398 (defun org-shiftup (&optional arg)
14399 "Increase item in timestamp or increase priority of current headline.
14400 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14401 depending on context. See the individual commands for more information."
14402 (interactive "P")
14403 (cond
14404 ((and org-support-shift-select (org-region-active-p))
14405 (org-call-for-shift-select 'previous-line))
14406 ((org-at-timestamp-p t)
14407 (call-interactively (if org-edit-timestamp-down-means-later
14408 'org-timestamp-down 'org-timestamp-up)))
14409 ((and (not (eq org-support-shift-select 'always))
14410 org-enable-priority-commands
14411 (org-on-heading-p))
14412 (call-interactively 'org-priority-up))
14413 ((and (not org-support-shift-select) (org-at-item-p))
14414 (call-interactively 'org-previous-item))
14415 ((org-clocktable-try-shift 'up arg))
14416 (org-support-shift-select
14417 (org-call-for-shift-select 'previous-line))
14418 (t (org-shiftselect-error))))
14420 (defun org-shiftdown (&optional arg)
14421 "Decrease item in timestamp or decrease priority of current headline.
14422 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14423 depending on context. See the individual commands for more information."
14424 (interactive "P")
14425 (cond
14426 ((and org-support-shift-select (org-region-active-p))
14427 (org-call-for-shift-select 'next-line))
14428 ((org-at-timestamp-p t)
14429 (call-interactively (if org-edit-timestamp-down-means-later
14430 'org-timestamp-up 'org-timestamp-down)))
14431 ((and (not (eq org-support-shift-select 'always))
14432 org-enable-priority-commands
14433 (org-on-heading-p))
14434 (call-interactively 'org-priority-down))
14435 ((and (not org-support-shift-select) (org-at-item-p))
14436 (call-interactively 'org-next-item))
14437 ((org-clocktable-try-shift 'down arg))
14438 (org-support-shift-select
14439 (org-call-for-shift-select 'next-line))
14440 (t (org-shiftselect-error))))
14442 (defun org-shiftright (&optional arg)
14443 "Cycle the thing at point or in the current line, depending on context.
14444 Depending on context, this does one of the following:
14446 - switch a timestamp at point one day into the future
14447 - on a headline, switch to the next TODO keyword.
14448 - on an item, switch entire list to the next bullet type
14449 - on a property line, switch to the next allowed value
14450 - on a clocktable definition line, move time block into the future"
14451 (interactive "P")
14452 (cond
14453 ((and org-support-shift-select (org-region-active-p))
14454 (org-call-for-shift-select 'forward-char))
14455 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14456 ((and (not (eq org-support-shift-select 'always))
14457 (org-on-heading-p))
14458 (let ((org-inhibit-logging
14459 (not org-treat-S-cursor-todo-selection-as-state-change))
14460 (org-inhibit-blocking
14461 (not org-treat-S-cursor-todo-selection-as-state-change)))
14462 (org-call-with-arg 'org-todo 'right)))
14463 ((or (and org-support-shift-select
14464 (not (eq org-support-shift-select 'always))
14465 (org-at-item-bullet-p))
14466 (and (not org-support-shift-select) (org-at-item-p)))
14467 (org-call-with-arg 'org-cycle-list-bullet nil))
14468 ((and (not (eq org-support-shift-select 'always))
14469 (org-at-property-p))
14470 (call-interactively 'org-property-next-allowed-value))
14471 ((org-clocktable-try-shift 'right arg))
14472 (org-support-shift-select
14473 (org-call-for-shift-select 'forward-char))
14474 (t (org-shiftselect-error))))
14476 (defun org-shiftleft (&optional arg)
14477 "Cycle the thing at point or in the current line, depending on context.
14478 Depending on context, this does one of the following:
14480 - switch a timestamp at point one day into the past
14481 - on a headline, switch to the previous TODO keyword.
14482 - on an item, switch entire list to the previous bullet type
14483 - on a property line, switch to the previous allowed value
14484 - on a clocktable definition line, move time block into the past"
14485 (interactive "P")
14486 (cond
14487 ((and org-support-shift-select (org-region-active-p))
14488 (org-call-for-shift-select 'backward-char))
14489 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14490 ((and (not (eq org-support-shift-select 'always))
14491 (org-on-heading-p))
14492 (let ((org-inhibit-logging
14493 (not org-treat-S-cursor-todo-selection-as-state-change))
14494 (org-inhibit-blocking
14495 (not org-treat-S-cursor-todo-selection-as-state-change)))
14496 (org-call-with-arg 'org-todo 'left)))
14497 ((or (and org-support-shift-select
14498 (not (eq org-support-shift-select 'always))
14499 (org-at-item-bullet-p))
14500 (and (not org-support-shift-select) (org-at-item-p)))
14501 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14502 ((and (not (eq org-support-shift-select 'always))
14503 (org-at-property-p))
14504 (call-interactively 'org-property-previous-allowed-value))
14505 ((org-clocktable-try-shift 'left arg))
14506 (org-support-shift-select
14507 (org-call-for-shift-select 'backward-char))
14508 (t (org-shiftselect-error))))
14510 (defun org-shiftcontrolright ()
14511 "Switch to next TODO set."
14512 (interactive)
14513 (cond
14514 ((and org-support-shift-select (org-region-active-p))
14515 (org-call-for-shift-select 'forward-word))
14516 ((and (not (eq org-support-shift-select 'always))
14517 (org-on-heading-p))
14518 (org-call-with-arg 'org-todo 'nextset))
14519 (org-support-shift-select
14520 (org-call-for-shift-select 'forward-word))
14521 (t (org-shiftselect-error))))
14523 (defun org-shiftcontrolleft ()
14524 "Switch to previous TODO set."
14525 (interactive)
14526 (cond
14527 ((and org-support-shift-select (org-region-active-p))
14528 (org-call-for-shift-select 'backward-word))
14529 ((and (not (eq org-support-shift-select 'always))
14530 (org-on-heading-p))
14531 (org-call-with-arg 'org-todo 'previousset))
14532 (org-support-shift-select
14533 (org-call-for-shift-select 'backward-word))
14534 (t (org-shiftselect-error))))
14536 (defun org-ctrl-c-ret ()
14537 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14538 (interactive)
14539 (cond
14540 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14541 (t (call-interactively 'org-insert-heading))))
14543 (defun org-copy-special ()
14544 "Copy region in table or copy current subtree.
14545 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14546 See the individual commands for more information."
14547 (interactive)
14548 (call-interactively
14549 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14551 (defun org-cut-special ()
14552 "Cut region in table or cut current subtree.
14553 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14554 See the individual commands for more information."
14555 (interactive)
14556 (call-interactively
14557 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14559 (defun org-paste-special (arg)
14560 "Paste rectangular region into table, or past subtree relative to level.
14561 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14562 See the individual commands for more information."
14563 (interactive "P")
14564 (if (org-at-table-p)
14565 (org-table-paste-rectangle)
14566 (org-paste-subtree arg)))
14568 (defun org-edit-special ()
14569 "Call a special editor for the stuff at point.
14570 When at a table, call the formula editor with `org-table-edit-formulas'.
14571 When at the first line of an src example, call `org-edit-src-code'.
14572 When in an #+include line, visit the include file. Otherwise call
14573 `ffap' to visit the file at point."
14574 (interactive)
14575 (cond
14576 ((org-at-table-p)
14577 (call-interactively 'org-table-edit-formulas))
14578 ((save-excursion
14579 (beginning-of-line 1)
14580 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14581 (find-file (org-trim (match-string 1))))
14582 ((org-edit-src-code))
14583 ((org-edit-fixed-width-region))
14584 (t (call-interactively 'ffap))))
14587 (defun org-ctrl-c-ctrl-c (&optional arg)
14588 "Set tags in headline, or update according to changed information at point.
14590 This command does many different things, depending on context:
14592 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14593 this is what we do.
14595 - If the cursor is in a headline, prompt for tags and insert them
14596 into the current line, aligned to `org-tags-column'. When called
14597 with prefix arg, realign all tags in the current buffer.
14599 - If the cursor is in one of the special #+KEYWORD lines, this
14600 triggers scanning the buffer for these lines and updating the
14601 information.
14603 - If the cursor is inside a table, realign the table. This command
14604 works even if the automatic table editor has been turned off.
14606 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14607 the entire table.
14609 - If the cursor is at a footnote reference or definition, jump to
14610 the corresponding definition or references, respectively.
14612 - If the cursor is a the beginning of a dynamic block, update it.
14614 - If the cursor is inside a table created by the table.el package,
14615 activate that table.
14617 - If the current buffer is a remember buffer, close note and file
14618 it. A prefix argument of 1 files to the default location
14619 without further interaction. A prefix argument of 2 files to
14620 the currently clocking task.
14622 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14623 links in this buffer.
14625 - If the cursor is on a numbered item in a plain list, renumber the
14626 ordered list.
14628 - If the cursor is on a checkbox, toggle it."
14629 (interactive "P")
14630 (let ((org-enable-table-editor t))
14631 (cond
14632 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14633 org-occur-highlights
14634 org-latex-fragment-image-overlays)
14635 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14636 (org-remove-occur-highlights)
14637 (org-remove-latex-fragment-image-overlays)
14638 (message "Temporary highlights/overlays removed from current buffer"))
14639 ((and (local-variable-p 'org-finish-function (current-buffer))
14640 (fboundp org-finish-function))
14641 (funcall org-finish-function))
14642 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14643 ((org-at-property-p)
14644 (call-interactively 'org-property-action))
14645 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14646 ((org-on-heading-p) (call-interactively 'org-set-tags))
14647 ((org-at-table.el-p)
14648 (require 'table)
14649 (beginning-of-line 1)
14650 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14651 (call-interactively 'table-recognize-table))
14652 ((org-at-table-p)
14653 (org-table-maybe-eval-formula)
14654 (if arg
14655 (call-interactively 'org-table-recalculate)
14656 (org-table-maybe-recalculate-line))
14657 (call-interactively 'org-table-align))
14658 ((or (org-footnote-at-reference-p)
14659 (org-footnote-at-definition-p))
14660 (call-interactively 'org-footnote-action))
14661 ((org-at-item-checkbox-p)
14662 (call-interactively 'org-toggle-checkbox))
14663 ((org-at-item-p)
14664 (if arg
14665 (call-interactively 'org-toggle-checkbox)
14666 (call-interactively 'org-maybe-renumber-ordered-list)))
14667 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14668 ;; Dynamic block
14669 (beginning-of-line 1)
14670 (save-excursion (org-update-dblock)))
14671 ((save-excursion
14672 (beginning-of-line 1)
14673 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
14674 (cond
14675 ((equal (match-string 1) "TBLFM")
14676 ;; Recalculate the table before this line
14677 (save-excursion
14678 (beginning-of-line 1)
14679 (skip-chars-backward " \r\n\t")
14680 (if (org-at-table-p)
14681 (org-call-with-arg 'org-table-recalculate t))))
14683 ; (org-set-regexps-and-options)
14684 ; (org-restart-font-lock)
14685 (let ((org-inhibit-startup t)) (org-mode-restart))
14686 (message "Local setup has been refreshed"))))
14687 ((org-clock-update-time-maybe))
14688 (t (error "C-c C-c can do nothing useful at this location.")))))
14690 (defun org-mode-restart ()
14691 "Restart Org-mode, to scan again for special lines.
14692 Also updates the keyword regular expressions."
14693 (interactive)
14694 (org-mode)
14695 (message "Org-mode restarted"))
14697 (defun org-kill-note-or-show-branches ()
14698 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14699 (interactive)
14700 (if (not org-finish-function)
14701 (call-interactively 'show-branches)
14702 (let ((org-note-abort t))
14703 (funcall org-finish-function))))
14705 (defun org-return (&optional indent)
14706 "Goto next table row or insert a newline.
14707 Calls `org-table-next-row' or `newline', depending on context.
14708 See the individual commands for more information."
14709 (interactive)
14710 (cond
14711 ((bobp) (if indent (newline-and-indent) (newline)))
14712 ((org-at-table-p)
14713 (org-table-justify-field-maybe)
14714 (call-interactively 'org-table-next-row))
14715 ((and org-return-follows-link
14716 (eq (get-text-property (point) 'face) 'org-link))
14717 (call-interactively 'org-open-at-point))
14718 ((and (org-at-heading-p)
14719 (looking-at
14720 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14721 (org-show-entry)
14722 (end-of-line 1)
14723 (newline))
14724 (t (if indent (newline-and-indent) (newline)))))
14726 (defun org-return-indent ()
14727 "Goto next table row or insert a newline and indent.
14728 Calls `org-table-next-row' or `newline-and-indent', depending on
14729 context. See the individual commands for more information."
14730 (interactive)
14731 (org-return t))
14733 (defun org-ctrl-c-star ()
14734 "Compute table, or change heading status of lines.
14735 Calls `org-table-recalculate' or `org-toggle-heading',
14736 depending on context."
14737 (interactive)
14738 (cond
14739 ((org-at-table-p)
14740 (call-interactively 'org-table-recalculate))
14742 ;; Convert all lines in region to list items
14743 (call-interactively 'org-toggle-heading))))
14745 (defun org-ctrl-c-minus ()
14746 "Insert separator line in table or modify bullet status of line.
14747 Also turns a plain line or a region of lines into list items.
14748 Calls `org-table-insert-hline', `org-toggle-item', or
14749 `org-cycle-list-bullet', depending on context."
14750 (interactive)
14751 (cond
14752 ((org-at-table-p)
14753 (call-interactively 'org-table-insert-hline))
14754 ((org-region-active-p)
14755 (call-interactively 'org-toggle-item))
14756 ((org-in-item-p)
14757 (call-interactively 'org-cycle-list-bullet))
14759 (call-interactively 'org-toggle-item))))
14761 (defun org-toggle-item ()
14762 "Convert headings or normal lines to items, items to normal lines.
14763 If there is no active region, only the current line is considered.
14765 If the first line in the region is a headline, convert all headlines to items.
14767 If the first line in the region is an item, convert all items to normal lines.
14769 If the first line is normal text, add an item bullet to each line."
14770 (interactive)
14771 (let (l2 l beg end)
14772 (if (org-region-active-p)
14773 (setq beg (region-beginning) end (region-end))
14774 (setq beg (point-at-bol)
14775 end (min (1+ (point-at-eol)) (point-max))))
14776 (save-excursion
14777 (goto-char end)
14778 (setq l2 (org-current-line))
14779 (goto-char beg)
14780 (beginning-of-line 1)
14781 (setq l (1- (org-current-line)))
14782 (if (org-at-item-p)
14783 ;; We already have items, de-itemize
14784 (while (< (setq l (1+ l)) l2)
14785 (when (org-at-item-p)
14786 (goto-char (match-beginning 2))
14787 (delete-region (match-beginning 2) (match-end 2))
14788 (and (looking-at "[ \t]+") (replace-match "")))
14789 (beginning-of-line 2))
14790 (if (org-on-heading-p)
14791 ;; Headings, convert to items
14792 (while (< (setq l (1+ l)) l2)
14793 (if (looking-at org-outline-regexp)
14794 (replace-match "- " t t))
14795 (beginning-of-line 2))
14796 ;; normal lines, turn them into items
14797 (while (< (setq l (1+ l)) l2)
14798 (unless (org-at-item-p)
14799 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14800 (replace-match "\\1- \\2")))
14801 (beginning-of-line 2)))))))
14803 (defun org-toggle-heading (&optional nstars)
14804 "Convert headings to normal text, or items or text to headings.
14805 If there is no active region, only the current line is considered.
14807 If the first line is a heading, remove the stars from all headlines
14808 in the region.
14810 If the first line is a plain list item, turn all plain list items into
14811 headings.
14813 If the first line is a normal line, turn each and every line in the region
14814 into a heading.
14816 When converting a line into a heading, the number of stars is chosen
14817 such that the lines become children of the current entry. However, when
14818 a prefix argument is given, its value determines the number of stars to add."
14819 (interactive "P")
14820 (let (l2 l itemp beg end)
14821 (if (org-region-active-p)
14822 (setq beg (region-beginning) end (region-end))
14823 (setq beg (point-at-bol)
14824 end (min (1+ (point-at-eol)) (point-max))))
14825 (save-excursion
14826 (goto-char end)
14827 (setq l2 (org-current-line))
14828 (goto-char beg)
14829 (beginning-of-line 1)
14830 (setq l (1- (org-current-line)))
14831 (if (org-on-heading-p)
14832 ;; We already have headlines, de-star them
14833 (while (< (setq l (1+ l)) l2)
14834 (when (org-on-heading-p t)
14835 (and (looking-at outline-regexp) (replace-match "")))
14836 (beginning-of-line 2))
14837 (setq itemp (org-at-item-p))
14838 (let* ((stars
14839 (if nstars
14840 (make-string (prefix-numeric-value current-prefix-arg)
14842 (save-excursion
14843 (re-search-backward org-complex-heading-regexp nil t)
14844 (or (match-string 1) ""))))
14845 (add-stars (cond (nstars "")
14846 ((equal stars "") "*")
14847 (org-odd-levels-only "**")
14848 (t "*")))
14849 (rpl (concat stars add-stars " ")))
14850 (while (< (setq l (1+ l)) l2)
14851 (if itemp
14852 (and (org-at-item-p) (replace-match rpl t t))
14853 (unless (org-on-heading-p)
14854 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14855 (replace-match (concat rpl (match-string 2))))))
14856 (beginning-of-line 2)))))))
14858 (defun org-meta-return (&optional arg)
14859 "Insert a new heading or wrap a region in a table.
14860 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14861 See the individual commands for more information."
14862 (interactive "P")
14863 (cond
14864 ((run-hook-with-args-until-success 'org-metareturn-hook))
14865 ((org-at-table-p)
14866 (call-interactively 'org-table-wrap-region))
14867 (t (call-interactively 'org-insert-heading))))
14869 ;;; Menu entries
14871 ;; Define the Org-mode menus
14872 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14873 '("Tbl"
14874 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14875 ["Next Field" org-cycle (org-at-table-p)]
14876 ["Previous Field" org-shifttab (org-at-table-p)]
14877 ["Next Row" org-return (org-at-table-p)]
14878 "--"
14879 ["Blank Field" org-table-blank-field (org-at-table-p)]
14880 ["Edit Field" org-table-edit-field (org-at-table-p)]
14881 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14882 "--"
14883 ("Column"
14884 ["Move Column Left" org-metaleft (org-at-table-p)]
14885 ["Move Column Right" org-metaright (org-at-table-p)]
14886 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14887 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14888 ("Row"
14889 ["Move Row Up" org-metaup (org-at-table-p)]
14890 ["Move Row Down" org-metadown (org-at-table-p)]
14891 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14892 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14893 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14894 "--"
14895 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14896 ("Rectangle"
14897 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14898 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14899 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14900 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14901 "--"
14902 ("Calculate"
14903 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14904 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14905 ["Edit Formulas" org-edit-special (org-at-table-p)]
14906 "--"
14907 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14908 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14909 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14910 "--"
14911 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14912 "--"
14913 ["Sum Column/Rectangle" org-table-sum
14914 (or (org-at-table-p) (org-region-active-p))]
14915 ["Which Column?" org-table-current-column (org-at-table-p)])
14916 ["Debug Formulas"
14917 org-table-toggle-formula-debugger
14918 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14919 ["Show Col/Row Numbers"
14920 org-table-toggle-coordinate-overlays
14921 :style toggle
14922 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14923 "--"
14924 ["Create" org-table-create (and (not (org-at-table-p))
14925 org-enable-table-editor)]
14926 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14927 ["Import from File" org-table-import (not (org-at-table-p))]
14928 ["Export to File" org-table-export (org-at-table-p)]
14929 "--"
14930 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14932 (easy-menu-define org-org-menu org-mode-map "Org menu"
14933 '("Org"
14934 ("Show/Hide"
14935 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14936 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14937 ["Sparse Tree..." org-sparse-tree t]
14938 ["Reveal Context" org-reveal t]
14939 ["Show All" show-all t]
14940 "--"
14941 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14942 "--"
14943 ["New Heading" org-insert-heading t]
14944 ("Navigate Headings"
14945 ["Up" outline-up-heading t]
14946 ["Next" outline-next-visible-heading t]
14947 ["Previous" outline-previous-visible-heading t]
14948 ["Next Same Level" outline-forward-same-level t]
14949 ["Previous Same Level" outline-backward-same-level t]
14950 "--"
14951 ["Jump" org-goto t])
14952 ("Edit Structure"
14953 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14954 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14955 "--"
14956 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14957 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14958 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14959 "--"
14960 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14961 "--"
14962 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14963 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14964 ["Demote Heading" org-metaright (not (org-at-table-p))]
14965 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14966 "--"
14967 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14968 "--"
14969 ["Convert to odd levels" org-convert-to-odd-levels t]
14970 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14971 ("Editing"
14972 ["Emphasis..." org-emphasize t]
14973 ["Edit Source Example" org-edit-special t]
14974 "--"
14975 ["Footnote new/jump" org-footnote-action t]
14976 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14977 ("Archive"
14978 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14979 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14980 ; :active t :keys "C-u C-c C-x C-a"]
14981 ["Sparse trees open ARCHIVE trees"
14982 (setq org-sparse-tree-open-archived-trees
14983 (not org-sparse-tree-open-archived-trees))
14984 :style toggle :selected org-sparse-tree-open-archived-trees]
14985 ["Cycling opens ARCHIVE trees"
14986 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14987 :style toggle :selected org-cycle-open-archived-trees]
14988 "--"
14989 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14990 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14991 ; ["Check and Move Children" (org-archive-subtree '(4))
14992 ; :active t :keys "C-u C-c C-x C-s"]
14994 "--"
14995 ("Hyperlinks"
14996 ["Store Link (Global)" org-store-link t]
14997 ["Insert Link" org-insert-link t]
14998 ["Follow Link" org-open-at-point t]
14999 "--"
15000 ["Next link" org-next-link t]
15001 ["Previous link" org-previous-link t]
15002 "--"
15003 ["Descriptive Links"
15004 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15005 :style radio
15006 :selected (member '(org-link) buffer-invisibility-spec)]
15007 ["Literal Links"
15008 (progn
15009 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15010 :style radio
15011 :selected (not (member '(org-link) buffer-invisibility-spec))])
15012 "--"
15013 ("TODO Lists"
15014 ["TODO/DONE/-" org-todo t]
15015 ("Select keyword"
15016 ["Next keyword" org-shiftright (org-on-heading-p)]
15017 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15018 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15019 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15020 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15021 ["Show TODO Tree" org-show-todo-tree t]
15022 ["Global TODO list" org-todo-list t]
15023 "--"
15024 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15025 :selected org-enforce-todo-dependencies :style toggle :active t]
15026 "Settings for tree at point"
15027 ["Do Children sequentially" org-toggle-ordered-property :style radio
15028 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15029 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15030 ["Do Children parallel" org-toggle-ordered-property :style radio
15031 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15032 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15033 "--"
15034 ["Set Priority" org-priority t]
15035 ["Priority Up" org-shiftup t]
15036 ["Priority Down" org-shiftdown t]
15037 "--"
15038 ["Get news from all feeds" org-feed-update-all t]
15039 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15040 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15041 ("TAGS and Properties"
15042 ["Set Tags" org-set-tags-command t]
15043 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15044 "--"
15045 ["Set property" org-set-property t]
15046 ["Column view of properties" org-columns t]
15047 ["Insert Column View DBlock" org-insert-columns-dblock t])
15048 ("Dates and Scheduling"
15049 ["Timestamp" org-time-stamp t]
15050 ["Timestamp (inactive)" org-time-stamp-inactive t]
15051 ("Change Date"
15052 ["1 Day Later" org-shiftright t]
15053 ["1 Day Earlier" org-shiftleft t]
15054 ["1 ... Later" org-shiftup t]
15055 ["1 ... Earlier" org-shiftdown t])
15056 ["Compute Time Range" org-evaluate-time-range t]
15057 ["Schedule Item" org-schedule t]
15058 ["Deadline" org-deadline t]
15059 "--"
15060 ["Custom time format" org-toggle-time-stamp-overlays
15061 :style radio :selected org-display-custom-times]
15062 "--"
15063 ["Goto Calendar" org-goto-calendar t]
15064 ["Date from Calendar" org-date-from-calendar t]
15065 "--"
15066 ["Start/Restart Timer" org-timer-start t]
15067 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15068 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15069 ["Insert Timer String" org-timer t]
15070 ["Insert Timer Item" org-timer-item t])
15071 ("Logging work"
15072 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15073 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15074 ["Clock out" org-clock-out t]
15075 ["Clock cancel" org-clock-cancel t]
15076 "--"
15077 ["Mark as default task" org-clock-mark-default-task t]
15078 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15079 ["Goto running clock" org-clock-goto t]
15080 "--"
15081 ["Display times" org-clock-display t]
15082 ["Create clock table" org-clock-report t]
15083 "--"
15084 ["Record DONE time"
15085 (progn (setq org-log-done (not org-log-done))
15086 (message "Switching to %s will %s record a timestamp"
15087 (car org-done-keywords)
15088 (if org-log-done "automatically" "not")))
15089 :style toggle :selected org-log-done])
15090 "--"
15091 ["Agenda Command..." org-agenda t]
15092 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15093 ("File List for Agenda")
15094 ("Special views current file"
15095 ["TODO Tree" org-show-todo-tree t]
15096 ["Check Deadlines" org-check-deadlines t]
15097 ["Timeline" org-timeline t]
15098 ["Tags/Property tree" org-match-sparse-tree t])
15099 "--"
15100 ["Export/Publish..." org-export t]
15101 ("LaTeX"
15102 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15103 :selected org-cdlatex-mode]
15104 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15105 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15106 ["Modify math symbol" org-cdlatex-math-modify
15107 (org-inside-LaTeX-fragment-p)]
15108 ["Insert citation" org-reftex-citation t]
15109 "--"
15110 ["Export LaTeX fragments as images"
15111 (if (featurep 'org-exp)
15112 (setq org-export-with-LaTeX-fragments
15113 (not org-export-with-LaTeX-fragments))
15114 (require 'org-exp))
15115 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15116 org-export-with-LaTeX-fragments)])
15117 "--"
15118 ("Documentation"
15119 ["Show Version" org-version t]
15120 ["Info Documentation" org-info t])
15121 ("Customize"
15122 ["Browse Org Group" org-customize t]
15123 "--"
15124 ["Expand This Menu" org-create-customize-menu
15125 (fboundp 'customize-menu-create)])
15126 "--"
15127 ("Refresh/Reload"
15128 ["Refresh setup current buffer" org-mode-restart t]
15129 ["Reload Org (after update)" org-reload t]
15130 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15133 (defun org-info (&optional node)
15134 "Read documentation for Org-mode in the info system.
15135 With optional NODE, go directly to that node."
15136 (interactive)
15137 (info (format "(org)%s" (or node ""))))
15139 (defun org-install-agenda-files-menu ()
15140 (let ((bl (buffer-list)))
15141 (save-excursion
15142 (while bl
15143 (set-buffer (pop bl))
15144 (if (org-mode-p) (setq bl nil)))
15145 (when (org-mode-p)
15146 (easy-menu-change
15147 '("Org") "File List for Agenda"
15148 (append
15149 (list
15150 ["Edit File List" (org-edit-agenda-file-list) t]
15151 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15152 ["Remove Current File from List" org-remove-file t]
15153 ["Cycle through agenda files" org-cycle-agenda-files t]
15154 ["Occur in all agenda files" org-occur-in-agenda-files t]
15155 "--")
15156 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15158 ;;;; Documentation
15160 ;;;###autoload
15161 (defun org-require-autoloaded-modules ()
15162 (interactive)
15163 (mapc 'require
15164 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15165 org-docbook org-exp org-html org-icalendar
15166 org-id org-latex
15167 org-publish org-remember org-table
15168 org-timer org-xoxo)))
15170 ;;;###autoload
15171 (defun org-reload (&optional uncompiled)
15172 "Reload all org lisp files.
15173 With prefix arg UNCOMPILED, load the uncompiled versions."
15174 (interactive "P")
15175 (require 'find-func)
15176 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15177 (dir-org (file-name-directory (org-find-library-name "org")))
15178 (dir-org-contrib (ignore-errors
15179 (file-name-directory
15180 (org-find-library-name "org-contribdir"))))
15181 (files
15182 (append (directory-files dir-org t file-re)
15183 (and dir-org-contrib
15184 (directory-files dir-org-contrib t file-re))))
15185 (remove-re (concat (if (featurep 'xemacs)
15186 "org-colview" "org-colview-xemacs")
15187 "\\'")))
15188 (setq files (mapcar 'file-name-sans-extension files))
15189 (setq files (mapcar
15190 (lambda (x) (if (string-match remove-re x) nil x))
15191 files))
15192 (setq files (delq nil files))
15193 (mapc
15194 (lambda (f)
15195 (when (featurep (intern (file-name-nondirectory f)))
15196 (if (and (not uncompiled)
15197 (file-exists-p (concat f ".elc")))
15198 (load (concat f ".elc") nil nil t)
15199 (load (concat f ".el") nil nil t))))
15200 files))
15201 (org-version))
15203 ;;;###autoload
15204 (defun org-customize ()
15205 "Call the customize function with org as argument."
15206 (interactive)
15207 (org-load-modules-maybe)
15208 (org-require-autoloaded-modules)
15209 (customize-browse 'org))
15211 (defun org-create-customize-menu ()
15212 "Create a full customization menu for Org-mode, insert it into the menu."
15213 (interactive)
15214 (org-load-modules-maybe)
15215 (org-require-autoloaded-modules)
15216 (if (fboundp 'customize-menu-create)
15217 (progn
15218 (easy-menu-change
15219 '("Org") "Customize"
15220 `(["Browse Org group" org-customize t]
15221 "--"
15222 ,(customize-menu-create 'org)
15223 ["Set" Custom-set t]
15224 ["Save" Custom-save t]
15225 ["Reset to Current" Custom-reset-current t]
15226 ["Reset to Saved" Custom-reset-saved t]
15227 ["Reset to Standard Settings" Custom-reset-standard t]))
15228 (message "\"Org\"-menu now contains full customization menu"))
15229 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15231 ;;;; Miscellaneous stuff
15233 ;;; Generally useful functions
15235 (defun org-find-text-property-in-string (prop s)
15236 "Return the first non-nil value of property PROP in string S."
15237 (or (get-text-property 0 prop s)
15238 (get-text-property (or (next-single-property-change 0 prop s) 0)
15239 prop s)))
15241 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15242 "Display the given MESSAGE as a warning."
15243 (if (fboundp 'display-warning)
15244 (display-warning 'org message
15245 (if (featurep 'xemacs)
15246 'warning
15247 :warning))
15248 (let ((buf (get-buffer-create "*Org warnings*")))
15249 (with-current-buffer buf
15250 (goto-char (point-max))
15251 (insert "Warning (Org): " message)
15252 (unless (bolp)
15253 (newline)))
15254 (display-buffer buf)
15255 (sit-for 0))))
15257 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15258 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15259 (if (and marker (marker-buffer marker)
15260 (buffer-live-p (marker-buffer marker)))
15261 (progn
15262 (switch-to-buffer (marker-buffer marker))
15263 (if (or (> marker (point-max)) (< marker (point-min)))
15264 (widen))
15265 (goto-char marker)
15266 (org-show-context 'org-goto))
15267 (if bookmark
15268 (bookmark-jump bookmark)
15269 (error "Cannot find location"))))
15271 (defun org-quote-csv-field (s)
15272 "Quote field for inclusion in CSV material."
15273 (if (string-match "[\",]" s)
15274 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15277 (defun org-plist-delete (plist property)
15278 "Delete PROPERTY from PLIST.
15279 This is in contrast to merely setting it to 0."
15280 (let (p)
15281 (while plist
15282 (if (not (eq property (car plist)))
15283 (setq p (plist-put p (car plist) (nth 1 plist))))
15284 (setq plist (cddr plist)))
15287 (defun org-force-self-insert (N)
15288 "Needed to enforce self-insert under remapping."
15289 (interactive "p")
15290 (self-insert-command N))
15292 (defun org-string-width (s)
15293 "Compute width of string, ignoring invisible characters.
15294 This ignores character with invisibility property `org-link', and also
15295 characters with property `org-cwidth', because these will become invisible
15296 upon the next fontification round."
15297 (let (b l)
15298 (when (or (eq t buffer-invisibility-spec)
15299 (assq 'org-link buffer-invisibility-spec))
15300 (while (setq b (text-property-any 0 (length s)
15301 'invisible 'org-link s))
15302 (setq s (concat (substring s 0 b)
15303 (substring s (or (next-single-property-change
15304 b 'invisible s) (length s)))))))
15305 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15306 (setq s (concat (substring s 0 b)
15307 (substring s (or (next-single-property-change
15308 b 'org-cwidth s) (length s))))))
15309 (setq l (string-width s) b -1)
15310 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15311 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15314 (defun org-get-indentation (&optional line)
15315 "Get the indentation of the current line, interpreting tabs.
15316 When LINE is given, assume it represents a line and compute its indentation."
15317 (if line
15318 (if (string-match "^ *" (org-remove-tabs line))
15319 (match-end 0))
15320 (save-excursion
15321 (beginning-of-line 1)
15322 (skip-chars-forward " \t")
15323 (current-column))))
15325 (defun org-remove-tabs (s &optional width)
15326 "Replace tabulators in S with spaces.
15327 Assumes that s is a single line, starting in column 0."
15328 (setq width (or width tab-width))
15329 (while (string-match "\t" s)
15330 (setq s (replace-match
15331 (make-string
15332 (- (* width (/ (+ (match-beginning 0) width) width))
15333 (match-beginning 0)) ?\ )
15334 t t s)))
15337 (defun org-fix-indentation (line ind)
15338 "Fix indentation in LINE.
15339 IND is a cons cell with target and minimum indentation.
15340 If the current indentation in LINE is smaller than the minimum,
15341 leave it alone. If it is larger than ind, set it to the target."
15342 (let* ((l (org-remove-tabs line))
15343 (i (org-get-indentation l))
15344 (i1 (car ind)) (i2 (cdr ind)))
15345 (if (>= i i2) (setq l (substring line i2)))
15346 (if (> i1 0)
15347 (concat (make-string i1 ?\ ) l)
15348 l)))
15350 (defun org-remove-indentation (code &optional n)
15351 "Remove the maximum common indentation from the lines in CODE.
15352 N may optionally be the number of spaces to remove."
15353 (with-temp-buffer
15354 (insert code)
15355 (org-do-remove-indentation n)
15356 (buffer-string)))
15358 (defun org-do-remove-indentation (&optional n)
15359 "Remove the maximum common indentation from the buffer."
15360 (untabify (point-min) (point-max))
15361 (let ((min 10000) re)
15362 (if n
15363 (setq min n)
15364 (goto-char (point-min))
15365 (while (re-search-forward "^ *[^ \n]" nil t)
15366 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
15367 (unless (or (= min 0) (= min 10000))
15368 (setq re (format "^ \\{%d\\}" min))
15369 (goto-char (point-min))
15370 (while (re-search-forward re nil t)
15371 (replace-match "")
15372 (end-of-line 1))
15373 min)))
15375 (defun org-base-buffer (buffer)
15376 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15377 (if (not buffer)
15378 buffer
15379 (or (buffer-base-buffer buffer)
15380 buffer)))
15382 (defun org-trim (s)
15383 "Remove whitespace at beginning and end of string."
15384 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15385 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15388 (defun org-wrap (string &optional width lines)
15389 "Wrap string to either a number of lines, or a width in characters.
15390 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15391 that costs. If there is a word longer than WIDTH, the text is actually
15392 wrapped to the length of that word.
15393 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15394 many lines, whatever width that takes.
15395 The return value is a list of lines, without newlines at the end."
15396 (let* ((words (org-split-string string "[ \t\n]+"))
15397 (maxword (apply 'max (mapcar 'org-string-width words)))
15398 w ll)
15399 (cond (width
15400 (org-do-wrap words (max maxword width)))
15401 (lines
15402 (setq w maxword)
15403 (setq ll (org-do-wrap words maxword))
15404 (if (<= (length ll) lines)
15406 (setq ll words)
15407 (while (> (length ll) lines)
15408 (setq w (1+ w))
15409 (setq ll (org-do-wrap words w)))
15410 ll))
15411 (t (error "Cannot wrap this")))))
15413 (defun org-do-wrap (words width)
15414 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15415 (let (lines line)
15416 (while words
15417 (setq line (pop words))
15418 (while (and words (< (+ (length line) (length (car words))) width))
15419 (setq line (concat line " " (pop words))))
15420 (setq lines (push line lines)))
15421 (nreverse lines)))
15423 (defun org-split-string (string &optional separators)
15424 "Splits STRING into substrings at SEPARATORS.
15425 No empty strings are returned if there are matches at the beginning
15426 and end of string."
15427 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15428 (start 0)
15429 notfirst
15430 (list nil))
15431 (while (and (string-match rexp string
15432 (if (and notfirst
15433 (= start (match-beginning 0))
15434 (< start (length string)))
15435 (1+ start) start))
15436 (< (match-beginning 0) (length string)))
15437 (setq notfirst t)
15438 (or (eq (match-beginning 0) 0)
15439 (and (eq (match-beginning 0) (match-end 0))
15440 (eq (match-beginning 0) start))
15441 (setq list
15442 (cons (substring string start (match-beginning 0))
15443 list)))
15444 (setq start (match-end 0)))
15445 (or (eq start (length string))
15446 (setq list
15447 (cons (substring string start)
15448 list)))
15449 (nreverse list)))
15451 (defun org-quote-vert (s)
15452 "Replace \"|\" with \"\\vert\"."
15453 (while (string-match "|" s)
15454 (setq s (replace-match "\\vert" t t s)))
15457 (defun org-uuidgen-p (s)
15458 "Is S an ID created by UUIDGEN?"
15459 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15461 (defun org-context ()
15462 "Return a list of contexts of the current cursor position.
15463 If several contexts apply, all are returned.
15464 Each context entry is a list with a symbol naming the context, and
15465 two positions indicating start and end of the context. Possible
15466 contexts are:
15468 :headline anywhere in a headline
15469 :headline-stars on the leading stars in a headline
15470 :todo-keyword on a TODO keyword (including DONE) in a headline
15471 :tags on the TAGS in a headline
15472 :priority on the priority cookie in a headline
15473 :item on the first line of a plain list item
15474 :item-bullet on the bullet/number of a plain list item
15475 :checkbox on the checkbox in a plain list item
15476 :table in an org-mode table
15477 :table-special on a special filed in a table
15478 :table-table in a table.el table
15479 :link on a hyperlink
15480 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15481 :target on a <<target>>
15482 :radio-target on a <<<radio-target>>>
15483 :latex-fragment on a LaTeX fragment
15484 :latex-preview on a LaTeX fragment with overlayed preview image
15486 This function expects the position to be visible because it uses font-lock
15487 faces as a help to recognize the following contexts: :table-special, :link,
15488 and :keyword."
15489 (let* ((f (get-text-property (point) 'face))
15490 (faces (if (listp f) f (list f)))
15491 (p (point)) clist o)
15492 ;; First the large context
15493 (cond
15494 ((org-on-heading-p t)
15495 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15496 (when (progn
15497 (beginning-of-line 1)
15498 (looking-at org-todo-line-tags-regexp))
15499 (push (org-point-in-group p 1 :headline-stars) clist)
15500 (push (org-point-in-group p 2 :todo-keyword) clist)
15501 (push (org-point-in-group p 4 :tags) clist))
15502 (goto-char p)
15503 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15504 (if (looking-at "\\[#[A-Z0-9]\\]")
15505 (push (org-point-in-group p 0 :priority) clist)))
15507 ((org-at-item-p)
15508 (push (org-point-in-group p 2 :item-bullet) clist)
15509 (push (list :item (point-at-bol)
15510 (save-excursion (org-end-of-item) (point)))
15511 clist)
15512 (and (org-at-item-checkbox-p)
15513 (push (org-point-in-group p 0 :checkbox) clist)))
15515 ((org-at-table-p)
15516 (push (list :table (org-table-begin) (org-table-end)) clist)
15517 (if (memq 'org-formula faces)
15518 (push (list :table-special
15519 (previous-single-property-change p 'face)
15520 (next-single-property-change p 'face)) clist)))
15521 ((org-at-table-p 'any)
15522 (push (list :table-table) clist)))
15523 (goto-char p)
15525 ;; Now the small context
15526 (cond
15527 ((org-at-timestamp-p)
15528 (push (org-point-in-group p 0 :timestamp) clist))
15529 ((memq 'org-link faces)
15530 (push (list :link
15531 (previous-single-property-change p 'face)
15532 (next-single-property-change p 'face)) clist))
15533 ((memq 'org-special-keyword faces)
15534 (push (list :keyword
15535 (previous-single-property-change p 'face)
15536 (next-single-property-change p 'face)) clist))
15537 ((org-on-target-p)
15538 (push (org-point-in-group p 0 :target) clist)
15539 (goto-char (1- (match-beginning 0)))
15540 (if (looking-at org-radio-target-regexp)
15541 (push (org-point-in-group p 0 :radio-target) clist))
15542 (goto-char p))
15543 ((setq o (car (delq nil
15544 (mapcar
15545 (lambda (x)
15546 (if (memq x org-latex-fragment-image-overlays) x))
15547 (org-overlays-at (point))))))
15548 (push (list :latex-fragment
15549 (org-overlay-start o) (org-overlay-end o)) clist)
15550 (push (list :latex-preview
15551 (org-overlay-start o) (org-overlay-end o)) clist))
15552 ((org-inside-LaTeX-fragment-p)
15553 ;; FIXME: positions wrong.
15554 (push (list :latex-fragment (point) (point)) clist)))
15556 (setq clist (nreverse (delq nil clist)))
15557 clist))
15559 ;; FIXME: Compare with at-regexp-p Do we need both?
15560 (defun org-in-regexp (re &optional nlines visually)
15561 "Check if point is inside a match of regexp.
15562 Normally only the current line is checked, but you can include NLINES extra
15563 lines both before and after point into the search.
15564 If VISUALLY is set, require that the cursor is not after the match but
15565 really on, so that the block visually is on the match."
15566 (catch 'exit
15567 (let ((pos (point))
15568 (eol (point-at-eol (+ 1 (or nlines 0))))
15569 (inc (if visually 1 0)))
15570 (save-excursion
15571 (beginning-of-line (- 1 (or nlines 0)))
15572 (while (re-search-forward re eol t)
15573 (if (and (<= (match-beginning 0) pos)
15574 (>= (+ inc (match-end 0)) pos))
15575 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15577 (defun org-at-regexp-p (regexp)
15578 "Is point inside a match of REGEXP in the current line?"
15579 (catch 'exit
15580 (save-excursion
15581 (let ((pos (point)) (end (point-at-eol)))
15582 (beginning-of-line 1)
15583 (while (re-search-forward regexp end t)
15584 (if (and (<= (match-beginning 0) pos)
15585 (>= (match-end 0) pos))
15586 (throw 'exit t)))
15587 nil))))
15589 (defun org-occur-in-agenda-files (regexp &optional nlines)
15590 "Call `multi-occur' with buffers for all agenda files."
15591 (interactive "sOrg-files matching: \np")
15592 (let* ((files (org-agenda-files))
15593 (tnames (mapcar 'file-truename files))
15594 (extra org-agenda-text-search-extra-files)
15596 (when (eq (car extra) 'agenda-archives)
15597 (setq extra (cdr extra))
15598 (setq files (org-add-archive-files files)))
15599 (while (setq f (pop extra))
15600 (unless (member (file-truename f) tnames)
15601 (add-to-list 'files f 'append)
15602 (add-to-list 'tnames (file-truename f) 'append)))
15603 (multi-occur
15604 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15605 regexp)))
15607 (if (boundp 'occur-mode-find-occurrence-hook)
15608 ;; Emacs 23
15609 (add-hook 'occur-mode-find-occurrence-hook
15610 (lambda ()
15611 (when (org-mode-p)
15612 (org-reveal))))
15613 ;; Emacs 22
15614 (defadvice occur-mode-goto-occurrence
15615 (after org-occur-reveal activate)
15616 (and (org-mode-p) (org-reveal)))
15617 (defadvice occur-mode-goto-occurrence-other-window
15618 (after org-occur-reveal activate)
15619 (and (org-mode-p) (org-reveal)))
15620 (defadvice occur-mode-display-occurrence
15621 (after org-occur-reveal activate)
15622 (when (org-mode-p)
15623 (let ((pos (occur-mode-find-occurrence)))
15624 (with-current-buffer (marker-buffer pos)
15625 (save-excursion
15626 (goto-char pos)
15627 (org-reveal)))))))
15629 (defun org-uniquify (list)
15630 "Remove duplicate elements from LIST."
15631 (let (res)
15632 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15633 res))
15635 (defun org-delete-all (elts list)
15636 "Remove all elements in ELTS from LIST."
15637 (while elts
15638 (setq list (delete (pop elts) list)))
15639 list)
15641 (defun org-back-over-empty-lines ()
15642 "Move backwards over whitespace, to the beginning of the first empty line.
15643 Returns the number of empty lines passed."
15644 (let ((pos (point)))
15645 (skip-chars-backward " \t\n\r")
15646 (beginning-of-line 2)
15647 (goto-char (min (point) pos))
15648 (count-lines (point) pos)))
15650 (defun org-skip-whitespace ()
15651 (skip-chars-forward " \t\n\r"))
15653 (defun org-point-in-group (point group &optional context)
15654 "Check if POINT is in match-group GROUP.
15655 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15656 match. If the match group does ot exist or point is not inside it,
15657 return nil."
15658 (and (match-beginning group)
15659 (>= point (match-beginning group))
15660 (<= point (match-end group))
15661 (if context
15662 (list context (match-beginning group) (match-end group))
15663 t)))
15665 (defun org-switch-to-buffer-other-window (&rest args)
15666 "Switch to buffer in a second window on the current frame.
15667 In particular, do not allow pop-up frames."
15668 (let (pop-up-frames special-display-buffer-names special-display-regexps
15669 special-display-function)
15670 (apply 'switch-to-buffer-other-window args)))
15672 (defun org-combine-plists (&rest plists)
15673 "Create a single property list from all plists in PLISTS.
15674 The process starts by copying the first list, and then setting properties
15675 from the other lists. Settings in the last list are the most significant
15676 ones and overrule settings in the other lists."
15677 (let ((rtn (copy-sequence (pop plists)))
15678 p v ls)
15679 (while plists
15680 (setq ls (pop plists))
15681 (while ls
15682 (setq p (pop ls) v (pop ls))
15683 (setq rtn (plist-put rtn p v))))
15684 rtn))
15686 (defun org-move-line-down (arg)
15687 "Move the current line down. 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 (+ 1 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-move-line-up (arg)
15700 "Move the current line up. With prefix argument, move it past ARG lines."
15701 (interactive "p")
15702 (let ((col (current-column))
15703 beg end pos)
15704 (beginning-of-line 1) (setq beg (point))
15705 (beginning-of-line 2) (setq end (point))
15706 (beginning-of-line (- arg))
15707 (setq pos (move-marker (make-marker) (point)))
15708 (insert (delete-and-extract-region beg end))
15709 (goto-char pos)
15710 (org-move-to-column col)))
15712 (defun org-replace-escapes (string table)
15713 "Replace %-escapes in STRING with values in TABLE.
15714 TABLE is an association list with keys like \"%a\" and string values.
15715 The sequences in STRING may contain normal field width and padding information,
15716 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15717 so values can contain further %-escapes if they are define later in TABLE."
15718 (let ((case-fold-search nil)
15719 e re rpl)
15720 (while (setq e (pop table))
15721 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15722 (while (string-match re string)
15723 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15724 (cdr e)))
15725 (setq string (replace-match rpl t t string))))
15726 string))
15729 (defun org-sublist (list start end)
15730 "Return a section of LIST, from START to END.
15731 Counting starts at 1."
15732 (let (rtn (c start))
15733 (setq list (nthcdr (1- start) list))
15734 (while (and list (<= c end))
15735 (push (pop list) rtn)
15736 (setq c (1+ c)))
15737 (nreverse rtn)))
15739 (defun org-find-base-buffer-visiting (file)
15740 "Like `find-buffer-visiting' but always return the base buffer and
15741 not an indirect buffer."
15742 (let ((buf (or (get-file-buffer file)
15743 (find-buffer-visiting file))))
15744 (if buf
15745 (or (buffer-base-buffer buf) buf)
15746 nil)))
15748 (defun org-image-file-name-regexp (&optional extensions)
15749 "Return regexp matching the file names of images.
15750 If EXTENSIONS is given, only match these."
15751 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15752 (image-file-name-regexp)
15753 (let ((image-file-name-extensions
15754 (or extensions
15755 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15756 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15757 (concat "\\."
15758 (regexp-opt (nconc (mapcar 'upcase
15759 image-file-name-extensions)
15760 image-file-name-extensions)
15762 "\\'"))))
15764 (defun org-file-image-p (file &optional extensions)
15765 "Return non-nil if FILE is an image."
15766 (save-match-data
15767 (string-match (org-image-file-name-regexp extensions) file)))
15769 (defun org-get-cursor-date ()
15770 "Return the date at cursor in as a time.
15771 This works in the calendar and in the agenda, anywhere else it just
15772 returns the current time."
15773 (let (date day defd)
15774 (cond
15775 ((eq major-mode 'calendar-mode)
15776 (setq date (calendar-cursor-to-date)
15777 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15778 ((eq major-mode 'org-agenda-mode)
15779 (setq day (get-text-property (point) 'day))
15780 (if day
15781 (setq date (calendar-gregorian-from-absolute day)
15782 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15783 (nth 2 date))))))
15784 (or defd (current-time))))
15786 (defvar org-agenda-action-marker (make-marker)
15787 "Marker pointing to the entry for the next agenda action.")
15789 (defun org-mark-entry-for-agenda-action ()
15790 "Mark the current entry as target of an agenda action.
15791 Agenda actions are actions executed from the agenda with the key `k',
15792 which make use of the date at the cursor."
15793 (interactive)
15794 (move-marker org-agenda-action-marker
15795 (save-excursion (org-back-to-heading t) (point))
15796 (current-buffer))
15797 (message
15798 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15800 ;;; Paragraph filling stuff.
15801 ;; We want this to be just right, so use the full arsenal.
15803 (defun org-indent-line-function ()
15804 "Indent line like previous, but further if previous was headline or item."
15805 (interactive)
15806 (let* ((pos (point))
15807 (itemp (org-at-item-p))
15808 (case-fold-search t)
15809 (org-drawer-regexp (or org-drawer-regexp "\000"))
15810 column bpos bcol tpos tcol bullet btype bullet-type)
15811 ;; Find the previous relevant line
15812 (beginning-of-line 1)
15813 (cond
15814 ((looking-at "#") (setq column 0))
15815 ((looking-at "\\*+ ") (setq column 0))
15816 ((and (looking-at "[ \t]*:END:")
15817 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15818 (save-excursion
15819 (goto-char (1- (match-beginning 1)))
15820 (setq column (current-column))))
15821 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
15822 (save-excursion
15823 (re-search-backward
15824 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
15825 (setq column (org-get-indentation (match-string 0))))
15827 (beginning-of-line 0)
15828 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15829 (not (looking-at "[ \t]*:END:"))
15830 (not (looking-at org-drawer-regexp)))
15831 (beginning-of-line 0))
15832 (cond
15833 ((looking-at "\\*+[ \t]+")
15834 (if (not org-adapt-indentation)
15835 (setq column 0)
15836 (goto-char (match-end 0))
15837 (setq column (current-column))))
15838 ((looking-at org-drawer-regexp)
15839 (goto-char (1- (match-beginning 1)))
15840 (setq column (current-column)))
15841 ((looking-at "\\([ \t]*\\):END:")
15842 (goto-char (match-end 1))
15843 (setq column (current-column)))
15844 ((org-in-item-p)
15845 (org-beginning-of-item)
15846 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15847 (setq bpos (match-beginning 1) tpos (match-end 0)
15848 bcol (progn (goto-char bpos) (current-column))
15849 tcol (progn (goto-char tpos) (current-column))
15850 bullet (match-string 1)
15851 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15852 (if (> tcol (+ bcol org-description-max-indent))
15853 (setq tcol (+ bcol 5)))
15854 (if (not itemp)
15855 (setq column tcol)
15856 (goto-char pos)
15857 (beginning-of-line 1)
15858 (if (looking-at "\\S-")
15859 (progn
15860 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15861 (setq bullet (match-string 1)
15862 btype (if (string-match "[0-9]" bullet) "n" bullet))
15863 (setq column (if (equal btype bullet-type) bcol tcol)))
15864 (setq column (org-get-indentation)))))
15865 (t (setq column (org-get-indentation))))))
15866 (goto-char pos)
15867 (if (<= (current-column) (current-indentation))
15868 (org-indent-line-to column)
15869 (save-excursion (org-indent-line-to column)))
15870 (setq column (current-column))
15871 (beginning-of-line 1)
15872 (if (looking-at
15873 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15874 (replace-match (concat "\\1" (format org-property-format
15875 (match-string 2) (match-string 3)))
15876 t nil))
15877 (org-move-to-column column)))
15879 (defun org-set-autofill-regexps ()
15880 (interactive)
15881 ;; In the paragraph separator we include headlines, because filling
15882 ;; text in a line directly attached to a headline would otherwise
15883 ;; fill the headline as well.
15884 (org-set-local 'comment-start-skip "^#+[ \t]*")
15885 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15886 ;; The paragraph starter includes hand-formatted lists.
15887 (org-set-local
15888 'paragraph-start
15889 (concat
15890 "\f" "\\|"
15891 "[ ]*$" "\\|"
15892 "\\*+ " "\\|"
15893 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
15894 "[ \t]*[:|]" "\\|"
15895 "\\$\\$" "\\|"
15896 "\\\\\\(begin\\|end\\|[][]\\)"))
15897 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15898 ;; But only if the user has not turned off tables or fixed-width regions
15899 (org-set-local
15900 'auto-fill-inhibit-regexp
15901 (concat "\\*+ \\|#\\+"
15902 "\\|[ \t]*" org-keyword-time-regexp
15903 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15904 (concat
15905 "\\|[ \t]*["
15906 (if org-enable-table-editor "|" "")
15907 (if org-enable-fixed-width-editor ":" "")
15908 "]"))))
15909 ;; We use our own fill-paragraph function, to make sure that tables
15910 ;; and fixed-width regions are not wrapped. That function will pass
15911 ;; through to `fill-paragraph' when appropriate.
15912 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15913 ; Adaptive filling: To get full control, first make sure that
15914 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15915 (org-set-local 'adaptive-fill-regexp "\000")
15916 (org-set-local 'adaptive-fill-function
15917 'org-adaptive-fill-function)
15918 (org-set-local
15919 'align-mode-rules-list
15920 '((org-in-buffer-settings
15921 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15922 (modes . '(org-mode))))))
15924 (defun org-fill-paragraph (&optional justify)
15925 "Re-align a table, pass through to fill-paragraph if no table."
15926 (let ((table-p (org-at-table-p))
15927 (table.el-p (org-at-table.el-p)))
15928 (cond ((and (equal (char-after (point-at-bol)) ?*)
15929 (save-excursion (goto-char (point-at-bol))
15930 (looking-at outline-regexp)))
15931 t) ; skip headlines
15932 (table.el-p t) ; skip table.el tables
15933 (table-p (org-table-align) t) ; align org-mode tables
15934 (t nil)))) ; call paragraph-fill
15936 ;; For reference, this is the default value of adaptive-fill-regexp
15937 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15939 (defun org-adaptive-fill-function ()
15940 "Return a fill prefix for org-mode files.
15941 In particular, this makes sure hanging paragraphs for hand-formatted lists
15942 work correctly."
15943 (cond ((looking-at "#[ \t]+")
15944 (match-string 0))
15945 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15946 (save-excursion
15947 (if (> (match-end 1) (+ (match-beginning 1)
15948 org-description-max-indent))
15949 (goto-char (+ (match-beginning 1) 5))
15950 (goto-char (match-end 0)))
15951 (make-string (current-column) ?\ )))
15952 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15953 (save-excursion
15954 (goto-char (match-end 0))
15955 (make-string (current-column) ?\ )))
15956 (t nil)))
15958 ;;; Other stuff.
15960 (defun org-toggle-fixed-width-section (arg)
15961 "Toggle the fixed-width export.
15962 If there is no active region, the QUOTE keyword at the current headline is
15963 inserted or removed. When present, it causes the text between this headline
15964 and the next to be exported as fixed-width text, and unmodified.
15965 If there is an active region, this command adds or removes a colon as the
15966 first character of this line. If the first character of a line is a colon,
15967 this line is also exported in fixed-width font."
15968 (interactive "P")
15969 (let* ((cc 0)
15970 (regionp (org-region-active-p))
15971 (beg (if regionp (region-beginning) (point)))
15972 (end (if regionp (region-end)))
15973 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15974 (case-fold-search nil)
15975 (re "[ \t]*\\(: \\)")
15976 off)
15977 (if regionp
15978 (save-excursion
15979 (goto-char beg)
15980 (setq cc (current-column))
15981 (beginning-of-line 1)
15982 (setq off (looking-at re))
15983 (while (> nlines 0)
15984 (setq nlines (1- nlines))
15985 (beginning-of-line 1)
15986 (cond
15987 (arg
15988 (org-move-to-column cc t)
15989 (insert ": \n")
15990 (forward-line -1))
15991 ((and off (looking-at re))
15992 (replace-match "" t t nil 1))
15993 ((not off) (org-move-to-column cc t) (insert ": ")))
15994 (forward-line 1)))
15995 (save-excursion
15996 (org-back-to-heading)
15997 (if (looking-at (concat outline-regexp
15998 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15999 (replace-match "" t t nil 1)
16000 (if (looking-at outline-regexp)
16001 (progn
16002 (goto-char (match-end 0))
16003 (insert org-quote-string " "))))))))
16005 (defun org-reftex-citation ()
16006 "Use reftex-citation to insert a citation into the buffer.
16007 This looks for a line like
16009 #+BIBLIOGRAPHY: foo plain option:-d
16011 and derives from it that foo.bib is the bbliography file relevant
16012 for this document. It then installs the necessary environment for RefTeX
16013 to work in this buffer and calls `reftex-citation' to insert a citation
16014 into the buffer.
16016 Export of such citations to both LaTeX and HTML is handled by the contributed
16017 package org-exp-bibtex by Taru Karttunen."
16018 (interactive)
16019 (let ((reftex-docstruct-symbol 'rds)
16020 (reftex-cite-format "\\cite{%l}")
16021 rds bib)
16022 (save-excursion
16023 (save-restriction
16024 (widen)
16025 (let ((case-fold-search t)
16026 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16027 (if (not (save-excursion
16028 (or (re-search-forward re nil t)
16029 (re-search-backward re nil t))))
16030 (error "No bibliography defined in file")
16031 (setq bib (concat (match-string 1) ".bib")
16032 rds (list (list 'bib bib)))))))
16033 (call-interactively 'reftex-citation)))
16035 ;;;; Functions extending outline functionality
16037 (defun org-beginning-of-line (&optional arg)
16038 "Go to the beginning of the current line. If that is invisible, continue
16039 to a visible line beginning. This makes the function of C-a more intuitive.
16040 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16041 first attempt, and only move to after the tags when the cursor is already
16042 beyond the end of the headline."
16043 (interactive "P")
16044 (let ((pos (point))
16045 (special (if (consp org-special-ctrl-a/e)
16046 (car org-special-ctrl-a/e)
16047 org-special-ctrl-a/e))
16048 refpos)
16049 (if (org-bound-and-true-p line-move-visual)
16050 (beginning-of-visual-line 1)
16051 (beginning-of-line 1))
16052 (if (and arg (fboundp 'move-beginning-of-line))
16053 (call-interactively 'move-beginning-of-line)
16054 (if (bobp)
16056 (backward-char 1)
16057 (if (org-invisible-p)
16058 (while (and (not (bobp)) (org-invisible-p))
16059 (backward-char 1)
16060 (beginning-of-line 1))
16061 (forward-char 1))))
16062 (when special
16063 (cond
16064 ((and (looking-at org-complex-heading-regexp)
16065 (= (char-after (match-end 1)) ?\ ))
16066 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16067 (point-at-eol)))
16068 (goto-char
16069 (if (eq special t)
16070 (cond ((> pos refpos) refpos)
16071 ((= pos (point)) refpos)
16072 (t (point)))
16073 (cond ((> pos (point)) (point))
16074 ((not (eq last-command this-command)) (point))
16075 (t refpos)))))
16076 ((org-at-item-p)
16077 (goto-char
16078 (if (eq special t)
16079 (cond ((> pos (match-end 4)) (match-end 4))
16080 ((= pos (point)) (match-end 4))
16081 (t (point)))
16082 (cond ((> pos (point)) (point))
16083 ((not (eq last-command this-command)) (point))
16084 (t (match-end 4))))))))
16085 (org-no-warnings
16086 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16088 (defun org-end-of-line (&optional arg)
16089 "Go to the end of the line.
16090 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16091 first attempt, and only move to after the tags when the cursor is already
16092 beyond the end of the headline."
16093 (interactive "P")
16094 (let ((special (if (consp org-special-ctrl-a/e)
16095 (cdr org-special-ctrl-a/e)
16096 org-special-ctrl-a/e)))
16097 (if (or (not special)
16098 (not (org-on-heading-p))
16099 arg)
16100 (call-interactively
16101 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
16102 ((fboundp 'move-end-of-line) 'move-end-of-line)
16103 (t 'end-of-line)))
16104 (let ((pos (point)))
16105 (beginning-of-line 1)
16106 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16107 (if (eq special t)
16108 (if (or (< pos (match-beginning 1))
16109 (= pos (match-end 0)))
16110 (goto-char (match-beginning 1))
16111 (goto-char (match-end 0)))
16112 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16113 (goto-char (match-end 0))
16114 (goto-char (match-beginning 1))))
16115 (call-interactively (if (fboundp 'move-end-of-line)
16116 'move-end-of-line
16117 'end-of-line)))))
16118 (org-no-warnings
16119 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16121 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16122 (define-key org-mode-map "\C-e" 'org-end-of-line)
16124 (defun org-backward-sentence (&optional arg)
16125 "Go to beginning of sentence, or beginning of table field.
16126 This will call `backward-sentence' or `org-table-beginning-of-field',
16127 depending on context."
16128 (interactive "P")
16129 (cond
16130 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16131 (t (call-interactively 'backward-sentence))))
16133 (defun org-forward-sentence (&optional arg)
16134 "Go to end of sentence, or end of table field.
16135 This will call `forward-sentence' or `org-table-end-of-field',
16136 depending on context."
16137 (interactive "P")
16138 (cond
16139 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16140 (t (call-interactively 'forward-sentence))))
16142 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16143 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16145 (defun org-kill-line (&optional arg)
16146 "Kill line, to tags or end of line."
16147 (interactive "P")
16148 (cond
16149 ((or (not org-special-ctrl-k)
16150 (bolp)
16151 (not (org-on-heading-p)))
16152 (call-interactively 'kill-line))
16153 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16154 (kill-region (point) (match-beginning 1))
16155 (org-set-tags nil t))
16156 (t (kill-region (point) (point-at-eol)))))
16158 (define-key org-mode-map "\C-k" 'org-kill-line)
16160 (defun org-yank (&optional arg)
16161 "Yank. If the kill is a subtree, treat it specially.
16162 This command will look at the current kill and check if is a single
16163 subtree, or a series of subtrees[1]. If it passes the test, and if the
16164 cursor is at the beginning of a line or after the stars of a currently
16165 empty headline, then the yank is handled specially. How exactly depends
16166 on the value of the following variables, both set by default.
16168 org-yank-folded-subtrees
16169 When set, the subtree(s) will be folded after insertion, but only
16170 if doing so would now swallow text after the yanked text.
16172 org-yank-adjusted-subtrees
16173 When set, the subtree will be promoted or demoted in order to
16174 fit into the local outline tree structure, which means that the level
16175 will be adjusted so that it becomes the smaller one of the two
16176 *visible* surrounding headings.
16178 Any prefix to this command will cause `yank' to be called directly with
16179 no special treatment. In particular, a simple `C-u' prefix will just
16180 plainly yank the text as it is.
16182 \[1] The test checks if the first non-white line is a heading
16183 and if there are no other headings with fewer stars."
16184 (interactive "P")
16185 (org-yank-generic 'yank arg))
16187 (defun org-yank-generic (command arg)
16188 "Perform some yank-like command.
16190 This function implements the behavior described in the `org-yank'
16191 documentation. However, it has been generalized to work for any
16192 interactive command with similar behavior."
16194 ;; pretend to be command COMMAND
16195 (setq this-command command)
16197 (if arg
16198 (call-interactively command)
16200 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16201 (and (org-kill-is-subtree-p)
16202 (or (bolp)
16203 (and (looking-at "[ \t]*$")
16204 (string-match
16205 "\\`\\*+\\'"
16206 (buffer-substring (point-at-bol) (point)))))))
16207 swallowp)
16208 (cond
16209 ((and subtreep org-yank-folded-subtrees)
16210 (let ((beg (point))
16211 end)
16212 (if (and subtreep org-yank-adjusted-subtrees)
16213 (org-paste-subtree nil nil 'for-yank)
16214 (call-interactively command))
16216 (setq end (point))
16217 (goto-char beg)
16218 (when (and (bolp) subtreep
16219 (not (setq swallowp
16220 (org-yank-folding-would-swallow-text beg end))))
16221 (or (looking-at outline-regexp)
16222 (re-search-forward (concat "^" outline-regexp) end t))
16223 (while (and (< (point) end) (looking-at outline-regexp))
16224 (hide-subtree)
16225 (org-cycle-show-empty-lines 'folded)
16226 (condition-case nil
16227 (outline-forward-same-level 1)
16228 (error (goto-char end)))))
16229 (when swallowp
16230 (message
16231 "Inserted text not folded because that would swallow text"))
16233 (goto-char end)
16234 (skip-chars-forward " \t\n\r")
16235 (beginning-of-line 1)
16236 (push-mark beg 'nomsg)))
16237 ((and subtreep org-yank-adjusted-subtrees)
16238 (let ((beg (point-at-bol)))
16239 (org-paste-subtree nil nil 'for-yank)
16240 (push-mark beg 'nomsg)))
16242 (call-interactively command))))))
16244 (defun org-yank-folding-would-swallow-text (beg end)
16245 "Would hide-subtree at BEG swallow any text after END?"
16246 (let (level)
16247 (save-excursion
16248 (goto-char beg)
16249 (when (or (looking-at outline-regexp)
16250 (re-search-forward (concat "^" outline-regexp) end t))
16251 (setq level (org-outline-level)))
16252 (goto-char end)
16253 (skip-chars-forward " \t\r\n\v\f")
16254 (if (or (eobp)
16255 (and (bolp) (looking-at org-outline-regexp)
16256 (<= (org-outline-level) level)))
16257 nil ; Nothing would be swallowed
16258 t)))) ; something would swallow
16260 (define-key org-mode-map "\C-y" 'org-yank)
16262 (defun org-invisible-p ()
16263 "Check if point is at a character currently not visible."
16264 ;; Early versions of noutline don't have `outline-invisible-p'.
16265 (if (fboundp 'outline-invisible-p)
16266 (outline-invisible-p)
16267 (get-char-property (point) 'invisible)))
16269 (defun org-invisible-p2 ()
16270 "Check if point is at a character currently not visible."
16271 (save-excursion
16272 (if (and (eolp) (not (bobp))) (backward-char 1))
16273 ;; Early versions of noutline don't have `outline-invisible-p'.
16274 (if (fboundp 'outline-invisible-p)
16275 (outline-invisible-p)
16276 (get-char-property (point) 'invisible))))
16278 (defun org-back-to-heading (&optional invisible-ok)
16279 "Call `outline-back-to-heading', but provide a better error message."
16280 (condition-case nil
16281 (outline-back-to-heading invisible-ok)
16282 (error (error "Before first headline at position %d in buffer %s"
16283 (point) (current-buffer)))))
16285 (defun org-before-first-heading-p ()
16286 "Before first heading?"
16287 (save-excursion
16288 (null (re-search-backward "^\\*+ " nil t))))
16290 (defalias 'org-on-heading-p 'outline-on-heading-p)
16291 (defalias 'org-at-heading-p 'outline-on-heading-p)
16292 (defun org-at-heading-or-item-p ()
16293 (or (org-on-heading-p) (org-at-item-p)))
16295 (defun org-on-target-p ()
16296 (or (org-in-regexp org-radio-target-regexp)
16297 (org-in-regexp org-target-regexp)))
16299 (defun org-up-heading-all (arg)
16300 "Move to the heading line of which the present line is a subheading.
16301 This function considers both visible and invisible heading lines.
16302 With argument, move up ARG levels."
16303 (if (fboundp 'outline-up-heading-all)
16304 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16305 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16307 (defun org-up-heading-safe ()
16308 "Move to the heading line of which the present line is a subheading.
16309 This version will not throw an error. It will return the level of the
16310 headline found, or nil if no higher level is found.
16312 Also, this function will be a lot faster than `outline-up-heading',
16313 because it relies on stars being the outline starters. This can really
16314 make a significant difference in outlines with very many siblings."
16315 (let (start-level re)
16316 (org-back-to-heading t)
16317 (setq start-level (funcall outline-level))
16318 (if (equal start-level 1)
16320 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16321 (if (re-search-backward re nil t)
16322 (funcall outline-level)))))
16324 (defun org-first-sibling-p ()
16325 "Is this heading the first child of its parents?"
16326 (interactive)
16327 (let ((re (concat "^" outline-regexp))
16328 level l)
16329 (unless (org-at-heading-p t)
16330 (error "Not at a heading"))
16331 (setq level (funcall outline-level))
16332 (save-excursion
16333 (if (not (re-search-backward re nil t))
16335 (setq l (funcall outline-level))
16336 (< l level)))))
16338 (defun org-goto-sibling (&optional previous)
16339 "Goto the next sibling, even if it is invisible.
16340 When PREVIOUS is set, go to the previous sibling instead. Returns t
16341 when a sibling was found. When none is found, return nil and don't
16342 move point."
16343 (let ((fun (if previous 're-search-backward 're-search-forward))
16344 (pos (point))
16345 (re (concat "^" outline-regexp))
16346 level l)
16347 (when (condition-case nil (org-back-to-heading t) (error nil))
16348 (setq level (funcall outline-level))
16349 (catch 'exit
16350 (or previous (forward-char 1))
16351 (while (funcall fun re nil t)
16352 (setq l (funcall outline-level))
16353 (when (< l level) (goto-char pos) (throw 'exit nil))
16354 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16355 (goto-char pos)
16356 nil))))
16358 (defun org-show-siblings ()
16359 "Show all siblings of the current headline."
16360 (save-excursion
16361 (while (org-goto-sibling) (org-flag-heading nil)))
16362 (save-excursion
16363 (while (org-goto-sibling 'previous)
16364 (org-flag-heading nil))))
16366 (defun org-show-hidden-entry ()
16367 "Show an entry where even the heading is hidden."
16368 (save-excursion
16369 (org-show-entry)))
16371 (defun org-flag-heading (flag &optional entry)
16372 "Flag the current heading. FLAG non-nil means make invisible.
16373 When ENTRY is non-nil, show the entire entry."
16374 (save-excursion
16375 (org-back-to-heading t)
16376 ;; Check if we should show the entire entry
16377 (if entry
16378 (progn
16379 (org-show-entry)
16380 (save-excursion
16381 (and (outline-next-heading)
16382 (org-flag-heading nil))))
16383 (outline-flag-region (max (point-min) (1- (point)))
16384 (save-excursion (outline-end-of-heading) (point))
16385 flag))))
16387 (defun org-get-next-sibling ()
16388 "Move to next heading of the same level, and return point.
16389 If there is no such heading, return nil.
16390 This is like outline-next-sibling, but invisible headings are ok."
16391 (let ((level (funcall outline-level)))
16392 (outline-next-heading)
16393 (while (and (not (eobp)) (> (funcall outline-level) level))
16394 (outline-next-heading))
16395 (if (or (eobp) (< (funcall outline-level) level))
16397 (point))))
16399 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16400 ;; This contains an exact copy of the original function, but it uses
16401 ;; `org-back-to-heading', to make it work also in invisible
16402 ;; trees. And is uses an invisible-OK argument.
16403 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16404 ;; Furthermore, when used inside Org, finding the end of a large subtree
16405 ;; with many children and grandchildren etc, this can be much faster
16406 ;; than the outline version.
16407 (org-back-to-heading invisible-OK)
16408 (let ((first t)
16409 (level (funcall outline-level)))
16410 (if (and (org-mode-p) (< level 1000))
16411 ;; A true heading (not a plain list item), in Org-mode
16412 ;; This means we can easily find the end by looking
16413 ;; only for the right number of stars. Using a regexp to do
16414 ;; this is so much faster than using a Lisp loop.
16415 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16416 (forward-char 1)
16417 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16418 ;; something else, do it the slow way
16419 (while (and (not (eobp))
16420 (or first (> (funcall outline-level) level)))
16421 (setq first nil)
16422 (outline-next-heading)))
16423 (unless to-heading
16424 (if (memq (preceding-char) '(?\n ?\^M))
16425 (progn
16426 ;; Go to end of line before heading
16427 (forward-char -1)
16428 (if (memq (preceding-char) '(?\n ?\^M))
16429 ;; leave blank line before heading
16430 (forward-char -1))))))
16431 (point))
16433 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
16434 "Use Org version in org-mode, for dramatic speed-up."
16435 (if (eq major-mode 'org-mode)
16436 (org-end-of-subtree)
16437 ad-do-it))
16439 (defun org-forward-same-level (arg &optional invisible-ok)
16440 "Move forward to the arg'th subheading at same level as this one.
16441 Stop at the first and last subheadings of a superior heading."
16442 (interactive "p")
16443 (org-back-to-heading)
16444 (org-on-heading-p)
16445 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16446 (re (format "^\\*\\{1,%d\\} " level))
16448 (forward-char 1)
16449 (while (> arg 0)
16450 (while (and (re-search-forward re nil 'move)
16451 (setq l (- (match-end 0) (match-beginning 0) 1))
16452 (= l level)
16453 (not invisible-ok)
16454 (org-invisible-p))
16455 (if (< l level) (setq arg 1)))
16456 (setq arg (1- arg)))
16457 (beginning-of-line 1)))
16459 (defun org-backward-same-level (arg &optional invisible-ok)
16460 "Move backward to the arg'th subheading at same level as this one.
16461 Stop at the first and last subheadings of a superior heading."
16462 (interactive "p")
16463 (org-back-to-heading)
16464 (org-on-heading-p)
16465 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16466 (re (format "^\\*\\{1,%d\\} " level))
16468 (while (> arg 0)
16469 (while (and (re-search-backward re nil 'move)
16470 (setq l (- (match-end 0) (match-beginning 0) 1))
16471 (= l level)
16472 (not invisible-ok)
16473 (org-invisible-p))
16474 (if (< l level) (setq arg 1)))
16475 (setq arg (1- arg)))))
16477 (defun org-show-subtree ()
16478 "Show everything after this heading at deeper levels."
16479 (outline-flag-region
16480 (point)
16481 (save-excursion
16482 (outline-end-of-subtree) (outline-next-heading) (point))
16483 nil))
16485 (defun org-show-entry ()
16486 "Show the body directly following this heading.
16487 Show the heading too, if it is currently invisible."
16488 (interactive)
16489 (save-excursion
16490 (condition-case nil
16491 (progn
16492 (org-back-to-heading t)
16493 (outline-flag-region
16494 (max (point-min) (1- (point)))
16495 (save-excursion
16496 (if (re-search-forward
16497 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16498 (match-beginning 1)
16499 (point-max)))
16500 nil)
16501 (org-cycle-hide-drawers 'children))
16502 (error nil))))
16504 (defun org-make-options-regexp (kwds &optional extra)
16505 "Make a regular expression for keyword lines."
16506 (concat
16508 "#?[ \t]*\\+\\("
16509 (mapconcat 'regexp-quote kwds "\\|")
16510 (if extra (concat "\\|" extra))
16511 "\\):[ \t]*"
16512 "\\(.+\\)"))
16514 ;; Make isearch reveal the necessary context
16515 (defun org-isearch-end ()
16516 "Reveal context after isearch exits."
16517 (when isearch-success ; only if search was successful
16518 (if (featurep 'xemacs)
16519 ;; Under XEmacs, the hook is run in the correct place,
16520 ;; we directly show the context.
16521 (org-show-context 'isearch)
16522 ;; In Emacs the hook runs *before* restoring the overlays.
16523 ;; So we have to use a one-time post-command-hook to do this.
16524 ;; (Emacs 22 has a special variable, see function `org-mode')
16525 (unless (and (boundp 'isearch-mode-end-hook-quit)
16526 isearch-mode-end-hook-quit)
16527 ;; Only when the isearch was not quitted.
16528 (org-add-hook 'post-command-hook 'org-isearch-post-command
16529 'append 'local)))))
16531 (defun org-isearch-post-command ()
16532 "Remove self from hook, and show context."
16533 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16534 (org-show-context 'isearch))
16537 ;;;; Integration with and fixes for other packages
16539 ;;; Imenu support
16541 (defvar org-imenu-markers nil
16542 "All markers currently used by Imenu.")
16543 (make-variable-buffer-local 'org-imenu-markers)
16545 (defun org-imenu-new-marker (&optional pos)
16546 "Return a new marker for use by Imenu, and remember the marker."
16547 (let ((m (make-marker)))
16548 (move-marker m (or pos (point)))
16549 (push m org-imenu-markers)
16552 (defun org-imenu-get-tree ()
16553 "Produce the index for Imenu."
16554 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16555 (setq org-imenu-markers nil)
16556 (let* ((n org-imenu-depth)
16557 (re (concat "^" outline-regexp))
16558 (subs (make-vector (1+ n) nil))
16559 (last-level 0)
16560 m level head)
16561 (save-excursion
16562 (save-restriction
16563 (widen)
16564 (goto-char (point-max))
16565 (while (re-search-backward re nil t)
16566 (setq level (org-reduced-level (funcall outline-level)))
16567 (when (<= level n)
16568 (looking-at org-complex-heading-regexp)
16569 (setq head (org-link-display-format
16570 (org-match-string-no-properties 4))
16571 m (org-imenu-new-marker))
16572 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16573 (if (>= level last-level)
16574 (push (cons head m) (aref subs level))
16575 (push (cons head (aref subs (1+ level))) (aref subs level))
16576 (loop for i from (1+ level) to n do (aset subs i nil)))
16577 (setq last-level level)))))
16578 (aref subs 1)))
16580 (eval-after-load "imenu"
16581 '(progn
16582 (add-hook 'imenu-after-jump-hook
16583 (lambda ()
16584 (if (eq major-mode 'org-mode)
16585 (org-show-context 'org-goto))))))
16587 (defun org-link-display-format (link)
16588 "Replace a link with either the description, or the link target
16589 if no description is present"
16590 (save-match-data
16591 (if (string-match org-bracket-link-analytic-regexp link)
16592 (replace-match (or (match-string 5 link)
16593 (concat (match-string 1 link)
16594 (match-string 3 link)))
16595 nil nil link)
16596 link)))
16598 ;; Speedbar support
16600 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16601 "Overlay marking the agenda restriction line in speedbar.")
16602 (org-overlay-put org-speedbar-restriction-lock-overlay
16603 'face 'org-agenda-restriction-lock)
16604 (org-overlay-put org-speedbar-restriction-lock-overlay
16605 'help-echo "Agendas are currently limited to this item.")
16606 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16608 (defun org-speedbar-set-agenda-restriction ()
16609 "Restrict future agenda commands to the location at point in speedbar.
16610 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16611 (interactive)
16612 (require 'org-agenda)
16613 (let (p m tp np dir txt)
16614 (cond
16615 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16616 'org-imenu t))
16617 (setq m (get-text-property p 'org-imenu-marker))
16618 (save-excursion
16619 (save-restriction
16620 (set-buffer (marker-buffer m))
16621 (goto-char m)
16622 (org-agenda-set-restriction-lock 'subtree))))
16623 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16624 'speedbar-function 'speedbar-find-file))
16625 (setq tp (previous-single-property-change
16626 (1+ p) 'speedbar-function)
16627 np (next-single-property-change
16628 tp 'speedbar-function)
16629 dir (speedbar-line-directory)
16630 txt (buffer-substring-no-properties (or tp (point-min))
16631 (or np (point-max))))
16632 (save-excursion
16633 (save-restriction
16634 (set-buffer (find-file-noselect
16635 (let ((default-directory dir))
16636 (expand-file-name txt))))
16637 (unless (org-mode-p)
16638 (error "Cannot restrict to non-Org-mode file"))
16639 (org-agenda-set-restriction-lock 'file))))
16640 (t (error "Don't know how to restrict Org-mode's agenda")))
16641 (org-move-overlay org-speedbar-restriction-lock-overlay
16642 (point-at-bol) (point-at-eol))
16643 (setq current-prefix-arg nil)
16644 (org-agenda-maybe-redo)))
16646 (eval-after-load "speedbar"
16647 '(progn
16648 (speedbar-add-supported-extension ".org")
16649 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16650 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16651 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16652 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16653 (add-hook 'speedbar-visiting-tag-hook
16654 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16657 ;;; Fixes and Hacks for problems with other packages
16659 ;; Make flyspell not check words in links, to not mess up our keymap
16660 (defun org-mode-flyspell-verify ()
16661 "Don't let flyspell put overlays at active buttons."
16662 (and (not (get-text-property (point) 'keymap))
16663 (not (get-text-property (point) 'org-no-flyspell))))
16665 (defun org-remove-flyspell-overlays-in (beg end)
16666 "Remove flyspell overlays in region."
16667 (and (org-bound-and-true-p flyspell-mode)
16668 (fboundp 'flyspell-delete-region-overlays)
16669 (flyspell-delete-region-overlays beg end))
16670 (add-text-properties beg end '(org-no-flyspell t)))
16672 ;; Make `bookmark-jump' show the jump location if it was hidden.
16673 (eval-after-load "bookmark"
16674 '(if (boundp 'bookmark-after-jump-hook)
16675 ;; We can use the hook
16676 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16677 ;; Hook not available, use advice
16678 (defadvice bookmark-jump (after org-make-visible activate)
16679 "Make the position visible."
16680 (org-bookmark-jump-unhide))))
16682 ;; Make sure saveplace show the location if it was hidden
16683 (eval-after-load "saveplace"
16684 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16685 "Make the position visible."
16686 (org-bookmark-jump-unhide)))
16688 (defun org-bookmark-jump-unhide ()
16689 "Unhide the current position, to show the bookmark location."
16690 (and (org-mode-p)
16691 (or (org-invisible-p)
16692 (save-excursion (goto-char (max (point-min) (1- (point))))
16693 (org-invisible-p)))
16694 (org-show-context 'bookmark-jump)))
16696 ;; Make session.el ignore our circular variable
16697 (eval-after-load "session"
16698 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16700 ;;;; Experimental code
16702 (defun org-closed-in-range ()
16703 "Sparse tree of items closed in a certain time range.
16704 Still experimental, may disappear in the future."
16705 (interactive)
16706 ;; Get the time interval from the user.
16707 (let* ((time1 (time-to-seconds
16708 (org-read-date nil 'to-time nil "Starting date: ")))
16709 (time2 (time-to-seconds
16710 (org-read-date nil 'to-time nil "End date:")))
16711 ;; callback function
16712 (callback (lambda ()
16713 (let ((time
16714 (time-to-seconds
16715 (apply 'encode-time
16716 (org-parse-time-string
16717 (match-string 1))))))
16718 ;; check if time in interval
16719 (and (>= time time1) (<= time time2))))))
16720 ;; make tree, check each match with the callback
16721 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16723 ;;;; Finish up
16725 (provide 'org)
16727 (run-hooks 'org-load-hook)
16729 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16731 ;;; org.el ends here