New option org-tags-sort-function.
[org-mode.git] / lisp / org.el
blob426f8902030eeb05df65a6c77b44892ecf6a28e7
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 when promoting and demoting.
688 When this is set and the *entire* text in an entry is indented, the
689 indentation is increased by one space in a demotion command, and
690 decreased by one in a promotion command. If any line in the entry
691 body starts at column 0, indentation is not changed at all.
693 This variable also influences how property drawers and planning
694 information is inserted. When t, these lines drawers will be inserted
695 indented. When nil, they will not be indented."
696 :group 'org-edit-structure
697 :type 'boolean)
699 (defcustom org-special-ctrl-a/e nil
700 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
702 When t, `C-a' will bring back the cursor to the beginning of the
703 headline text, i.e. after the stars and after a possible TODO keyword.
704 In an item, this will be the position after the bullet.
705 When the cursor is already at that position, another `C-a' will bring
706 it to the beginning of the line.
708 `C-e' will jump to the end of the headline, ignoring the presence of tags
709 in the headline. A second `C-e' will then jump to the true end of the
710 line, after any tags.
712 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
713 going to the true line boundary first. Only a directly following, identical
714 keypress will bring the cursor to the special positions.
716 This may also be a cons cell where the behavior for `C-a' and `C-e' is
717 set separately."
718 :group 'org-edit-structure
719 :type '(choice
720 (const :tag "off" nil)
721 (const :tag "after stars/bullet and before tags first" t)
722 (const :tag "true line boundary first" reversed)
723 (cons :tag "Set C-a and C-e separately"
724 (choice :tag "Special C-a"
725 (const :tag "off" nil)
726 (const :tag "after stars/bullet first" t)
727 (const :tag "before stars/bullet first" reversed))
728 (choice :tag "Special C-e"
729 (const :tag "off" nil)
730 (const :tag "before tags first" t)
731 (const :tag "after tags first" reversed)))))
732 (if (fboundp 'defvaralias)
733 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
735 (defcustom org-special-ctrl-k nil
736 "Non-nil means `C-k' will behave specially in headlines.
737 When nil, `C-k' will call the default `kill-line' command.
738 When t, the following will happen while the cursor is in the headline:
740 - When the cursor is at the beginning of a headline, kill the entire
741 line and possible the folded subtree below the line.
742 - When in the middle of the headline text, kill the headline up to the tags.
743 - When after the headline text, kill the tags."
744 :group 'org-edit-structure
745 :type 'boolean)
747 (defcustom org-yank-folded-subtrees t
748 "Non-nil means, when yanking subtrees, fold them.
749 If the kill is a single subtree, or a sequence of subtrees, i.e. if
750 it starts with a heading and all other headings in it are either children
751 or siblings, then fold all the subtrees. However, do this only if no
752 text after the yank would be swallowed into a folded tree by this action."
753 :group 'org-edit-structure
754 :type 'boolean)
756 (defcustom org-yank-adjusted-subtrees nil
757 "Non-nil means, when yanking subtrees, adjust the level.
758 With this setting, `org-paste-subtree' is used to insert the subtree, see
759 this function for details."
760 :group 'org-edit-structure
761 :type 'boolean)
763 (defcustom org-M-RET-may-split-line '((default . t))
764 "Non-nil means, M-RET will split the line at the cursor position.
765 When nil, it will go to the end of the line before making a
766 new line.
767 You may also set this option in a different way for different
768 contexts. Valid contexts are:
770 headline when creating a new headline
771 item when creating a new item
772 table in a table field
773 default the value to be used for all contexts not explicitly
774 customized"
775 :group 'org-structure
776 :group 'org-table
777 :type '(choice
778 (const :tag "Always" t)
779 (const :tag "Never" nil)
780 (repeat :greedy t :tag "Individual contexts"
781 (cons
782 (choice :tag "Context"
783 (const headline)
784 (const item)
785 (const table)
786 (const default))
787 (boolean)))))
790 (defcustom org-insert-heading-respect-content nil
791 "Non-nil means, insert new headings after the current subtree.
792 When nil, the new heading is created directly after the current line.
793 The commands \\[org-insert-heading-respect-content] and
794 \\[org-insert-todo-heading-respect-content] turn this variable on
795 for the duration of the command."
796 :group 'org-structure
797 :type 'boolean)
799 (defcustom org-blank-before-new-entry '((heading . auto)
800 (plain-list-item . auto))
801 "Should `org-insert-heading' leave a blank line before new heading/item?
802 The value is an alist, with `heading' and `plain-list-item' as car,
803 and a boolean flag as cdr. For plain lists, if the variable
804 `org-empty-line-terminates-plain-lists' is set, the setting here
805 is ignored and no empty line is inserted, to keep the list in tact."
806 :group 'org-edit-structure
807 :type '(list
808 (cons (const heading)
809 (choice (const :tag "Never" nil)
810 (const :tag "Always" t)
811 (const :tag "Auto" auto)))
812 (cons (const plain-list-item)
813 (choice (const :tag "Never" nil)
814 (const :tag "Always" t)
815 (const :tag "Auto" auto)))))
817 (defcustom org-insert-heading-hook nil
818 "Hook being run after inserting a new heading."
819 :group 'org-edit-structure
820 :type 'hook)
822 (defcustom org-enable-fixed-width-editor t
823 "Non-nil means, lines starting with \":\" are treated as fixed-width.
824 This currently only means, they are never auto-wrapped.
825 When nil, such lines will be treated like ordinary lines.
826 See also the QUOTE keyword."
827 :group 'org-edit-structure
828 :type 'boolean)
831 (defcustom org-goto-auto-isearch t
832 "Non-nil means, typing characters in org-goto starts incremental search."
833 :group 'org-edit-structure
834 :type 'boolean)
836 (defgroup org-sparse-trees nil
837 "Options concerning sparse trees in Org-mode."
838 :tag "Org Sparse Trees"
839 :group 'org-structure)
841 (defcustom org-highlight-sparse-tree-matches t
842 "Non-nil means, highlight all matches that define a sparse tree.
843 The highlights will automatically disappear the next time the buffer is
844 changed by an edit command."
845 :group 'org-sparse-trees
846 :type 'boolean)
848 (defcustom org-remove-highlights-with-change t
849 "Non-nil means, any change to the buffer will remove temporary highlights.
850 Such highlights are created by `org-occur' and `org-clock-display'.
851 When nil, `C-c C-c needs to be used to get rid of the highlights.
852 The highlights created by `org-preview-latex-fragment' always need
853 `C-c C-c' to be removed."
854 :group 'org-sparse-trees
855 :group 'org-time
856 :type 'boolean)
859 (defcustom org-occur-hook '(org-first-headline-recenter)
860 "Hook that is run after `org-occur' has constructed a sparse tree.
861 This can be used to recenter the window to show as much of the structure
862 as possible."
863 :group 'org-sparse-trees
864 :type 'hook)
866 (defgroup org-imenu-and-speedbar nil
867 "Options concerning imenu and speedbar in Org-mode."
868 :tag "Org Imenu and Speedbar"
869 :group 'org-structure)
871 (defcustom org-imenu-depth 2
872 "The maximum level for Imenu access to Org-mode headlines.
873 This also applied for speedbar access."
874 :group 'org-imenu-and-speedbar
875 :type 'integer)
877 (defgroup org-table nil
878 "Options concerning tables in Org-mode."
879 :tag "Org Table"
880 :group 'org)
882 (defcustom org-enable-table-editor 'optimized
883 "Non-nil means, lines starting with \"|\" are handled by the table editor.
884 When nil, such lines will be treated like ordinary lines.
886 When equal to the symbol `optimized', the table editor will be optimized to
887 do the following:
888 - Automatic overwrite mode in front of whitespace in table fields.
889 This makes the structure of the table stay in tact as long as the edited
890 field does not exceed the column width.
891 - Minimize the number of realigns. Normally, the table is aligned each time
892 TAB or RET are pressed to move to another field. With optimization this
893 happens only if changes to a field might have changed the column width.
894 Optimization requires replacing the functions `self-insert-command',
895 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
896 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
897 very good at guessing when a re-align will be necessary, but you can always
898 force one with \\[org-ctrl-c-ctrl-c].
900 If you would like to use the optimized version in Org-mode, but the
901 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
903 This variable can be used to turn on and off the table editor during a session,
904 but in order to toggle optimization, a restart is required.
906 See also the variable `org-table-auto-blank-field'."
907 :group 'org-table
908 :type '(choice
909 (const :tag "off" nil)
910 (const :tag "on" t)
911 (const :tag "on, optimized" optimized)))
913 (defcustom org-self-insert-cluster-for-undo t
914 "Non-nil means cluster self-insert commands for undo when possible.
915 If this is set, then, like in the Emacs command loop, 20 consequtive
916 characters will be undone together.
917 This is configurable, because there is some impact on typing performance."
918 :group 'org-table
919 :type 'boolean)
921 (defcustom org-table-tab-recognizes-table.el t
922 "Non-nil means, TAB will automatically notice a table.el table.
923 When it sees such a table, it moves point into it and - if necessary -
924 calls `table-recognize-table'."
925 :group 'org-table-editing
926 :type 'boolean)
928 (defgroup org-link nil
929 "Options concerning links in Org-mode."
930 :tag "Org Link"
931 :group 'org)
933 (defvar org-link-abbrev-alist-local nil
934 "Buffer-local version of `org-link-abbrev-alist', which see.
935 The value of this is taken from the #+LINK lines.")
936 (make-variable-buffer-local 'org-link-abbrev-alist-local)
938 (defcustom org-link-abbrev-alist nil
939 "Alist of link abbreviations.
940 The car of each element is a string, to be replaced at the start of a link.
941 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
942 links in Org-mode buffers can have an optional tag after a double colon, e.g.
944 [[linkkey:tag][description]]
946 The 'linkkey' must be a word word, starting with a letter, followed
947 by letters, numbers, '-' or '_'.
949 If REPLACE is a string, the tag will simply be appended to create the link.
950 If the string contains \"%s\", the tag will be inserted there. Alternatively,
951 the placeholder \"%h\" will cause a url-encoded version of the tag to
952 be inserted at that point (see the function `url-hexify-string').
954 REPLACE may also be a function that will be called with the tag as the
955 only argument to create the link, which should be returned as a string.
957 See the manual for examples."
958 :group 'org-link
959 :type '(repeat
960 (cons
961 (string :tag "Protocol")
962 (choice
963 (string :tag "Format")
964 (function)))))
966 (defcustom org-descriptive-links t
967 "Non-nil means, hide link part and only show description of bracket links.
968 Bracket links are like [[link][description]]. This variable sets the initial
969 state in new org-mode buffers. The setting can then be toggled on a
970 per-buffer basis from the Org->Hyperlinks menu."
971 :group 'org-link
972 :type 'boolean)
974 (defcustom org-link-file-path-type 'adaptive
975 "How the path name in file links should be stored.
976 Valid values are:
978 relative Relative to the current directory, i.e. the directory of the file
979 into which the link is being inserted.
980 absolute Absolute path, if possible with ~ for home directory.
981 noabbrev Absolute path, no abbreviation of home directory.
982 adaptive Use relative path for files in the current directory and sub-
983 directories of it. For other files, use an absolute path."
984 :group 'org-link
985 :type '(choice
986 (const relative)
987 (const absolute)
988 (const noabbrev)
989 (const adaptive)))
991 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
992 "Types of links that should be activated in Org-mode files.
993 This is a list of symbols, each leading to the activation of a certain link
994 type. In principle, it does not hurt to turn on most link types - there may
995 be a small gain when turning off unused link types. The types are:
997 bracket The recommended [[link][description]] or [[link]] links with hiding.
998 angular Links in angular brackets that may contain whitespace like
999 <bbdb:Carsten Dominik>.
1000 plain Plain links in normal text, no whitespace, like http://google.com.
1001 radio Text that is matched by a radio target, see manual for details.
1002 tag Tag settings in a headline (link to tag search).
1003 date Time stamps (link to calendar).
1004 footnote Footnote labels.
1006 Changing this variable requires a restart of Emacs to become effective."
1007 :group 'org-link
1008 :type '(set :greedy t
1009 (const :tag "Double bracket links (new style)" bracket)
1010 (const :tag "Angular bracket links (old style)" angular)
1011 (const :tag "Plain text links" plain)
1012 (const :tag "Radio target matches" radio)
1013 (const :tag "Tags" tag)
1014 (const :tag "Timestamps" date)
1015 (const :tag "Footnotes" footnote)))
1017 (defcustom org-make-link-description-function nil
1018 "Function to use to generate link descriptions from links. If
1019 nil the link location will be used. This function must take two
1020 parameters; the first is the link and the second the description
1021 org-insert-link has generated, and should return the description
1022 to use."
1023 :group 'org-link
1024 :type 'function)
1026 (defgroup org-link-store nil
1027 "Options concerning storing links in Org-mode."
1028 :tag "Org Store Link"
1029 :group 'org-link)
1031 (defcustom org-email-link-description-format "Email %c: %.30s"
1032 "Format of the description part of a link to an email or usenet message.
1033 The following %-escapes will be replaced by corresponding information:
1035 %F full \"From\" field
1036 %f name, taken from \"From\" field, address if no name
1037 %T full \"To\" field
1038 %t first name in \"To\" field, address if no name
1039 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1040 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1041 %s subject
1042 %m message-id.
1044 You may use normal field width specification between the % and the letter.
1045 This is for example useful to limit the length of the subject.
1047 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1048 :group 'org-link-store
1049 :type 'string)
1051 (defcustom org-from-is-user-regexp
1052 (let (r1 r2)
1053 (when (and user-mail-address (not (string= user-mail-address "")))
1054 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1055 (when (and user-full-name (not (string= user-full-name "")))
1056 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1057 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1058 "Regexp matched against the \"From:\" header of an email or usenet message.
1059 It should match if the message is from the user him/herself."
1060 :group 'org-link-store
1061 :type 'regexp)
1063 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1064 "Non-nil means, storing a link to an Org file will use entry IDs.
1066 Note that before this variable is even considered, org-id must be loaded,
1067 so please customize `org-modules' and turn it on.
1069 The variable can have the following values:
1071 t Create an ID if needed to make a link to the current entry.
1073 create-if-interactive
1074 If `org-store-link' is called directly (interactively, as a user
1075 command), do create an ID to support the link. But when doing the
1076 job for remember, only use the ID if it already exists. The
1077 purpose of this setting is to avoid proliferation of unwanted
1078 IDs, just because you happen to be in an Org file when you
1079 call `org-remember' that automatically and preemptively
1080 creates a link. If you do want to get an ID link in a remember
1081 template to an entry not having an ID, create it first by
1082 explicitly creating a link to it, using `C-c C-l' first.
1084 create-if-interactive-and-no-custom-id
1085 Like create-if-interactive, but do not create an ID if there is
1086 a CUSTOM_ID property defined in the entry. This is the default.
1088 use-existing
1089 Use existing ID, do not create one.
1091 nil Never use an ID to make a link, instead link using a text search for
1092 the headline text."
1093 :group 'org-link-store
1094 :type '(choice
1095 (const :tag "Create ID to make link" t)
1096 (const :tag "Create if storing link interactively"
1097 create-if-interactive)
1098 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1099 create-if-interactive-and-no-custom-id)
1100 (const :tag "Only use existing" use-existing)
1101 (const :tag "Do not use ID to create link" nil)))
1103 (defcustom org-context-in-file-links t
1104 "Non-nil means, file links from `org-store-link' contain context.
1105 A search string will be added to the file name with :: as separator and
1106 used to find the context when the link is activated by the command
1107 `org-open-at-point'.
1108 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1109 negates this setting for the duration of the command."
1110 :group 'org-link-store
1111 :type 'boolean)
1113 (defcustom org-keep-stored-link-after-insertion nil
1114 "Non-nil means, keep link in list for entire session.
1116 The command `org-store-link' adds a link pointing to the current
1117 location to an internal list. These links accumulate during a session.
1118 The command `org-insert-link' can be used to insert links into any
1119 Org-mode file (offering completion for all stored links). When this
1120 option is nil, every link which has been inserted once using \\[org-insert-link]
1121 will be removed from the list, to make completing the unused links
1122 more efficient."
1123 :group 'org-link-store
1124 :type 'boolean)
1126 (defgroup org-link-follow nil
1127 "Options concerning following links in Org-mode."
1128 :tag "Org Follow Link"
1129 :group 'org-link)
1131 (defcustom org-link-translation-function nil
1132 "Function to translate links with different syntax to Org syntax.
1133 This can be used to translate links created for example by the Planner
1134 or emacs-wiki packages to Org syntax.
1135 The function must accept two parameters, a TYPE containing the link
1136 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1137 which is everything after the link protocol. It should return a cons
1138 with possibly modified values of type and path.
1139 Org contains a function for this, so if you set this variable to
1140 `org-translate-link-from-planner', you should be able follow many
1141 links created by planner."
1142 :group 'org-link-follow
1143 :type 'function)
1145 (defcustom org-follow-link-hook nil
1146 "Hook that is run after a link has been followed."
1147 :group 'org-link-follow
1148 :type 'hook)
1150 (defcustom org-tab-follows-link nil
1151 "Non-nil means, on links TAB will follow the link.
1152 Needs to be set before org.el is loaded.
1153 This really should not be used, it does not make sense, and the
1154 implementation is bad."
1155 :group 'org-link-follow
1156 :type 'boolean)
1158 (defcustom org-return-follows-link nil
1159 "Non-nil means, on links RET will follow the link.
1160 Needs to be set before org.el is loaded."
1161 :group 'org-link-follow
1162 :type 'boolean)
1164 (defcustom org-mouse-1-follows-link
1165 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1166 "Non-nil means, mouse-1 on a link will follow the link.
1167 A longer mouse click will still set point. Does not work on XEmacs.
1168 Needs to be set before org.el is loaded."
1169 :group 'org-link-follow
1170 :type 'boolean)
1172 (defcustom org-mark-ring-length 4
1173 "Number of different positions to be recorded in the ring
1174 Changing this requires a restart of Emacs to work correctly."
1175 :group 'org-link-follow
1176 :type 'integer)
1178 (defcustom org-link-frame-setup
1179 '((vm . vm-visit-folder-other-frame)
1180 (gnus . gnus-other-frame)
1181 (file . find-file-other-window))
1182 "Setup the frame configuration for following links.
1183 When following a link with Emacs, it may often be useful to display
1184 this link in another window or frame. This variable can be used to
1185 set this up for the different types of links.
1186 For VM, use any of
1187 `vm-visit-folder'
1188 `vm-visit-folder-other-frame'
1189 For Gnus, use any of
1190 `gnus'
1191 `gnus-other-frame'
1192 `org-gnus-no-new-news'
1193 For FILE, use any of
1194 `find-file'
1195 `find-file-other-window'
1196 `find-file-other-frame'
1197 For the calendar, use the variable `calendar-setup'.
1198 For BBDB, it is currently only possible to display the matches in
1199 another window."
1200 :group 'org-link-follow
1201 :type '(list
1202 (cons (const vm)
1203 (choice
1204 (const vm-visit-folder)
1205 (const vm-visit-folder-other-window)
1206 (const vm-visit-folder-other-frame)))
1207 (cons (const gnus)
1208 (choice
1209 (const gnus)
1210 (const gnus-other-frame)
1211 (const org-gnus-no-new-news)))
1212 (cons (const file)
1213 (choice
1214 (const find-file)
1215 (const find-file-other-window)
1216 (const find-file-other-frame)))))
1218 (defcustom org-display-internal-link-with-indirect-buffer nil
1219 "Non-nil means, use indirect buffer to display infile links.
1220 Activating internal links (from one location in a file to another location
1221 in the same file) normally just jumps to the location. When the link is
1222 activated with a C-u prefix (or with mouse-3), the link is displayed in
1223 another window. When this option is set, the other window actually displays
1224 an indirect buffer clone of the current buffer, to avoid any visibility
1225 changes to the current buffer."
1226 :group 'org-link-follow
1227 :type 'boolean)
1229 (defcustom org-open-non-existing-files nil
1230 "Non-nil means, `org-open-file' will open non-existing files.
1231 When nil, an error will be generated.
1232 This variable applies only to external applications because they
1233 might choke on non-existing files. If the link is to a file that
1234 will be openend in Emacs, the variable is ignored."
1235 :group 'org-link-follow
1236 :type 'boolean)
1238 (defcustom org-open-directory-means-index-dot-org nil
1239 "Non-nil means, a link to a directory really means to index.org.
1240 When nil, following a directory link will run dired or open a finder/explorer
1241 window on that directory."
1242 :group 'org-link-follow
1243 :type 'boolean)
1245 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1246 "Function and arguments to call for following mailto links.
1247 This is a list with the first element being a lisp function, and the
1248 remaining elements being arguments to the function. In string arguments,
1249 %a will be replaced by the address, and %s will be replaced by the subject
1250 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1251 :group 'org-link-follow
1252 :type '(choice
1253 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1254 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1255 (const :tag "message-mail" (message-mail "%a" "%s"))
1256 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1258 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1259 "Non-nil means, ask for confirmation before executing shell links.
1260 Shell links can be dangerous: just think about a link
1262 [[shell:rm -rf ~/*][Google Search]]
1264 This link would show up in your Org-mode document as \"Google Search\",
1265 but really it would remove your entire home directory.
1266 Therefore we advise against setting this variable to nil.
1267 Just change it to `y-or-n-p' if you want to confirm with a
1268 single keystroke rather than having to type \"yes\"."
1269 :group 'org-link-follow
1270 :type '(choice
1271 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1272 (const :tag "with y-or-n (faster)" y-or-n-p)
1273 (const :tag "no confirmation (dangerous)" nil)))
1275 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1276 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1277 Elisp links can be dangerous: just think about a link
1279 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1281 This link would show up in your Org-mode document as \"Google Search\",
1282 but really it would remove your entire home directory.
1283 Therefore we advise against setting this variable to nil.
1284 Just change it to `y-or-n-p' if you want to confirm with a
1285 single keystroke rather than having to type \"yes\"."
1286 :group 'org-link-follow
1287 :type '(choice
1288 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1289 (const :tag "with y-or-n (faster)" y-or-n-p)
1290 (const :tag "no confirmation (dangerous)" nil)))
1292 (defconst org-file-apps-defaults-gnu
1293 '((remote . emacs)
1294 (system . mailcap)
1295 (t . mailcap))
1296 "Default file applications on a UNIX or GNU/Linux system.
1297 See `org-file-apps'.")
1299 (defconst org-file-apps-defaults-macosx
1300 '((remote . emacs)
1301 (t . "open %s")
1302 (system . "open %s")
1303 ("ps.gz" . "gv %s")
1304 ("eps.gz" . "gv %s")
1305 ("dvi" . "xdvi %s")
1306 ("fig" . "xfig %s"))
1307 "Default file applications on a MacOS X system.
1308 The system \"open\" is known as a default, but we use X11 applications
1309 for some files for which the OS does not have a good default.
1310 See `org-file-apps'.")
1312 (defconst org-file-apps-defaults-windowsnt
1313 (list
1314 '(remote . emacs)
1315 (cons t
1316 (list (if (featurep 'xemacs)
1317 'mswindows-shell-execute
1318 'w32-shell-execute)
1319 "open" 'file))
1320 (cons 'system
1321 (list (if (featurep 'xemacs)
1322 'mswindows-shell-execute
1323 'w32-shell-execute)
1324 "open" 'file)))
1325 "Default file applications on a Windows NT system.
1326 The system \"open\" is used for most files.
1327 See `org-file-apps'.")
1329 (defcustom org-file-apps
1331 (auto-mode . emacs)
1332 ("\\.x?html?\\'" . default)
1333 ("\\.pdf\\'" . default)
1335 "External applications for opening `file:path' items in a document.
1336 Org-mode uses system defaults for different file types, but
1337 you can use this variable to set the application for a given file
1338 extension. The entries in this list are cons cells where the car identifies
1339 files and the cdr the corresponding command. Possible values for the
1340 file identifier are
1341 \"regex\" Regular expression matched against the file name. For backward
1342 compatibility, this can also be a string with only alphanumeric
1343 characters, which is then interpreted as an extension.
1344 `directory' Matches a directory
1345 `remote' Matches a remote file, accessible through tramp or efs.
1346 Remote files most likely should be visited through Emacs
1347 because external applications cannot handle such paths.
1348 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1349 so all files Emacs knows how to handle. Using this with
1350 command `emacs' will open most files in Emacs. Beware that this
1351 will also open html files inside Emacs, unless you add
1352 (\"html\" . default) to the list as well.
1353 t Default for files not matched by any of the other options.
1354 `system' The system command to open files, like `open' on Windows
1355 and Mac OS X, and mailcap under GNU/Linux. This is the command
1356 that will be selected if you call `C-c C-o' with a double
1357 `C-u C-u' prefix.
1359 Possible values for the command are:
1360 `emacs' The file will be visited by the current Emacs process.
1361 `default' Use the default application for this file type, which is the
1362 association for t in the list, most likely in the system-specific
1363 part.
1364 This can be used to overrule an unwanted setting in the
1365 system-specific variable.
1366 `system' Use the system command for opening files, like \"open\".
1367 This command is specified by the entry whose car is `system'.
1368 Most likely, the system-specific version of this variable
1369 does define this command, but you can overrule/replace it
1370 here.
1371 string A command to be executed by a shell; %s will be replaced
1372 by the path to the file.
1373 sexp A Lisp form which will be evaluated. The file path will
1374 be available in the Lisp variable `file'.
1375 For more examples, see the system specific constants
1376 `org-file-apps-defaults-macosx'
1377 `org-file-apps-defaults-windowsnt'
1378 `org-file-apps-defaults-gnu'."
1379 :group 'org-link-follow
1380 :type '(repeat
1381 (cons (choice :value ""
1382 (string :tag "Extension")
1383 (const :tag "System command to open files" system)
1384 (const :tag "Default for unrecognized files" t)
1385 (const :tag "Remote file" remote)
1386 (const :tag "Links to a directory" directory)
1387 (const :tag "Any files that have Emacs modes"
1388 auto-mode))
1389 (choice :value ""
1390 (const :tag "Visit with Emacs" emacs)
1391 (const :tag "Use default" default)
1392 (const :tag "Use the system command" system)
1393 (string :tag "Command")
1394 (sexp :tag "Lisp form")))))
1396 (defgroup org-refile nil
1397 "Options concerning refiling entries in Org-mode."
1398 :tag "Org Refile"
1399 :group 'org)
1401 (defcustom org-directory "~/org"
1402 "Directory with org files.
1403 This is just a default location to look for Org files. There is no need
1404 at all to put your files into this directory. It is only used in the
1405 following situations:
1407 1. When a remember template specifies a target file that is not an
1408 absolute path. The path will then be interpreted relative to
1409 `org-directory'
1410 2. When a remember note is filed away in an interactive way (when exiting the
1411 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1412 with `org-directory' as the default path."
1413 :group 'org-refile
1414 :group 'org-remember
1415 :type 'directory)
1417 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1418 "Default target for storing notes.
1419 Used by the hooks for remember.el. This can be a string, or nil to mean
1420 the value of `remember-data-file'.
1421 You can set this on a per-template basis with the variable
1422 `org-remember-templates'."
1423 :group 'org-refile
1424 :group 'org-remember
1425 :type '(choice
1426 (const :tag "Default from remember-data-file" nil)
1427 file))
1429 (defcustom org-goto-interface 'outline
1430 "The default interface to be used for `org-goto'.
1431 Allowed values are:
1432 outline The interface shows an outline of the relevant file
1433 and the correct heading is found by moving through
1434 the outline or by searching with incremental search.
1435 outline-path-completion Headlines in the current buffer are offered via
1436 completion. This is the interface also used by
1437 the refile command."
1438 :group 'org-refile
1439 :type '(choice
1440 (const :tag "Outline" outline)
1441 (const :tag "Outline-path-completion" outline-path-completion)))
1443 (defcustom org-goto-max-level 5
1444 "Maximum level to be considered when running org-goto with refile interface."
1445 :group 'org-refile
1446 :type 'integer)
1448 (defcustom org-reverse-note-order nil
1449 "Non-nil means, store new notes at the beginning of a file or entry.
1450 When nil, new notes will be filed to the end of a file or entry.
1451 This can also be a list with cons cells of regular expressions that
1452 are matched against file names, and values."
1453 :group 'org-remember
1454 :group 'org-refile
1455 :type '(choice
1456 (const :tag "Reverse always" t)
1457 (const :tag "Reverse never" nil)
1458 (repeat :tag "By file name regexp"
1459 (cons regexp boolean))))
1461 (defcustom org-refile-targets nil
1462 "Targets for refiling entries with \\[org-refile].
1463 This is list of cons cells. Each cell contains:
1464 - a specification of the files to be considered, either a list of files,
1465 or a symbol whose function or variable value will be used to retrieve
1466 a file name or a list of file names. If you use `org-agenda-files' for
1467 that, all agenda files will be scanned for targets. Nil means, consider
1468 headings in the current buffer.
1469 - A specification of how to find candidate refile targets. This may be
1470 any of:
1471 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1472 This tag has to be present in all target headlines, inheritance will
1473 not be considered.
1474 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1475 todo keyword.
1476 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1477 headlines that are refiling targets.
1478 - a cons cell (:level . N). Any headline of level N is considered a target.
1479 Note that, when `org-odd-levels-only' is set, level corresponds to
1480 order in hierarchy, not to the number of stars.
1481 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1482 Note that, when `org-odd-levels-only' is set, level corresponds to
1483 order in hierarchy, not to the number of stars.
1485 You can set the variable `org-refile-target-verify-function' to a function
1486 to verify each headline found by the simple critery above.
1488 When this variable is nil, all top-level headlines in the current buffer
1489 are used, equivalent to the value `((nil . (:level . 1))'."
1490 :group 'org-refile
1491 :type '(repeat
1492 (cons
1493 (choice :value org-agenda-files
1494 (const :tag "All agenda files" org-agenda-files)
1495 (const :tag "Current buffer" nil)
1496 (function) (variable) (file))
1497 (choice :tag "Identify target headline by"
1498 (cons :tag "Specific tag" (const :value :tag) (string))
1499 (cons :tag "TODO keyword" (const :value :todo) (string))
1500 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1501 (cons :tag "Level number" (const :value :level) (integer))
1502 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1504 (defcustom org-refile-target-verify-function nil
1505 "Function to verify if the headline at point should be a refile target.
1506 The function will be called without arguments, with point at the
1507 beginning of the headline. It should return t and leave point
1508 where it is if the headline is a valid target for refiling.
1510 If the target should not be selected, the function must return nil.
1511 In addition to this, it may move point to a place from where the search
1512 should be continued. For example, the function may decide that the entire
1513 subtree of the current entry should be excluded and move point to the end
1514 of the subtree."
1515 :group 'org-refile
1516 :type 'function)
1518 (defcustom org-refile-use-outline-path nil
1519 "Non-nil means, provide refile targets as paths.
1520 So a level 3 headline will be available as level1/level2/level3.
1522 When the value is `file', also include the file name (without directory)
1523 into the path. In this case, you can also stop the completion after
1524 the file name, to get entries inserted as top level in the file.
1526 When `full-file-path', include the full file path."
1527 :group 'org-refile
1528 :type '(choice
1529 (const :tag "Not" nil)
1530 (const :tag "Yes" t)
1531 (const :tag "Start with file name" file)
1532 (const :tag "Start with full file path" full-file-path)))
1534 (defcustom org-outline-path-complete-in-steps t
1535 "Non-nil means, complete the outline path in hierarchical steps.
1536 When Org-mode uses the refile interface to select an outline path
1537 \(see variable `org-refile-use-outline-path'), the completion of
1538 the path can be done is a single go, or if can be done in steps down
1539 the headline hierarchy. Going in steps is probably the best if you
1540 do not use a special completion package like `ido' or `icicles'.
1541 However, when using these packages, going in one step can be very
1542 fast, while still showing the whole path to the entry."
1543 :group 'org-refile
1544 :type 'boolean)
1546 (defcustom org-refile-allow-creating-parent-nodes nil
1547 "Non-nil means, allow to create new nodes as refile targets.
1548 New nodes are then created by adding \"/new node name\" to the completion
1549 of an existing node. When the value of this variable is `confirm',
1550 new node creation must be confirmed by the user (recommended)
1551 When nil, the completion must match an existing entry.
1553 Note that, if the new heading is not seen by the criteria
1554 listed in `org-refile-targets', multiple instances of the same
1555 heading would be created by trying again to file under the new
1556 heading."
1557 :group 'org-refile
1558 :type '(choice
1559 (const :tag "Never" nil)
1560 (const :tag "Always" t)
1561 (const :tag "Prompt for confirmation" confirm)))
1563 (defgroup org-todo nil
1564 "Options concerning TODO items in Org-mode."
1565 :tag "Org TODO"
1566 :group 'org)
1568 (defgroup org-progress nil
1569 "Options concerning Progress logging in Org-mode."
1570 :tag "Org Progress"
1571 :group 'org-time)
1573 (defvar org-todo-interpretation-widgets
1575 (:tag "Sequence (cycling hits every state)" sequence)
1576 (:tag "Type (cycling directly to DONE)" type))
1577 "The available interpretation symbols for customizing
1578 `org-todo-keywords'.
1579 Interested libraries should add to this list.")
1581 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1582 "List of TODO entry keyword sequences and their interpretation.
1583 \\<org-mode-map>This is a list of sequences.
1585 Each sequence starts with a symbol, either `sequence' or `type',
1586 indicating if the keywords should be interpreted as a sequence of
1587 action steps, or as different types of TODO items. The first
1588 keywords are states requiring action - these states will select a headline
1589 for inclusion into the global TODO list Org-mode produces. If one of
1590 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1591 signify that no further action is necessary. If \"|\" is not found,
1592 the last keyword is treated as the only DONE state of the sequence.
1594 The command \\[org-todo] cycles an entry through these states, and one
1595 additional state where no keyword is present. For details about this
1596 cycling, see the manual.
1598 TODO keywords and interpretation can also be set on a per-file basis with
1599 the special #+SEQ_TODO and #+TYP_TODO lines.
1601 Each keyword can optionally specify a character for fast state selection
1602 \(in combination with the variable `org-use-fast-todo-selection')
1603 and specifiers for state change logging, using the same syntax
1604 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1605 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1606 indicates to record a time stamp each time this state is selected.
1608 Each keyword may also specify if a timestamp or a note should be
1609 recorded when entering or leaving the state, by adding additional
1610 characters in the parenthesis after the keyword. This looks like this:
1611 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1612 record only the time of the state change. With X and Y being either
1613 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1614 Y when leaving the state if and only if the *target* state does not
1615 define X. You may omit any of the fast-selection key or X or /Y,
1616 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1618 For backward compatibility, this variable may also be just a list
1619 of keywords - in this case the interpretation (sequence or type) will be
1620 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1621 :group 'org-todo
1622 :group 'org-keywords
1623 :type '(choice
1624 (repeat :tag "Old syntax, just keywords"
1625 (string :tag "Keyword"))
1626 (repeat :tag "New syntax"
1627 (cons
1628 (choice
1629 :tag "Interpretation"
1630 ;;Quick and dirty way to see
1631 ;;`org-todo-interpretations'. This takes the
1632 ;;place of item arguments
1633 :convert-widget
1634 (lambda (widget)
1635 (widget-put widget
1636 :args (mapcar
1637 #'(lambda (x)
1638 (widget-convert
1639 (cons 'const x)))
1640 org-todo-interpretation-widgets))
1641 widget))
1642 (repeat
1643 (string :tag "Keyword"))))))
1645 (defvar org-todo-keywords-1 nil
1646 "All TODO and DONE keywords active in a buffer.")
1647 (make-variable-buffer-local 'org-todo-keywords-1)
1648 (defvar org-todo-keywords-for-agenda nil)
1649 (defvar org-done-keywords-for-agenda nil)
1650 (defvar org-todo-keyword-alist-for-agenda nil)
1651 (defvar org-tag-alist-for-agenda nil)
1652 (defvar org-agenda-contributing-files nil)
1653 (defvar org-not-done-keywords nil)
1654 (make-variable-buffer-local 'org-not-done-keywords)
1655 (defvar org-done-keywords nil)
1656 (make-variable-buffer-local 'org-done-keywords)
1657 (defvar org-todo-heads nil)
1658 (make-variable-buffer-local 'org-todo-heads)
1659 (defvar org-todo-sets nil)
1660 (make-variable-buffer-local 'org-todo-sets)
1661 (defvar org-todo-log-states nil)
1662 (make-variable-buffer-local 'org-todo-log-states)
1663 (defvar org-todo-kwd-alist nil)
1664 (make-variable-buffer-local 'org-todo-kwd-alist)
1665 (defvar org-todo-key-alist nil)
1666 (make-variable-buffer-local 'org-todo-key-alist)
1667 (defvar org-todo-key-trigger nil)
1668 (make-variable-buffer-local 'org-todo-key-trigger)
1670 (defcustom org-todo-interpretation 'sequence
1671 "Controls how TODO keywords are interpreted.
1672 This variable is in principle obsolete and is only used for
1673 backward compatibility, if the interpretation of todo keywords is
1674 not given already in `org-todo-keywords'. See that variable for
1675 more information."
1676 :group 'org-todo
1677 :group 'org-keywords
1678 :type '(choice (const sequence)
1679 (const type)))
1681 (defcustom org-use-fast-todo-selection t
1682 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1683 This variable describes if and under what circumstances the cycling
1684 mechanism for TODO keywords will be replaced by a single-key, direct
1685 selection scheme.
1687 When nil, fast selection is never used.
1689 When the symbol `prefix', it will be used when `org-todo' is called with
1690 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1691 in an agenda buffer.
1693 When t, fast selection is used by default. In this case, the prefix
1694 argument forces cycling instead.
1696 In all cases, the special interface is only used if access keys have actually
1697 been assigned by the user, i.e. if keywords in the configuration are followed
1698 by a letter in parenthesis, like TODO(t)."
1699 :group 'org-todo
1700 :type '(choice
1701 (const :tag "Never" nil)
1702 (const :tag "By default" t)
1703 (const :tag "Only with C-u C-c C-t" prefix)))
1705 (defcustom org-provide-todo-statistics t
1706 "Non-nil means, update todo statistics after insert and toggle.
1707 When this is set, todo statistics is updated in the parent of the current
1708 entry each time a todo state is changed."
1709 :group 'org-todo
1710 :type 'boolean)
1712 (defcustom org-hierarchical-todo-statistics t
1713 "Non-nil means, TODO statistics covers just direct children.
1714 When nil, all entries in the subtree are considered.
1715 This has only an effect if `org-provide-todo-statistics' is set."
1716 :group 'org-todo
1717 :type 'boolean)
1719 (defcustom org-after-todo-state-change-hook nil
1720 "Hook which is run after the state of a TODO item was changed.
1721 The new state (a string with a TODO keyword, or nil) is available in the
1722 Lisp variable `state'."
1723 :group 'org-todo
1724 :type 'hook)
1726 (defvar org-blocker-hook nil
1727 "Hook for functions that are allowed to block a state change.
1729 Each function gets as its single argument a property list, see
1730 `org-trigger-hook' for more information about this list.
1732 If any of the functions in this hook returns nil, the state change
1733 is blocked.")
1735 (defvar org-trigger-hook nil
1736 "Hook for functions that are triggered by a state change.
1738 Each function gets as its single argument a property list with at least
1739 the following elements:
1741 (:type type-of-change :position pos-at-entry-start
1742 :from old-state :to new-state)
1744 Depending on the type, more properties may be present.
1746 This mechanism is currently implemented for:
1748 TODO state changes
1749 ------------------
1750 :type todo-state-change
1751 :from previous state (keyword as a string), or nil, or a symbol
1752 'todo' or 'done', to indicate the general type of state.
1753 :to new state, like in :from")
1755 (defcustom org-enforce-todo-dependencies nil
1756 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1757 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1758 be blocked if any prior sibling is not yet done.
1759 Finally, if the parent is blocked because of ordered siblings of its own,
1760 the child will also be blocked.
1761 This variable needs to be set before org.el is loaded, and you need to
1762 restart Emacs after a change to make the change effective. The only way
1763 to change is while Emacs is running is through the customize interface."
1764 :set (lambda (var val)
1765 (set var val)
1766 (if val
1767 (add-hook 'org-blocker-hook
1768 'org-block-todo-from-children-or-siblings-or-parent)
1769 (remove-hook 'org-blocker-hook
1770 'org-block-todo-from-children-or-siblings-or-parent)))
1771 :group 'org-todo
1772 :type 'boolean)
1774 (defcustom org-enforce-todo-checkbox-dependencies nil
1775 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1776 When this is nil, checkboxes have no influence on switching TODO states.
1777 When non-nil, you first need to check off all check boxes before the TODO
1778 entry can be switched to DONE.
1779 This variable needs to be set before org.el is loaded, and you need to
1780 restart Emacs after a change to make the change effective. The only way
1781 to change is while Emacs is running is through the customize interface."
1782 :set (lambda (var val)
1783 (set var val)
1784 (if val
1785 (add-hook 'org-blocker-hook
1786 'org-block-todo-from-checkboxes)
1787 (remove-hook 'org-blocker-hook
1788 'org-block-todo-from-checkboxes)))
1789 :group 'org-todo
1790 :type 'boolean)
1792 (defcustom org-treat-insert-todo-heading-as-state-change nil
1793 "Non-nil means, inserting a TODO heading is treated as state change.
1794 So when the command \\[org-insert-todo-heading] is used, state change
1795 logging will apply if appropriate. When nil, the new TODO item will
1796 be inserted directly, and no logging will take place."
1797 :group 'org-todo
1798 :type 'boolean)
1800 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1801 "Non-nil means, switching TODO states with S-cursor counts as state change.
1802 This is the default behavior. However, setting this to nil allows a
1803 convenient way to select a TODO state and bypass any logging associated
1804 with that."
1805 :group 'org-todo
1806 :type 'boolean)
1808 (defcustom org-todo-state-tags-triggers nil
1809 "Tag changes that should be triggered by TODO state changes.
1810 This is a list. Each entry is
1812 (state-change (tag . flag) .......)
1814 State-change can be a string with a state, and empty string to indicate the
1815 state that has no TODO keyword, or it can be one of the symbols `todo'
1816 or `done', meaning any not-done or done state, respectively."
1817 :group 'org-todo
1818 :group 'org-tags
1819 :type '(repeat
1820 (cons (choice :tag "When changing to"
1821 (const :tag "Not-done state" todo)
1822 (const :tag "Done state" done)
1823 (string :tag "State"))
1824 (repeat
1825 (cons :tag "Tag action"
1826 (string :tag "Tag")
1827 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1829 (defcustom org-log-done nil
1830 "Information to record when a task moves to the DONE state.
1832 Possible values are:
1834 nil Don't add anything, just change the keyword
1835 time Add a time stamp to the task
1836 note Prompt a closing note and add it with template `org-log-note-headings'
1838 This option can also be set with on a per-file-basis with
1840 #+STARTUP: nologdone
1841 #+STARTUP: logdone
1842 #+STARTUP: lognotedone
1844 You can have local logging settings for a subtree by setting the LOGGING
1845 property to one or more of these keywords."
1846 :group 'org-todo
1847 :group 'org-progress
1848 :type '(choice
1849 (const :tag "No logging" nil)
1850 (const :tag "Record CLOSED timestamp" time)
1851 (const :tag "Record CLOSED timestamp with closing note." note)))
1853 ;; Normalize old uses of org-log-done.
1854 (cond
1855 ((eq org-log-done t) (setq org-log-done 'time))
1856 ((and (listp org-log-done) (memq 'done org-log-done))
1857 (setq org-log-done 'note)))
1859 (defcustom org-log-note-clock-out nil
1860 "Non-nil means, record a note when clocking out of an item.
1861 This can also be configured on a per-file basis by adding one of
1862 the following lines anywhere in the buffer:
1864 #+STARTUP: lognoteclock-out
1865 #+STARTUP: nolognoteclock-out"
1866 :group 'org-todo
1867 :group 'org-progress
1868 :type 'boolean)
1870 (defcustom org-log-done-with-time t
1871 "Non-nil means, the CLOSED time stamp will contain date and time.
1872 When nil, only the date will be recorded."
1873 :group 'org-progress
1874 :type 'boolean)
1876 (defcustom org-log-note-headings
1877 '((done . "CLOSING NOTE %t")
1878 (state . "State %-12s from %-12S %t")
1879 (note . "Note taken on %t")
1880 (clock-out . ""))
1881 "Headings for notes added to entries.
1882 The value is an alist, with the car being a symbol indicating the note
1883 context, and the cdr is the heading to be used. The heading may also be the
1884 empty string.
1885 %t in the heading will be replaced by a time stamp.
1886 %s will be replaced by the new TODO state, in double quotes.
1887 %S will be replaced by the old TODO state, in double quotes.
1888 %u will be replaced by the user name.
1889 %U will be replaced by the full user name."
1890 :group 'org-todo
1891 :group 'org-progress
1892 :type '(list :greedy t
1893 (cons (const :tag "Heading when closing an item" done) string)
1894 (cons (const :tag
1895 "Heading when changing todo state (todo sequence only)"
1896 state) string)
1897 (cons (const :tag "Heading when just taking a note" note) string)
1898 (cons (const :tag "Heading when clocking out" clock-out) string)))
1900 (unless (assq 'note org-log-note-headings)
1901 (push '(note . "%t") org-log-note-headings))
1903 (defcustom org-log-into-drawer nil
1904 "Non-nil means, insert state change notes and time stamps into a drawer.
1905 When nil, state changes notes will be inserted after the headline and
1906 any scheduling and clock lines, but not inside a drawer.
1908 The value of this variable should be the name of the drawer to use.
1909 LOGBOOK is proposed at the default drawer for this purpose, you can
1910 also set this to a string to define the drawer of your choice.
1912 A value of t is also allowed, representing \"LOGBOOK\".
1914 If this variable is set, `org-log-state-notes-insert-after-drawers'
1915 will be ignored.
1917 You can set the property LOG_INTO_DRAWER to overrule this setting for
1918 a subtree."
1919 :group 'org-todo
1920 :group 'org-progress
1921 :type '(choice
1922 (const :tag "Not into a drawer" nil)
1923 (const :tag "LOGBOOK" t)
1924 (string :tag "Other")))
1926 (if (fboundp 'defvaralias)
1927 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1929 (defun org-log-into-drawer ()
1930 "Return the value of `org-log-into-drawer', but let properties overrule.
1931 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
1932 used instead of the default value."
1933 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
1934 (cond
1935 ((or (not p) (equal p "nil")) org-log-into-drawer)
1936 ((equal p "t") "LOGBOOK")
1937 (t p))))
1939 (defcustom org-log-state-notes-insert-after-drawers nil
1940 "Non-nil means, insert state change notes after any drawers in entry.
1941 Only the drawers that *immediately* follow the headline and the
1942 deadline/scheduled line are skipped.
1943 When nil, insert notes right after the heading and perhaps the line
1944 with deadline/scheduling if present.
1946 This variable will have no effect if `org-log-into-drawer' is
1947 set."
1948 :group 'org-todo
1949 :group 'org-progress
1950 :type 'boolean)
1952 (defcustom org-log-states-order-reversed t
1953 "Non-nil means, the latest state change note will be directly after heading.
1954 When nil, the notes will be orderer according to time."
1955 :group 'org-todo
1956 :group 'org-progress
1957 :type 'boolean)
1959 (defcustom org-log-repeat 'time
1960 "Non-nil means, record moving through the DONE state when triggering repeat.
1961 An auto-repeating tasks is immediately switched back to TODO when marked
1962 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1963 the TODO keyword definition, or recording a closing note by setting
1964 `org-log-done', there will be no record of the task moving through DONE.
1965 This variable forces taking a note anyway. Possible values are:
1967 nil Don't force a record
1968 time Record a time stamp
1969 note Record a note
1971 This option can also be set with on a per-file-basis with
1973 #+STARTUP: logrepeat
1974 #+STARTUP: lognoterepeat
1975 #+STARTUP: nologrepeat
1977 You can have local logging settings for a subtree by setting the LOGGING
1978 property to one or more of these keywords."
1979 :group 'org-todo
1980 :group 'org-progress
1981 :type '(choice
1982 (const :tag "Don't force a record" nil)
1983 (const :tag "Force recording the DONE state" time)
1984 (const :tag "Force recording a note with the DONE state" note)))
1987 (defgroup org-priorities nil
1988 "Priorities in Org-mode."
1989 :tag "Org Priorities"
1990 :group 'org-todo)
1992 (defcustom org-enable-priority-commands t
1993 "Non-nil means, priority commands are active.
1994 When nil, these commands will be disabled, so that you never accidentally
1995 set a priority."
1996 :group 'org-priorities
1997 :type 'boolean)
1999 (defcustom org-highest-priority ?A
2000 "The highest priority of TODO items. A character like ?A, ?B etc.
2001 Must have a smaller ASCII number than `org-lowest-priority'."
2002 :group 'org-priorities
2003 :type 'character)
2005 (defcustom org-lowest-priority ?C
2006 "The lowest priority of TODO items. A character like ?A, ?B etc.
2007 Must have a larger ASCII number than `org-highest-priority'."
2008 :group 'org-priorities
2009 :type 'character)
2011 (defcustom org-default-priority ?B
2012 "The default priority of TODO items.
2013 This is the priority an item get if no explicit priority is given."
2014 :group 'org-priorities
2015 :type 'character)
2017 (defcustom org-priority-start-cycle-with-default t
2018 "Non-nil means, start with default priority when starting to cycle.
2019 When this is nil, the first step in the cycle will be (depending on the
2020 command used) one higher or lower that the default priority."
2021 :group 'org-priorities
2022 :type 'boolean)
2024 (defgroup org-time nil
2025 "Options concerning time stamps and deadlines in Org-mode."
2026 :tag "Org Time"
2027 :group 'org)
2029 (defcustom org-insert-labeled-timestamps-at-point nil
2030 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2031 When nil, these labeled time stamps are forces into the second line of an
2032 entry, just after the headline. When scheduling from the global TODO list,
2033 the time stamp will always be forced into the second line."
2034 :group 'org-time
2035 :type 'boolean)
2037 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2038 "Formats for `format-time-string' which are used for time stamps.
2039 It is not recommended to change this constant.")
2041 (defcustom org-time-stamp-rounding-minutes '(0 5)
2042 "Number of minutes to round time stamps to.
2043 These are two values, the first applies when first creating a time stamp.
2044 The second applies when changing it with the commands `S-up' and `S-down'.
2045 When changing the time stamp, this means that it will change in steps
2046 of N minutes, as given by the second value.
2048 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2049 numbers should be factors of 60, so for example 5, 10, 15.
2051 When this is larger than 1, you can still force an exact time-stamp by using
2052 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2053 and by using a prefix arg to `S-up/down' to specify the exact number
2054 of minutes to shift."
2055 :group 'org-time
2056 :get '(lambda (var) ; Make sure all entries have 5 elements
2057 (if (integerp (default-value var))
2058 (list (default-value var) 5)
2059 (default-value var)))
2060 :type '(list
2061 (integer :tag "when inserting times")
2062 (integer :tag "when modifying times")))
2064 ;; Normalize old customizations of this variable.
2065 (when (integerp org-time-stamp-rounding-minutes)
2066 (setq org-time-stamp-rounding-minutes
2067 (list org-time-stamp-rounding-minutes
2068 org-time-stamp-rounding-minutes)))
2070 (defcustom org-display-custom-times nil
2071 "Non-nil means, overlay custom formats over all time stamps.
2072 The formats are defined through the variable `org-time-stamp-custom-formats'.
2073 To turn this on on a per-file basis, insert anywhere in the file:
2074 #+STARTUP: customtime"
2075 :group 'org-time
2076 :set 'set-default
2077 :type 'sexp)
2078 (make-variable-buffer-local 'org-display-custom-times)
2080 (defcustom org-time-stamp-custom-formats
2081 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2082 "Custom formats for time stamps. See `format-time-string' for the syntax.
2083 These are overlayed over the default ISO format if the variable
2084 `org-display-custom-times' is set. Time like %H:%M should be at the
2085 end of the second format. The custom formats are also honored by export
2086 commands, if custom time display is turned on at the time of export."
2087 :group 'org-time
2088 :type 'sexp)
2090 (defun org-time-stamp-format (&optional long inactive)
2091 "Get the right format for a time string."
2092 (let ((f (if long (cdr org-time-stamp-formats)
2093 (car org-time-stamp-formats))))
2094 (if inactive
2095 (concat "[" (substring f 1 -1) "]")
2096 f)))
2098 (defcustom org-time-clocksum-format "%d:%02d"
2099 "The format string used when creating CLOCKSUM lines, or when
2100 org-mode generates a time duration."
2101 :group 'org-time
2102 :type 'string)
2104 (defcustom org-deadline-warning-days 14
2105 "No. of days before expiration during which a deadline becomes active.
2106 This variable governs the display in sparse trees and in the agenda.
2107 When 0 or negative, it means use this number (the absolute value of it)
2108 even if a deadline has a different individual lead time specified.
2110 Custom commands can set this variable in the options section."
2111 :group 'org-time
2112 :group 'org-agenda-daily/weekly
2113 :type 'integer)
2115 (defcustom org-read-date-prefer-future t
2116 "Non-nil means, assume future for incomplete date input from user.
2117 This affects the following situations:
2118 1. The user gives a day, but no month.
2119 For example, if today is the 15th, and you enter \"3\", Org-mode will
2120 read this as the third of *next* month. However, if you enter \"17\",
2121 it will be considered as *this* month.
2122 2. The user gives a month but not a year.
2123 For example, if it is april and you enter \"feb 2\", this will be read
2124 as feb 2, *next* year. \"May 5\", however, will be this year.
2126 Currently this does not work for ISO week specifications.
2128 When this option is nil, the current month and year will always be used
2129 as defaults."
2130 :group 'org-time
2131 :type 'boolean)
2133 (defcustom org-read-date-display-live t
2134 "Non-nil means, display current interpretation of date prompt live.
2135 This display will be in an overlay, in the minibuffer."
2136 :group 'org-time
2137 :type 'boolean)
2139 (defcustom org-read-date-popup-calendar t
2140 "Non-nil means, pop up a calendar when prompting for a date.
2141 In the calendar, the date can be selected with mouse-1. However, the
2142 minibuffer will also be active, and you can simply enter the date as well.
2143 When nil, only the minibuffer will be available."
2144 :group 'org-time
2145 :type 'boolean)
2146 (if (fboundp 'defvaralias)
2147 (defvaralias 'org-popup-calendar-for-date-prompt
2148 'org-read-date-popup-calendar))
2150 (defcustom org-read-date-minibuffer-setup-hook nil
2151 "Hook to be used to set up keys for the date/time interface.
2152 Add key definitions to `minibuffer-local-map', which will be a temporary
2153 copy."
2154 :group 'org-time
2155 :type 'hook)
2157 (defcustom org-extend-today-until 0
2158 "The hour when your day really ends. Must be an integer.
2159 This has influence for the following applications:
2160 - When switching the agenda to \"today\". It it is still earlier than
2161 the time given here, the day recognized as TODAY is actually yesterday.
2162 - When a date is read from the user and it is still before the time given
2163 here, the current date and time will be assumed to be yesterday, 23:59.
2164 Also, timestamps inserted in remember templates follow this rule.
2166 IMPORTANT: This is a feature whose implementation is and likely will
2167 remain incomplete. Really, it is only here because past midnight seems to
2168 be the favorite working time of John Wiegley :-)"
2169 :group 'org-time
2170 :type 'integer)
2172 (defcustom org-edit-timestamp-down-means-later nil
2173 "Non-nil means, S-down will increase the time in a time stamp.
2174 When nil, S-up will increase."
2175 :group 'org-time
2176 :type 'boolean)
2178 (defcustom org-calendar-follow-timestamp-change t
2179 "Non-nil means, make the calendar window follow timestamp changes.
2180 When a timestamp is modified and the calendar window is visible, it will be
2181 moved to the new date."
2182 :group 'org-time
2183 :type 'boolean)
2185 (defgroup org-tags nil
2186 "Options concerning tags in Org-mode."
2187 :tag "Org Tags"
2188 :group 'org)
2190 (defcustom org-tag-alist nil
2191 "List of tags allowed in Org-mode files.
2192 When this list is nil, Org-mode will base TAG input on what is already in the
2193 buffer.
2194 The value of this variable is an alist, the car of each entry must be a
2195 keyword as a string, the cdr may be a character that is used to select
2196 that tag through the fast-tag-selection interface.
2197 See the manual for details."
2198 :group 'org-tags
2199 :type '(repeat
2200 (choice
2201 (cons (string :tag "Tag name")
2202 (character :tag "Access char"))
2203 (const :tag "Start radio group" (:startgroup))
2204 (const :tag "End radio group" (:endgroup))
2205 (const :tag "New line" (:newline)))))
2207 (defcustom org-tag-persistent-alist nil
2208 "List of tags that will always appear in all Org-mode files.
2209 This is in addition to any in buffer settings or customizations
2210 of `org-tag-alist'.
2211 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2212 The value of this variable is an alist, the car of each entry must be a
2213 keyword as a string, the cdr may be a character that is used to select
2214 that tag through the fast-tag-selection interface.
2215 See the manual for details.
2216 To disable these tags on a per-file basis, insert anywhere in the file:
2217 #+STARTUP: noptag"
2218 :group 'org-tags
2219 :type '(repeat
2220 (choice
2221 (cons (string :tag "Tag name")
2222 (character :tag "Access char"))
2223 (const :tag "Start radio group" (:startgroup))
2224 (const :tag "End radio group" (:endgroup))
2225 (const :tag "New line" (:newline)))))
2227 (defvar org-file-tags nil
2228 "List of tags that can be inherited by all entries in the file.
2229 The tags will be inherited if the variable `org-use-tag-inheritance'
2230 says they should be.
2231 This variable is populated from #+TAG lines.")
2233 (defcustom org-use-fast-tag-selection 'auto
2234 "Non-nil means, use fast tag selection scheme.
2235 This is a special interface to select and deselect tags with single keys.
2236 When nil, fast selection is never used.
2237 When the symbol `auto', fast selection is used if and only if selection
2238 characters for tags have been configured, either through the variable
2239 `org-tag-alist' or through a #+TAGS line in the buffer.
2240 When t, fast selection is always used and selection keys are assigned
2241 automatically if necessary."
2242 :group 'org-tags
2243 :type '(choice
2244 (const :tag "Always" t)
2245 (const :tag "Never" nil)
2246 (const :tag "When selection characters are configured" 'auto)))
2248 (defcustom org-fast-tag-selection-single-key nil
2249 "Non-nil means, fast tag selection exits after first change.
2250 When nil, you have to press RET to exit it.
2251 During fast tag selection, you can toggle this flag with `C-c'.
2252 This variable can also have the value `expert'. In this case, the window
2253 displaying the tags menu is not even shown, until you press C-c again."
2254 :group 'org-tags
2255 :type '(choice
2256 (const :tag "No" nil)
2257 (const :tag "Yes" t)
2258 (const :tag "Expert" expert)))
2260 (defvar org-fast-tag-selection-include-todo nil
2261 "Non-nil means, fast tags selection interface will also offer TODO states.
2262 This is an undocumented feature, you should not rely on it.")
2264 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2265 "The column to which tags should be indented in a headline.
2266 If this number is positive, it specifies the column. If it is negative,
2267 it means that the tags should be flushright to that column. For example,
2268 -80 works well for a normal 80 character screen."
2269 :group 'org-tags
2270 :type 'integer)
2272 (defcustom org-auto-align-tags t
2273 "Non-nil means, realign tags after pro/demotion of TODO state change.
2274 These operations change the length of a headline and therefore shift
2275 the tags around. With this options turned on, after each such operation
2276 the tags are again aligned to `org-tags-column'."
2277 :group 'org-tags
2278 :type 'boolean)
2280 (defcustom org-use-tag-inheritance t
2281 "Non-nil means, tags in levels apply also for sublevels.
2282 When nil, only the tags directly given in a specific line apply there.
2283 This may also be a list of tags that should be inherited, or a regexp that
2284 matches tags that should be inherited. Additional control is possible
2285 with the variable `org-tags-exclude-from-inheritance' which gives an
2286 explicit list of tags to be excluded from inheritance., even if the value of
2287 `org-use-tag-inheritance' would select it for inheritance.
2289 If this option is t, a match early-on in a tree can lead to a large
2290 number of matches in the subtree when constructing the agenda or creating
2291 a sparse tree. If you only want to see the first match in a tree during
2292 a search, check out the variable `org-tags-match-list-sublevels'."
2293 :group 'org-tags
2294 :type '(choice
2295 (const :tag "Not" nil)
2296 (const :tag "Always" t)
2297 (repeat :tag "Specific tags" (string :tag "Tag"))
2298 (regexp :tag "Tags matched by regexp")))
2300 (defcustom org-tags-exclude-from-inheritance nil
2301 "List of tags that should never be inherited.
2302 This is a way to exclude a few tags from inheritance. For way to do
2303 the opposite, to actively allow inheritance for selected tags,
2304 see the variable `org-use-tag-inheritance'."
2305 :group 'org-tags
2306 :type '(repeat (string :tag "Tag")))
2308 (defun org-tag-inherit-p (tag)
2309 "Check if TAG is one that should be inherited."
2310 (cond
2311 ((member tag org-tags-exclude-from-inheritance) nil)
2312 ((eq org-use-tag-inheritance t) t)
2313 ((not org-use-tag-inheritance) nil)
2314 ((stringp org-use-tag-inheritance)
2315 (string-match org-use-tag-inheritance tag))
2316 ((listp org-use-tag-inheritance)
2317 (member tag org-use-tag-inheritance))
2318 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2320 (defcustom org-tags-match-list-sublevels t
2321 "Non-nil means list also sublevels of headlines matching a search.
2322 This variable applies to tags/property searches, and also to stuck
2323 projects because this search is based on a tags match as well.
2325 When set to the symbol `indented', sublevels are indented with
2326 leading dots.
2328 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2329 the sublevels of a headline matching a tag search often also match
2330 the same search. Listing all of them can create very long lists.
2331 Setting this variable to nil causes subtrees of a match to be skipped.
2333 This variable is semi-obsolete and probably should always be true. It
2334 is better to limit inheritance to certain tags using the variables
2335 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2336 :group 'org-tags
2337 :type '(choice
2338 (const :tag "No, don't list them" nil)
2339 (const :tag "Yes, do list them" t)
2340 (const :tag "List them, indented with leading dots" indented)))
2342 (defcustom org-tags-sort-function nil
2343 "When set, tags are sorted using this function as a comparator"
2344 :group 'org-tags
2345 :type '(choice
2346 (const :tag "No sorting" nil)
2347 (const :tag "Alphabetical" string<)
2348 (const :tag "Reverse alphabetical" string>)
2349 (function :tag "Custom function" nil)))
2351 (defvar org-tags-history nil
2352 "History of minibuffer reads for tags.")
2353 (defvar org-last-tags-completion-table nil
2354 "The last used completion table for tags.")
2355 (defvar org-after-tags-change-hook nil
2356 "Hook that is run after the tags in a line have changed.")
2358 (defgroup org-properties nil
2359 "Options concerning properties in Org-mode."
2360 :tag "Org Properties"
2361 :group 'org)
2363 (defcustom org-property-format "%-10s %s"
2364 "How property key/value pairs should be formatted by `indent-line'.
2365 When `indent-line' hits a property definition, it will format the line
2366 according to this format, mainly to make sure that the values are
2367 lined-up with respect to each other."
2368 :group 'org-properties
2369 :type 'string)
2371 (defcustom org-use-property-inheritance nil
2372 "Non-nil means, properties apply also for sublevels.
2374 This setting is chiefly used during property searches. Turning it on can
2375 cause significant overhead when doing a search, which is why it is not
2376 on by default.
2378 When nil, only the properties directly given in the current entry count.
2379 When t, every property is inherited. The value may also be a list of
2380 properties that should have inheritance, or a regular expression matching
2381 properties that should be inherited.
2383 However, note that some special properties use inheritance under special
2384 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2385 and the properties ending in \"_ALL\" when they are used as descriptor
2386 for valid values of a property.
2388 Note for programmers:
2389 When querying an entry with `org-entry-get', you can control if inheritance
2390 should be used. By default, `org-entry-get' looks only at the local
2391 properties. You can request inheritance by setting the inherit argument
2392 to t (to force inheritance) or to `selective' (to respect the setting
2393 in this variable)."
2394 :group 'org-properties
2395 :type '(choice
2396 (const :tag "Not" nil)
2397 (const :tag "Always" t)
2398 (repeat :tag "Specific properties" (string :tag "Property"))
2399 (regexp :tag "Properties matched by regexp")))
2401 (defun org-property-inherit-p (property)
2402 "Check if PROPERTY is one that should be inherited."
2403 (cond
2404 ((eq org-use-property-inheritance t) t)
2405 ((not org-use-property-inheritance) nil)
2406 ((stringp org-use-property-inheritance)
2407 (string-match org-use-property-inheritance property))
2408 ((listp org-use-property-inheritance)
2409 (member property org-use-property-inheritance))
2410 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2412 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2413 "The default column format, if no other format has been defined.
2414 This variable can be set on the per-file basis by inserting a line
2416 #+COLUMNS: %25ITEM ....."
2417 :group 'org-properties
2418 :type 'string)
2420 (defcustom org-columns-ellipses ".."
2421 "The ellipses to be used when a field in column view is truncated.
2422 When this is the empty string, as many characters as possible are shown,
2423 but then there will be no visual indication that the field has been truncated.
2424 When this is a string of length N, the last N characters of a truncated
2425 field are replaced by this string. If the column is narrower than the
2426 ellipses string, only part of the ellipses string will be shown."
2427 :group 'org-properties
2428 :type 'string)
2430 (defcustom org-columns-modify-value-for-display-function nil
2431 "Function that modifies values for display in column view.
2432 For example, it can be used to cut out a certain part from a time stamp.
2433 The function must take 2 arguments:
2435 column-title The title of the column (*not* the property name)
2436 value The value that should be modified.
2438 The function should return the value that should be displayed,
2439 or nil if the normal value should be used."
2440 :group 'org-properties
2441 :type 'function)
2443 (defcustom org-effort-property "Effort"
2444 "The property that is being used to keep track of effort estimates.
2445 Effort estimates given in this property need to have the format H:MM."
2446 :group 'org-properties
2447 :group 'org-progress
2448 :type '(string :tag "Property"))
2450 (defconst org-global-properties-fixed
2451 '(("VISIBILITY_ALL" . "folded children content all")
2452 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2453 "List of property/value pairs that can be inherited by any entry.
2455 These are fixed values, for the preset properties. The user variable
2456 that can be used to add to this list is `org-global-properties'.
2458 The entries in this list are cons cells where the car is a property
2459 name and cdr is a string with the value. If the value represents
2460 multiple items like an \"_ALL\" property, separate the items by
2461 spaces.")
2463 (defcustom org-global-properties nil
2464 "List of property/value pairs that can be inherited by any entry.
2466 This list will be combined with the constant `org-global-properties-fixed'.
2468 The entries in this list are cons cells where the car is a property
2469 name and cdr is a string with the value.
2471 You can set buffer-local values for the same purpose in the variable
2472 `org-file-properties' this by adding lines like
2474 #+PROPERTY: NAME VALUE"
2475 :group 'org-properties
2476 :type '(repeat
2477 (cons (string :tag "Property")
2478 (string :tag "Value"))))
2480 (defvar org-file-properties nil
2481 "List of property/value pairs that can be inherited by any entry.
2482 Valid for the current buffer.
2483 This variable is populated from #+PROPERTY lines.")
2484 (make-variable-buffer-local 'org-file-properties)
2486 (defgroup org-agenda nil
2487 "Options concerning agenda views in Org-mode."
2488 :tag "Org Agenda"
2489 :group 'org)
2491 (defvar org-category nil
2492 "Variable used by org files to set a category for agenda display.
2493 Such files should use a file variable to set it, for example
2495 # -*- mode: org; org-category: \"ELisp\"
2497 or contain a special line
2499 #+CATEGORY: ELisp
2501 If the file does not specify a category, then file's base name
2502 is used instead.")
2503 (make-variable-buffer-local 'org-category)
2504 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2506 (defcustom org-agenda-files nil
2507 "The files to be used for agenda display.
2508 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2509 \\[org-remove-file]. You can also use customize to edit the list.
2511 If an entry is a directory, all files in that directory that are matched by
2512 `org-agenda-file-regexp' will be part of the file list.
2514 If the value of the variable is not a list but a single file name, then
2515 the list of agenda files is actually stored and maintained in that file, one
2516 agenda file per line."
2517 :group 'org-agenda
2518 :type '(choice
2519 (repeat :tag "List of files and directories" file)
2520 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2522 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2523 "Regular expression to match files for `org-agenda-files'.
2524 If any element in the list in that variable contains a directory instead
2525 of a normal file, all files in that directory that are matched by this
2526 regular expression will be included."
2527 :group 'org-agenda
2528 :type 'regexp)
2530 (defcustom org-agenda-text-search-extra-files nil
2531 "List of extra files to be searched by text search commands.
2532 These files will be search in addition to the agenda files by the
2533 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2534 Note that these files will only be searched for text search commands,
2535 not for the other agenda views like todo lists, tag searches or the weekly
2536 agenda. This variable is intended to list notes and possibly archive files
2537 that should also be searched by these two commands.
2538 In fact, if the first element in the list is the symbol `agenda-archives',
2539 than all archive files of all agenda files will be added to the search
2540 scope."
2541 :group 'org-agenda
2542 :type '(set :greedy t
2543 (const :tag "Agenda Archives" agenda-archives)
2544 (repeat :inline t (file))))
2546 (if (fboundp 'defvaralias)
2547 (defvaralias 'org-agenda-multi-occur-extra-files
2548 'org-agenda-text-search-extra-files))
2550 (defcustom org-agenda-skip-unavailable-files nil
2551 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2552 A nil value means to remove them, after a query, from the list."
2553 :group 'org-agenda
2554 :type 'boolean)
2556 (defcustom org-calendar-to-agenda-key [?c]
2557 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2558 The command `org-calendar-goto-agenda' will be bound to this key. The
2559 default is the character `c' because then `c' can be used to switch back and
2560 forth between agenda and calendar."
2561 :group 'org-agenda
2562 :type 'sexp)
2564 (defcustom org-calendar-agenda-action-key [?k]
2565 "The key to be installed in `calendar-mode-map' for agenda-action.
2566 The command `org-agenda-action' will be bound to this key. The
2567 default is the character `k' because we use the same key in the agenda."
2568 :group 'org-agenda
2569 :type 'sexp)
2571 (eval-after-load "calendar"
2572 '(progn
2573 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2574 'org-calendar-goto-agenda)
2575 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2576 'org-agenda-action)))
2578 (defgroup org-latex nil
2579 "Options for embedding LaTeX code into Org-mode."
2580 :tag "Org LaTeX"
2581 :group 'org)
2583 (defcustom org-format-latex-options
2584 '(:foreground default :background default :scale 1.0
2585 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2586 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2587 "Options for creating images from LaTeX fragments.
2588 This is a property list with the following properties:
2589 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2590 `default' means use the foreground of the default face.
2591 :background the background color, or \"Transparent\".
2592 `default' means use the background of the default face.
2593 :scale a scaling factor for the size of the images.
2594 :html-foreground, :html-background, :html-scale
2595 the same numbers for HTML export.
2596 :matchers a list indicating which matchers should be used to
2597 find LaTeX fragments. Valid members of this list are:
2598 \"begin\" find environments
2599 \"$1\" find single characters surrounded by $.$
2600 \"$\" find math expressions surrounded by $...$
2601 \"$$\" find math expressions surrounded by $$....$$
2602 \"\\(\" find math expressions surrounded by \\(...\\)
2603 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2604 :group 'org-latex
2605 :type 'plist)
2607 (defcustom org-format-latex-header "\\documentclass{article}
2608 \\usepackage{fullpage} % do not remove
2609 \\usepackage{amssymb}
2610 \\usepackage[usenames]{color}
2611 \\usepackage{amsmath}
2612 \\usepackage{latexsym}
2613 \\usepackage[mathscr]{eucal}
2614 \\pagestyle{empty} % do not remove"
2615 "The document header used for processing LaTeX fragments."
2616 :group 'org-latex
2617 :type 'string)
2620 (defgroup org-font-lock nil
2621 "Font-lock settings for highlighting in Org-mode."
2622 :tag "Org Font Lock"
2623 :group 'org)
2625 (defcustom org-level-color-stars-only nil
2626 "Non-nil means fontify only the stars in each headline.
2627 When nil, the entire headline is fontified.
2628 Changing it requires restart of `font-lock-mode' to become effective
2629 also in regions already fontified."
2630 :group 'org-font-lock
2631 :type 'boolean)
2633 (defcustom org-hide-leading-stars nil
2634 "Non-nil means, hide the first N-1 stars in a headline.
2635 This works by using the face `org-hide' for these stars. This
2636 face is white for a light background, and black for a dark
2637 background. You may have to customize the face `org-hide' to
2638 make this work.
2639 Changing it requires restart of `font-lock-mode' to become effective
2640 also in regions already fontified.
2641 You may also set this on a per-file basis by adding one of the following
2642 lines to the buffer:
2644 #+STARTUP: hidestars
2645 #+STARTUP: showstars"
2646 :group 'org-font-lock
2647 :type 'boolean)
2649 (defcustom org-fontify-done-headline nil
2650 "Non-nil means, change the face of a headline if it is marked DONE.
2651 Normally, only the TODO/DONE keyword indicates the state of a headline.
2652 When this is non-nil, the headline after the keyword is set to the
2653 `org-headline-done' as an additional indication."
2654 :group 'org-font-lock
2655 :type 'boolean)
2657 (defcustom org-fontify-emphasized-text t
2658 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2659 Changing this variable requires a restart of Emacs to take effect."
2660 :group 'org-font-lock
2661 :type 'boolean)
2663 (defcustom org-highlight-latex-fragments-and-specials nil
2664 "Non-nil means, fontify what is treated specially by the exporters."
2665 :group 'org-font-lock
2666 :type 'boolean)
2668 (defcustom org-hide-emphasis-markers nil
2669 "Non-nil mean font-lock should hide the emphasis marker characters."
2670 :group 'org-font-lock
2671 :type 'boolean)
2673 (defvar org-emph-re nil
2674 "Regular expression for matching emphasis.")
2675 (defvar org-verbatim-re nil
2676 "Regular expression for matching verbatim text.")
2677 (defvar org-emphasis-regexp-components) ; defined just below
2678 (defvar org-emphasis-alist) ; defined just below
2679 (defun org-set-emph-re (var val)
2680 "Set variable and compute the emphasis regular expression."
2681 (set var val)
2682 (when (and (boundp 'org-emphasis-alist)
2683 (boundp 'org-emphasis-regexp-components)
2684 org-emphasis-alist org-emphasis-regexp-components)
2685 (let* ((e org-emphasis-regexp-components)
2686 (pre (car e))
2687 (post (nth 1 e))
2688 (border (nth 2 e))
2689 (body (nth 3 e))
2690 (nl (nth 4 e))
2691 (body1 (concat body "*?"))
2692 (markers (mapconcat 'car org-emphasis-alist ""))
2693 (vmarkers (mapconcat
2694 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2695 org-emphasis-alist "")))
2696 ;; make sure special characters appear at the right position in the class
2697 (if (string-match "\\^" markers)
2698 (setq markers (concat (replace-match "" t t markers) "^")))
2699 (if (string-match "-" markers)
2700 (setq markers (concat (replace-match "" t t markers) "-")))
2701 (if (string-match "\\^" vmarkers)
2702 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2703 (if (string-match "-" vmarkers)
2704 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2705 (if (> nl 0)
2706 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2707 (int-to-string nl) "\\}")))
2708 ;; Make the regexp
2709 (setq org-emph-re
2710 (concat "\\([" pre "]\\|^\\)"
2711 "\\("
2712 "\\([" markers "]\\)"
2713 "\\("
2714 "[^" border "]\\|"
2715 "[^" border "]"
2716 body1
2717 "[^" border "]"
2718 "\\)"
2719 "\\3\\)"
2720 "\\([" post "]\\|$\\)"))
2721 (setq org-verbatim-re
2722 (concat "\\([" pre "]\\|^\\)"
2723 "\\("
2724 "\\([" vmarkers "]\\)"
2725 "\\("
2726 "[^" border "]\\|"
2727 "[^" border "]"
2728 body1
2729 "[^" border "]"
2730 "\\)"
2731 "\\3\\)"
2732 "\\([" post "]\\|$\\)")))))
2734 (defcustom org-emphasis-regexp-components
2735 '(" \t('\"{" "- \t.,:!?;'\")}" " \t\r\n,\"'" "." 1)
2736 "Components used to build the regular expression for emphasis.
2737 This is a list with 6 entries. Terminology: In an emphasis string
2738 like \" *strong word* \", we call the initial space PREMATCH, the final
2739 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2740 and \"trong wor\" is the body. The different components in this variable
2741 specify what is allowed/forbidden in each part:
2743 pre Chars allowed as prematch. Beginning of line will be allowed too.
2744 post Chars allowed as postmatch. End of line will be allowed too.
2745 border The chars *forbidden* as border characters.
2746 body-regexp A regexp like \".\" to match a body character. Don't use
2747 non-shy groups here, and don't allow newline here.
2748 newline The maximum number of newlines allowed in an emphasis exp.
2750 Use customize to modify this, or restart Emacs after changing it."
2751 :group 'org-font-lock
2752 :set 'org-set-emph-re
2753 :type '(list
2754 (sexp :tag "Allowed chars in pre ")
2755 (sexp :tag "Allowed chars in post ")
2756 (sexp :tag "Forbidden chars in border ")
2757 (sexp :tag "Regexp for body ")
2758 (integer :tag "number of newlines allowed")
2759 (option (boolean :tag "Please ignore this button"))))
2761 (defcustom org-emphasis-alist
2762 `(("*" bold "<b>" "</b>")
2763 ("/" italic "<i>" "</i>")
2764 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2765 ("=" org-code "<code>" "</code>" verbatim)
2766 ("~" org-verbatim "<code>" "</code>" verbatim)
2767 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2768 "<del>" "</del>")
2770 "Special syntax for emphasized text.
2771 Text starting and ending with a special character will be emphasized, for
2772 example *bold*, _underlined_ and /italic/. This variable sets the marker
2773 characters, the face to be used by font-lock for highlighting in Org-mode
2774 Emacs buffers, and the HTML tags to be used for this.
2775 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2776 Use customize to modify this, or restart Emacs after changing it."
2777 :group 'org-font-lock
2778 :set 'org-set-emph-re
2779 :type '(repeat
2780 (list
2781 (string :tag "Marker character")
2782 (choice
2783 (face :tag "Font-lock-face")
2784 (plist :tag "Face property list"))
2785 (string :tag "HTML start tag")
2786 (string :tag "HTML end tag")
2787 (option (const verbatim)))))
2789 (defvar org-protecting-blocks
2790 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
2791 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
2792 This is needed for font-lock setup.")
2794 ;;; Miscellaneous options
2796 (defgroup org-completion nil
2797 "Completion in Org-mode."
2798 :tag "Org Completion"
2799 :group 'org)
2801 (defcustom org-completion-use-ido nil
2802 "Non-nil means, use ido completion wherever possible.
2803 Note that `ido-mode' must be active for this variable to be relevant.
2804 If you decide to turn this variable on, you might well want to turn off
2805 `org-outline-path-complete-in-steps'."
2806 :group 'org-completion
2807 :type 'boolean)
2809 (defcustom org-completion-fallback-command 'hippie-expand
2810 "The expansion command called by \\[org-complete] in normal context.
2811 Normal means, no org-mode-specific context."
2812 :group 'org-completion
2813 :type 'function)
2815 ;;; Functions and variables from ther packages
2816 ;; Declared here to avoid compiler warnings
2818 ;; XEmacs only
2819 (defvar outline-mode-menu-heading)
2820 (defvar outline-mode-menu-show)
2821 (defvar outline-mode-menu-hide)
2822 (defvar zmacs-regions) ; XEmacs regions
2824 ;; Emacs only
2825 (defvar mark-active)
2827 ;; Various packages
2828 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2829 (declare-function calendar-forward-day "cal-move" (arg))
2830 (declare-function calendar-goto-date "cal-move" (date))
2831 (declare-function calendar-goto-today "cal-move" ())
2832 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2833 (defvar calc-embedded-close-formula)
2834 (defvar calc-embedded-open-formula)
2835 (declare-function cdlatex-tab "ext:cdlatex" ())
2836 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2837 (defvar font-lock-unfontify-region-function)
2838 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2839 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2840 (defvar iswitchb-temp-buflist)
2841 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2842 (defvar org-agenda-tags-todo-honor-ignore-options)
2843 (declare-function org-agenda-skip "org-agenda" ())
2844 (declare-function org-format-agenda-item "org-agenda"
2845 (extra txt &optional category tags dotime noprefix remove-re))
2846 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2847 (declare-function org-agenda-change-all-lines "org-agenda"
2848 (newhead hdmarker &optional fixface just-this))
2849 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2850 (declare-function org-agenda-maybe-redo "org-agenda" ())
2851 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2852 (beg end))
2853 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2854 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2855 "org-agenda" (&optional end))
2857 (declare-function parse-time-string "parse-time" (string))
2858 (declare-function remember "remember" (&optional initial))
2859 (declare-function remember-buffer-desc "remember" ())
2860 (declare-function remember-finalize "remember" ())
2861 (defvar remember-save-after-remembering)
2862 (defvar remember-data-file)
2863 (defvar remember-register)
2864 (defvar remember-buffer)
2865 (defvar remember-handler-functions)
2866 (defvar remember-annotation-functions)
2867 (defvar texmathp-why)
2868 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2869 (declare-function table--at-cell-p "table" (position &optional object at-column))
2871 (defvar w3m-current-url)
2872 (defvar w3m-current-title)
2874 (defvar org-latex-regexps)
2876 ;;; Autoload and prepare some org modules
2878 ;; Some table stuff that needs to be defined here, because it is used
2879 ;; by the functions setting up org-mode or checking for table context.
2881 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2882 "Detects an org-type or table-type table.")
2883 (defconst org-table-line-regexp "^[ \t]*|"
2884 "Detects an org-type table line.")
2885 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2886 "Detects an org-type table line.")
2887 (defconst org-table-hline-regexp "^[ \t]*|-"
2888 "Detects an org-type table hline.")
2889 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2890 "Detects a table-type table hline.")
2891 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2892 "Searching from within a table (any type) this finds the first line
2893 outside the table.")
2895 ;; Autoload the functions in org-table.el that are needed by functions here.
2897 (eval-and-compile
2898 (org-autoload "org-table"
2899 '(org-table-align org-table-begin org-table-blank-field
2900 org-table-convert org-table-convert-region org-table-copy-down
2901 org-table-copy-region org-table-create
2902 org-table-create-or-convert-from-region
2903 org-table-create-with-table.el org-table-current-dline
2904 org-table-cut-region org-table-delete-column org-table-edit-field
2905 org-table-edit-formulas org-table-end org-table-eval-formula
2906 org-table-export org-table-field-info
2907 org-table-get-stored-formulas org-table-goto-column
2908 org-table-hline-and-move org-table-import org-table-insert-column
2909 org-table-insert-hline org-table-insert-row org-table-iterate
2910 org-table-justify-field-maybe org-table-kill-row
2911 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2912 org-table-move-column org-table-move-column-left
2913 org-table-move-column-right org-table-move-row
2914 org-table-move-row-down org-table-move-row-up
2915 org-table-next-field org-table-next-row org-table-paste-rectangle
2916 org-table-previous-field org-table-recalculate
2917 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2918 org-table-toggle-coordinate-overlays
2919 org-table-toggle-formula-debugger org-table-wrap-region
2920 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2922 (defun org-at-table-p (&optional table-type)
2923 "Return t if the cursor is inside an org-type table.
2924 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2925 (if org-enable-table-editor
2926 (save-excursion
2927 (beginning-of-line 1)
2928 (looking-at (if table-type org-table-any-line-regexp
2929 org-table-line-regexp)))
2930 nil))
2931 (defsubst org-table-p () (org-at-table-p))
2933 (defun org-at-table.el-p ()
2934 "Return t if and only if we are at a table.el table."
2935 (and (org-at-table-p 'any)
2936 (save-excursion
2937 (goto-char (org-table-begin 'any))
2938 (looking-at org-table1-hline-regexp))))
2939 (defun org-table-recognize-table.el ()
2940 "If there is a table.el table nearby, recognize it and move into it."
2941 (if org-table-tab-recognizes-table.el
2942 (if (org-at-table.el-p)
2943 (progn
2944 (beginning-of-line 1)
2945 (if (looking-at org-table-dataline-regexp)
2947 (if (looking-at org-table1-hline-regexp)
2948 (progn
2949 (beginning-of-line 2)
2950 (if (looking-at org-table-any-border-regexp)
2951 (beginning-of-line -1)))))
2952 (if (re-search-forward "|" (org-table-end t) t)
2953 (progn
2954 (require 'table)
2955 (if (table--at-cell-p (point))
2957 (message "recognizing table.el table...")
2958 (table-recognize-table)
2959 (message "recognizing table.el table...done")))
2960 (error "This should not happen..."))
2962 nil)
2963 nil))
2965 (defun org-at-table-hline-p ()
2966 "Return t if the cursor is inside a hline in a table."
2967 (if org-enable-table-editor
2968 (save-excursion
2969 (beginning-of-line 1)
2970 (looking-at org-table-hline-regexp))
2971 nil))
2973 (defvar org-table-clean-did-remove-column nil)
2975 (defun org-table-map-tables (function)
2976 "Apply FUNCTION to the start of all tables in the buffer."
2977 (save-excursion
2978 (save-restriction
2979 (widen)
2980 (goto-char (point-min))
2981 (while (re-search-forward org-table-any-line-regexp nil t)
2982 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2983 (beginning-of-line 1)
2984 (if (looking-at org-table-line-regexp)
2985 (save-excursion (funcall function)))
2986 (re-search-forward org-table-any-border-regexp nil 1))))
2987 (message "Mapping tables: done"))
2989 ;; Declare and autoload functions from org-exp.el & Co
2991 (declare-function org-default-export-plist "org-exp")
2992 (declare-function org-infile-export-plist "org-exp")
2993 (declare-function org-get-current-options "org-exp")
2994 (eval-and-compile
2995 (org-autoload "org-exp"
2996 '(org-export org-export-visible
2997 org-insert-export-options-template
2998 org-table-clean-before-export))
2999 (org-autoload "org-ascii"
3000 '(org-export-as-ascii org-export-ascii-preprocess
3001 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3002 org-export-region-as-ascii))
3003 (org-autoload "org-html"
3004 '(org-export-as-html-and-open
3005 org-export-as-html-batch org-export-as-html-to-buffer
3006 org-replace-region-by-html org-export-region-as-html
3007 org-export-as-html))
3008 (org-autoload "org-icalendar"
3009 '(org-export-icalendar-this-file
3010 org-export-icalendar-all-agenda-files
3011 org-export-icalendar-combine-agenda-files))
3012 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3014 ;; Declare and autoload functions from org-agenda.el
3016 (eval-and-compile
3017 (org-autoload "org-agenda"
3018 '(org-agenda org-agenda-list org-search-view
3019 org-todo-list org-tags-view org-agenda-list-stuck-projects
3020 org-diary org-agenda-to-appt
3021 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3023 ;; Autoload org-remember
3025 (eval-and-compile
3026 (org-autoload "org-remember"
3027 '(org-remember-insinuate org-remember-annotation
3028 org-remember-apply-template org-remember org-remember-handler)))
3030 ;; Autoload org-clock.el
3033 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3034 (beg end))
3035 (declare-function org-clock-update-mode-line "org-clock" ())
3036 (defvar org-clock-start-time)
3037 (defvar org-clock-marker (make-marker)
3038 "Marker recording the last clock-in.")
3039 (defun org-clock-is-active ()
3040 "Return non-nil if clock is currently running.
3041 The return value is actually the clock marker."
3042 (marker-buffer org-clock-marker))
3044 (eval-and-compile
3045 (org-autoload
3046 "org-clock"
3047 '(org-clock-in org-clock-out org-clock-cancel
3048 org-clock-goto org-clock-sum org-clock-display
3049 org-clock-remove-overlays org-clock-report
3050 org-clocktable-shift org-dblock-write:clocktable
3051 org-get-clocktable)))
3053 (defun org-clock-update-time-maybe ()
3054 "If this is a CLOCK line, update it and return t.
3055 Otherwise, return nil."
3056 (interactive)
3057 (save-excursion
3058 (beginning-of-line 1)
3059 (skip-chars-forward " \t")
3060 (when (looking-at org-clock-string)
3061 (let ((re (concat "[ \t]*" org-clock-string
3062 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3063 "\\([ \t]*=>.*\\)?\\)?"))
3064 ts te h m s neg)
3065 (cond
3066 ((not (looking-at re))
3067 nil)
3068 ((not (match-end 2))
3069 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3070 (> org-clock-marker (point))
3071 (<= org-clock-marker (point-at-eol)))
3072 ;; The clock is running here
3073 (setq org-clock-start-time
3074 (apply 'encode-time
3075 (org-parse-time-string (match-string 1))))
3076 (org-clock-update-mode-line)))
3078 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3079 (end-of-line 1)
3080 (setq ts (match-string 1)
3081 te (match-string 3))
3082 (setq s (- (time-to-seconds
3083 (apply 'encode-time (org-parse-time-string te)))
3084 (time-to-seconds
3085 (apply 'encode-time (org-parse-time-string ts))))
3086 neg (< s 0)
3087 s (abs s)
3088 h (floor (/ s 3600))
3089 s (- s (* 3600 h))
3090 m (floor (/ s 60))
3091 s (- s (* 60 s)))
3092 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3093 t))))))
3095 (defun org-check-running-clock ()
3096 "Check if the current buffer contains the running clock.
3097 If yes, offer to stop it and to save the buffer with the changes."
3098 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3099 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3100 (buffer-name))))
3101 (org-clock-out)
3102 (when (y-or-n-p "Save changed buffer?")
3103 (save-buffer))))
3105 (defun org-clocktable-try-shift (dir n)
3106 "Check if this line starts a clock table, if yes, shift the time block."
3107 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3108 (org-clocktable-shift dir n)))
3110 ;; Autoload org-timer.el
3112 (eval-and-compile
3113 (org-autoload
3114 "org-timer"
3115 '(org-timer-start org-timer org-timer-item
3116 org-timer-change-times-in-region)))
3118 ;; Autoload org-feed.el
3120 (eval-and-compile
3121 (org-autoload
3122 "org-feed"
3123 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3126 ;; Autoload archiving code
3127 ;; The stuff that is needed for cycling and tags has to be defined here.
3129 (defgroup org-archive nil
3130 "Options concerning archiving in Org-mode."
3131 :tag "Org Archive"
3132 :group 'org-structure)
3134 (defcustom org-archive-location "%s_archive::"
3135 "The location where subtrees should be archived.
3137 The value of this variable is a string, consisting of two parts,
3138 separated by a double-colon. The first part is a filename and
3139 the second part is a headline.
3141 When the filename is omitted, archiving happens in the same file.
3142 %s in the filename will be replaced by the current file
3143 name (without the directory part). Archiving to a different file
3144 is useful to keep archived entries from contributing to the
3145 Org-mode Agenda.
3147 The archived entries will be filed as subtrees of the specified
3148 headline. When the headline is omitted, the subtrees are simply
3149 filed away at the end of the file, as top-level entries. Also in
3150 the heading you can use %s to represent the file name, this can be
3151 useful when using the same archive for a number of different files.
3153 Here are a few examples:
3154 \"%s_archive::\"
3155 If the current file is Projects.org, archive in file
3156 Projects.org_archive, as top-level trees. This is the default.
3158 \"::* Archived Tasks\"
3159 Archive in the current file, under the top-level headline
3160 \"* Archived Tasks\".
3162 \"~/org/archive.org::\"
3163 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3165 \"~/org/archive.org::From %s\"
3166 Archive in file ~/org/archive.org (absolute path), und headlines
3167 \"From FILENAME\" where file name is the current file name.
3169 \"basement::** Finished Tasks\"
3170 Archive in file ./basement (relative path), as level 3 trees
3171 below the level 2 heading \"** Finished Tasks\".
3173 You may set this option on a per-file basis by adding to the buffer a
3174 line like
3176 #+ARCHIVE: basement::** Finished Tasks
3178 You may also define it locally for a subtree by setting an ARCHIVE property
3179 in the entry. If such a property is found in an entry, or anywhere up
3180 the hierarchy, it will be used."
3181 :group 'org-archive
3182 :type 'string)
3184 (defcustom org-archive-tag "ARCHIVE"
3185 "The tag that marks a subtree as archived.
3186 An archived subtree does not open during visibility cycling, and does
3187 not contribute to the agenda listings.
3188 After changing this, font-lock must be restarted in the relevant buffers to
3189 get the proper fontification."
3190 :group 'org-archive
3191 :group 'org-keywords
3192 :type 'string)
3194 (defcustom org-agenda-skip-archived-trees t
3195 "Non-nil means, the agenda will skip any items located in archived trees.
3196 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3197 variable is no longer recommended, you should leave it at the value t.
3198 Instead, use the key `v' to cycle the archives-mode in the agenda."
3199 :group 'org-archive
3200 :group 'org-agenda-skip
3201 :type 'boolean)
3203 (defcustom org-columns-skip-arrchived-trees t
3204 "Non-nil means, irgnore archived trees when creating column view."
3205 :group 'org-archive
3206 :group 'org-properties
3207 :type 'boolean)
3209 (defcustom org-cycle-open-archived-trees nil
3210 "Non-nil means, `org-cycle' will open archived trees.
3211 An archived tree is a tree marked with the tag ARCHIVE.
3212 When nil, archived trees will stay folded. You can still open them with
3213 normal outline commands like `show-all', but not with the cycling commands."
3214 :group 'org-archive
3215 :group 'org-cycle
3216 :type 'boolean)
3218 (defcustom org-sparse-tree-open-archived-trees nil
3219 "Non-nil means sparse tree construction shows matches in archived trees.
3220 When nil, matches in these trees are highlighted, but the trees are kept in
3221 collapsed state."
3222 :group 'org-archive
3223 :group 'org-sparse-trees
3224 :type 'boolean)
3226 (defun org-cycle-hide-archived-subtrees (state)
3227 "Re-hide all archived subtrees after a visibility state change."
3228 (when (and (not org-cycle-open-archived-trees)
3229 (not (memq state '(overview folded))))
3230 (save-excursion
3231 (let* ((globalp (memq state '(contents all)))
3232 (beg (if globalp (point-min) (point)))
3233 (end (if globalp (point-max) (org-end-of-subtree t))))
3234 (org-hide-archived-subtrees beg end)
3235 (goto-char beg)
3236 (if (looking-at (concat ".*:" org-archive-tag ":"))
3237 (message "%s" (substitute-command-keys
3238 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3240 (defun org-force-cycle-archived ()
3241 "Cycle subtree even if it is archived."
3242 (interactive)
3243 (setq this-command 'org-cycle)
3244 (let ((org-cycle-open-archived-trees t))
3245 (call-interactively 'org-cycle)))
3247 (defun org-hide-archived-subtrees (beg end)
3248 "Re-hide all archived subtrees after a visibility state change."
3249 (save-excursion
3250 (let* ((re (concat ":" org-archive-tag ":")))
3251 (goto-char beg)
3252 (while (re-search-forward re end t)
3253 (and (org-on-heading-p) (hide-subtree))
3254 (org-end-of-subtree t)))))
3256 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3258 (eval-and-compile
3259 (org-autoload "org-archive"
3260 '(org-add-archive-files org-archive-subtree
3261 org-archive-to-archive-sibling org-toggle-archive-tag)))
3263 ;; Autoload Column View Code
3265 (declare-function org-columns-number-to-string "org-colview")
3266 (declare-function org-columns-get-format-and-top-level "org-colview")
3267 (declare-function org-columns-compute "org-colview")
3269 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3270 '(org-columns-number-to-string org-columns-get-format-and-top-level
3271 org-columns-compute org-agenda-columns org-columns-remove-overlays
3272 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3274 ;; Autoload ID code
3276 (declare-function org-id-store-link "org-id")
3277 (declare-function org-id-locations-load "org-id")
3278 (declare-function org-id-locations-save "org-id")
3279 (defvar org-id-track-globally)
3280 (org-autoload "org-id"
3281 '(org-id-get-create org-id-new org-id-copy org-id-get
3282 org-id-get-with-outline-path-completion
3283 org-id-get-with-outline-drilling
3284 org-id-goto org-id-find org-id-store-link))
3286 ;; Autoload Plotting Code
3288 (org-autoload "org-plot"
3289 '(org-plot/gnuplot))
3291 ;;; Variables for pre-computed regular expressions, all buffer local
3293 (defvar org-drawer-regexp nil
3294 "Matches first line of a hidden block.")
3295 (make-variable-buffer-local 'org-drawer-regexp)
3296 (defvar org-todo-regexp nil
3297 "Matches any of the TODO state keywords.")
3298 (make-variable-buffer-local 'org-todo-regexp)
3299 (defvar org-not-done-regexp nil
3300 "Matches any of the TODO state keywords except the last one.")
3301 (make-variable-buffer-local 'org-not-done-regexp)
3302 (defvar org-not-done-heading-regexp nil
3303 "Matches a TODO headline that is not done.")
3304 (make-variable-buffer-local 'org-not-done-regexp)
3305 (defvar org-todo-line-regexp nil
3306 "Matches a headline and puts TODO state into group 2 if present.")
3307 (make-variable-buffer-local 'org-todo-line-regexp)
3308 (defvar org-complex-heading-regexp nil
3309 "Matches a headline and puts everything into groups:
3310 group 1: the stars
3311 group 2: The todo keyword, maybe
3312 group 3: Priority cookie
3313 group 4: True headline
3314 group 5: Tags")
3315 (make-variable-buffer-local 'org-complex-heading-regexp)
3316 (defvar org-todo-line-tags-regexp nil
3317 "Matches a headline and puts TODO state into group 2 if present.
3318 Also put tags into group 4 if tags are present.")
3319 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3320 (defvar org-nl-done-regexp nil
3321 "Matches newline followed by a headline with the DONE keyword.")
3322 (make-variable-buffer-local 'org-nl-done-regexp)
3323 (defvar org-looking-at-done-regexp nil
3324 "Matches the DONE keyword a point.")
3325 (make-variable-buffer-local 'org-looking-at-done-regexp)
3326 (defvar org-ds-keyword-length 12
3327 "Maximum length of the Deadline and SCHEDULED keywords.")
3328 (make-variable-buffer-local 'org-ds-keyword-length)
3329 (defvar org-deadline-regexp nil
3330 "Matches the DEADLINE keyword.")
3331 (make-variable-buffer-local 'org-deadline-regexp)
3332 (defvar org-deadline-time-regexp nil
3333 "Matches the DEADLINE keyword together with a time stamp.")
3334 (make-variable-buffer-local 'org-deadline-time-regexp)
3335 (defvar org-deadline-line-regexp nil
3336 "Matches the DEADLINE keyword and the rest of the line.")
3337 (make-variable-buffer-local 'org-deadline-line-regexp)
3338 (defvar org-scheduled-regexp nil
3339 "Matches the SCHEDULED keyword.")
3340 (make-variable-buffer-local 'org-scheduled-regexp)
3341 (defvar org-scheduled-time-regexp nil
3342 "Matches the SCHEDULED keyword together with a time stamp.")
3343 (make-variable-buffer-local 'org-scheduled-time-regexp)
3344 (defvar org-closed-time-regexp nil
3345 "Matches the CLOSED keyword together with a time stamp.")
3346 (make-variable-buffer-local 'org-closed-time-regexp)
3348 (defvar org-keyword-time-regexp nil
3349 "Matches any of the 4 keywords, together with the time stamp.")
3350 (make-variable-buffer-local 'org-keyword-time-regexp)
3351 (defvar org-keyword-time-not-clock-regexp nil
3352 "Matches any of the 3 keywords, together with the time stamp.")
3353 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3354 (defvar org-maybe-keyword-time-regexp nil
3355 "Matches a timestamp, possibly preceeded by a keyword.")
3356 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3357 (defvar org-planning-or-clock-line-re nil
3358 "Matches a line with planning or clock info.")
3359 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3361 (defconst org-plain-time-of-day-regexp
3362 (concat
3363 "\\(\\<[012]?[0-9]"
3364 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3365 "\\(--?"
3366 "\\(\\<[012]?[0-9]"
3367 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3368 "\\)?")
3369 "Regular expression to match a plain time or time range.
3370 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3371 groups carry important information:
3372 0 the full match
3373 1 the first time, range or not
3374 8 the second time, if it is a range.")
3376 (defconst org-plain-time-extension-regexp
3377 (concat
3378 "\\(\\<[012]?[0-9]"
3379 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3380 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3381 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3382 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3383 groups carry important information:
3384 0 the full match
3385 7 hours of duration
3386 9 minutes of duration")
3388 (defconst org-stamp-time-of-day-regexp
3389 (concat
3390 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3391 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3392 "\\(--?"
3393 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3394 "Regular expression to match a timestamp time or time range.
3395 After a match, the following groups carry important information:
3396 0 the full match
3397 1 date plus weekday, for backreferencing to make sure both times on same day
3398 2 the first time, range or not
3399 4 the second time, if it is a range.")
3401 (defconst org-startup-options
3402 '(("fold" org-startup-folded t)
3403 ("overview" org-startup-folded t)
3404 ("nofold" org-startup-folded nil)
3405 ("showall" org-startup-folded nil)
3406 ("content" org-startup-folded content)
3407 ("hidestars" org-hide-leading-stars t)
3408 ("showstars" org-hide-leading-stars nil)
3409 ("odd" org-odd-levels-only t)
3410 ("oddeven" org-odd-levels-only nil)
3411 ("align" org-startup-align-all-tables t)
3412 ("noalign" org-startup-align-all-tables nil)
3413 ("customtime" org-display-custom-times t)
3414 ("logdone" org-log-done time)
3415 ("lognotedone" org-log-done note)
3416 ("nologdone" org-log-done nil)
3417 ("lognoteclock-out" org-log-note-clock-out t)
3418 ("nolognoteclock-out" org-log-note-clock-out nil)
3419 ("logrepeat" org-log-repeat state)
3420 ("lognoterepeat" org-log-repeat note)
3421 ("nologrepeat" org-log-repeat nil)
3422 ("fninline" org-footnote-define-inline t)
3423 ("nofninline" org-footnote-define-inline nil)
3424 ("fnlocal" org-footnote-section nil)
3425 ("fnauto" org-footnote-auto-label t)
3426 ("fnprompt" org-footnote-auto-label nil)
3427 ("fnconfirm" org-footnote-auto-label confirm)
3428 ("fnplain" org-footnote-auto-label plain)
3429 ("fnadjust" org-footnote-auto-adjust t)
3430 ("nofnadjust" org-footnote-auto-adjust nil)
3431 ("constcgs" constants-unit-system cgs)
3432 ("constSI" constants-unit-system SI)
3433 ("noptag" org-tag-persistent-alist nil)
3434 ("hideblocks" org-hide-block-startup t)
3435 ("nohideblocks" org-hide-block-startup nil))
3436 "Variable associated with STARTUP options for org-mode.
3437 Each element is a list of three items: The startup options as written
3438 in the #+STARTUP line, the corresponding variable, and the value to
3439 set this variable to if the option is found. An optional forth element PUSH
3440 means to push this value onto the list in the variable.")
3442 (defun org-set-regexps-and-options ()
3443 "Precompute regular expressions for current buffer."
3444 (when (org-mode-p)
3445 (org-set-local 'org-todo-kwd-alist nil)
3446 (org-set-local 'org-todo-key-alist nil)
3447 (org-set-local 'org-todo-key-trigger nil)
3448 (org-set-local 'org-todo-keywords-1 nil)
3449 (org-set-local 'org-done-keywords nil)
3450 (org-set-local 'org-todo-heads nil)
3451 (org-set-local 'org-todo-sets nil)
3452 (org-set-local 'org-todo-log-states nil)
3453 (org-set-local 'org-file-properties nil)
3454 (org-set-local 'org-file-tags nil)
3455 (let ((re (org-make-options-regexp
3456 '("CATEGORY" "TODO" "COLUMNS"
3457 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3458 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3459 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3460 (splitre "[ \t]+")
3461 kwds kws0 kwsa key log value cat arch tags const links hw dws
3462 tail sep kws1 prio props ftags drawers
3463 ext-setup-or-nil setup-contents (start 0))
3464 (save-excursion
3465 (save-restriction
3466 (widen)
3467 (goto-char (point-min))
3468 (while (or (and ext-setup-or-nil
3469 (string-match re ext-setup-or-nil start)
3470 (setq start (match-end 0)))
3471 (and (setq ext-setup-or-nil nil start 0)
3472 (re-search-forward re nil t)))
3473 (setq key (upcase (match-string 1 ext-setup-or-nil))
3474 value (org-match-string-no-properties 2 ext-setup-or-nil))
3475 (cond
3476 ((equal key "CATEGORY")
3477 (if (string-match "[ \t]+$" value)
3478 (setq value (replace-match "" t t value)))
3479 (setq cat value))
3480 ((member key '("SEQ_TODO" "TODO"))
3481 (push (cons 'sequence (org-split-string value splitre)) kwds))
3482 ((equal key "TYP_TODO")
3483 (push (cons 'type (org-split-string value splitre)) kwds))
3484 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3485 ;; general TODO-like setup
3486 (push (cons (intern (downcase (match-string 1 key)))
3487 (org-split-string value splitre)) kwds))
3488 ((equal key "TAGS")
3489 (setq tags (append tags (if tags '("\\n") nil)
3490 (org-split-string value splitre))))
3491 ((equal key "COLUMNS")
3492 (org-set-local 'org-columns-default-format value))
3493 ((equal key "LINK")
3494 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3495 (push (cons (match-string 1 value)
3496 (org-trim (match-string 2 value)))
3497 links)))
3498 ((equal key "PRIORITIES")
3499 (setq prio (org-split-string value " +")))
3500 ((equal key "PROPERTY")
3501 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3502 (push (cons (match-string 1 value) (match-string 2 value))
3503 props)))
3504 ((equal key "FILETAGS")
3505 (when (string-match "\\S-" value)
3506 (setq ftags
3507 (append
3508 ftags
3509 (apply 'append
3510 (mapcar (lambda (x) (org-split-string x ":"))
3511 (org-split-string value)))))))
3512 ((equal key "DRAWERS")
3513 (setq drawers (org-split-string value splitre)))
3514 ((equal key "CONSTANTS")
3515 (setq const (append const (org-split-string value splitre))))
3516 ((equal key "STARTUP")
3517 (let ((opts (org-split-string value splitre))
3518 l var val)
3519 (while (setq l (pop opts))
3520 (when (setq l (assoc l org-startup-options))
3521 (setq var (nth 1 l) val (nth 2 l))
3522 (if (not (nth 3 l))
3523 (set (make-local-variable var) val)
3524 (if (not (listp (symbol-value var)))
3525 (set (make-local-variable var) nil))
3526 (set (make-local-variable var) (symbol-value var))
3527 (add-to-list var val))))))
3528 ((equal key "ARCHIVE")
3529 (string-match " *$" value)
3530 (setq arch (replace-match "" t t value))
3531 (remove-text-properties 0 (length arch)
3532 '(face t fontified t) arch))
3533 ((equal key "SETUPFILE")
3534 (setq setup-contents (org-file-contents
3535 (expand-file-name
3536 (org-remove-double-quotes value))
3537 'noerror))
3538 (if (not ext-setup-or-nil)
3539 (setq ext-setup-or-nil setup-contents start 0)
3540 (setq ext-setup-or-nil
3541 (concat (substring ext-setup-or-nil 0 start)
3542 "\n" setup-contents "\n"
3543 (substring ext-setup-or-nil start)))))
3544 ))))
3545 (when cat
3546 (org-set-local 'org-category (intern cat))
3547 (push (cons "CATEGORY" cat) props))
3548 (when prio
3549 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3550 (setq prio (mapcar 'string-to-char prio))
3551 (org-set-local 'org-highest-priority (nth 0 prio))
3552 (org-set-local 'org-lowest-priority (nth 1 prio))
3553 (org-set-local 'org-default-priority (nth 2 prio)))
3554 (and props (org-set-local 'org-file-properties (nreverse props)))
3555 (and ftags (org-set-local 'org-file-tags
3556 (mapcar 'org-add-prop-inherited ftags)))
3557 (and drawers (org-set-local 'org-drawers drawers))
3558 (and arch (org-set-local 'org-archive-location arch))
3559 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3560 ;; Process the TODO keywords
3561 (unless kwds
3562 ;; Use the global values as if they had been given locally.
3563 (setq kwds (default-value 'org-todo-keywords))
3564 (if (stringp (car kwds))
3565 (setq kwds (list (cons org-todo-interpretation
3566 (default-value 'org-todo-keywords)))))
3567 (setq kwds (reverse kwds)))
3568 (setq kwds (nreverse kwds))
3569 (let (inter kws kw)
3570 (while (setq kws (pop kwds))
3571 (let ((kws (or
3572 (run-hook-with-args-until-success
3573 'org-todo-setup-filter-hook kws)
3574 kws)))
3575 (setq inter (pop kws) sep (member "|" kws)
3576 kws0 (delete "|" (copy-sequence kws))
3577 kwsa nil
3578 kws1 (mapcar
3579 (lambda (x)
3580 ;; 1 2
3581 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3582 (progn
3583 (setq kw (match-string 1 x)
3584 key (and (match-end 2) (match-string 2 x))
3585 log (org-extract-log-state-settings x))
3586 (push (cons kw (and key (string-to-char key))) kwsa)
3587 (and log (push log org-todo-log-states))
3589 (error "Invalid TODO keyword %s" x)))
3590 kws0)
3591 kwsa (if kwsa (append '((:startgroup))
3592 (nreverse kwsa)
3593 '((:endgroup))))
3594 hw (car kws1)
3595 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3596 tail (list inter hw (car dws) (org-last dws))))
3597 (add-to-list 'org-todo-heads hw 'append)
3598 (push kws1 org-todo-sets)
3599 (setq org-done-keywords (append org-done-keywords dws nil))
3600 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3601 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3602 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3603 (setq org-todo-sets (nreverse org-todo-sets)
3604 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3605 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3606 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3607 ;; Process the constants
3608 (when const
3609 (let (e cst)
3610 (while (setq e (pop const))
3611 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3612 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3613 (setq org-table-formula-constants-local cst)))
3615 ;; Process the tags.
3616 (when tags
3617 (let (e tgs)
3618 (while (setq e (pop tags))
3619 (cond
3620 ((equal e "{") (push '(:startgroup) tgs))
3621 ((equal e "}") (push '(:endgroup) tgs))
3622 ((equal e "\\n") (push '(:newline) tgs))
3623 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3624 (push (cons (match-string 1 e)
3625 (string-to-char (match-string 2 e)))
3626 tgs))
3627 (t (push (list e) tgs))))
3628 (org-set-local 'org-tag-alist nil)
3629 (while (setq e (pop tgs))
3630 (or (and (stringp (car e))
3631 (assoc (car e) org-tag-alist))
3632 (push e org-tag-alist)))))
3634 ;; Compute the regular expressions and other local variables
3635 (if (not org-done-keywords)
3636 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3637 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3638 (length org-scheduled-string)
3639 (length org-clock-string)
3640 (length org-closed-string)))
3641 org-drawer-regexp
3642 (concat "^[ \t]*:\\("
3643 (mapconcat 'regexp-quote org-drawers "\\|")
3644 "\\):[ \t]*$")
3645 org-not-done-keywords
3646 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3647 org-todo-regexp
3648 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3649 "\\|") "\\)\\>")
3650 org-not-done-regexp
3651 (concat "\\<\\("
3652 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3653 "\\)\\>")
3654 org-not-done-heading-regexp
3655 (concat "^\\(\\*+\\)[ \t]+\\("
3656 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3657 "\\)\\>")
3658 org-todo-line-regexp
3659 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3660 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3661 "\\)\\>\\)?[ \t]*\\(.*\\)")
3662 org-complex-heading-regexp
3663 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3664 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3665 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3666 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3667 org-nl-done-regexp
3668 (concat "\n\\*+[ \t]+"
3669 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3670 "\\)" "\\>")
3671 org-todo-line-tags-regexp
3672 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3673 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3674 (org-re
3675 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3676 org-looking-at-done-regexp
3677 (concat "^" "\\(?:"
3678 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3679 "\\>")
3680 org-deadline-regexp (concat "\\<" org-deadline-string)
3681 org-deadline-time-regexp
3682 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3683 org-deadline-line-regexp
3684 (concat "\\<\\(" org-deadline-string "\\).*")
3685 org-scheduled-regexp
3686 (concat "\\<" org-scheduled-string)
3687 org-scheduled-time-regexp
3688 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3689 org-closed-time-regexp
3690 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3691 org-keyword-time-regexp
3692 (concat "\\<\\(" org-scheduled-string
3693 "\\|" org-deadline-string
3694 "\\|" org-closed-string
3695 "\\|" org-clock-string "\\)"
3696 " *[[<]\\([^]>]+\\)[]>]")
3697 org-keyword-time-not-clock-regexp
3698 (concat "\\<\\(" org-scheduled-string
3699 "\\|" org-deadline-string
3700 "\\|" org-closed-string
3701 "\\)"
3702 " *[[<]\\([^]>]+\\)[]>]")
3703 org-maybe-keyword-time-regexp
3704 (concat "\\(\\<\\(" org-scheduled-string
3705 "\\|" org-deadline-string
3706 "\\|" org-closed-string
3707 "\\|" org-clock-string "\\)\\)?"
3708 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3709 org-planning-or-clock-line-re
3710 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3711 "\\|" org-deadline-string
3712 "\\|" org-closed-string "\\|" org-clock-string
3713 "\\)\\>\\)")
3715 (org-compute-latex-and-specials-regexp)
3716 (org-set-font-lock-defaults))))
3718 (defun org-file-contents (file &optional noerror)
3719 "Return the contents of FILE, as a string."
3720 (if (or (not file)
3721 (not (file-readable-p file)))
3722 (if noerror
3723 (progn
3724 (message "Cannot read file %s" file)
3725 (ding) (sit-for 2)
3727 (error "Cannot read file %s" file))
3728 (with-temp-buffer
3729 (insert-file-contents file)
3730 (buffer-string))))
3732 (defun org-extract-log-state-settings (x)
3733 "Extract the log state setting from a TODO keyword string.
3734 This will extract info from a string like \"WAIT(w@/!)\"."
3735 (let (kw key log1 log2)
3736 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3737 (setq kw (match-string 1 x)
3738 key (and (match-end 2) (match-string 2 x))
3739 log1 (and (match-end 3) (match-string 3 x))
3740 log2 (and (match-end 4) (match-string 4 x)))
3741 (and (or log1 log2)
3742 (list kw
3743 (and log1 (if (equal log1 "!") 'time 'note))
3744 (and log2 (if (equal log2 "!") 'time 'note)))))))
3746 (defun org-remove-keyword-keys (list)
3747 "Remove a pair of parenthesis at the end of each string in LIST."
3748 (mapcar (lambda (x)
3749 (if (string-match "(.*)$" x)
3750 (substring x 0 (match-beginning 0))
3752 list))
3754 ;; FIXME: this could be done much better, using second characters etc.
3755 (defun org-assign-fast-keys (alist)
3756 "Assign fast keys to a keyword-key alist.
3757 Respect keys that are already there."
3758 (let (new e k c c1 c2 (char ?a))
3759 (while (setq e (pop alist))
3760 (cond
3761 ((equal e '(:startgroup)) (push e new))
3762 ((equal e '(:endgroup)) (push e new))
3763 ((equal e '(:newline)) (push e new))
3765 (setq k (car e) c2 nil)
3766 (if (cdr e)
3767 (setq c (cdr e))
3768 ;; automatically assign a character.
3769 (setq c1 (string-to-char
3770 (downcase (substring
3771 k (if (= (string-to-char k) ?@) 1 0)))))
3772 (if (or (rassoc c1 new) (rassoc c1 alist))
3773 (while (or (rassoc char new) (rassoc char alist))
3774 (setq char (1+ char)))
3775 (setq c2 c1))
3776 (setq c (or c2 char)))
3777 (push (cons k c) new))))
3778 (nreverse new)))
3780 ;;; Some variables used in various places
3782 (defvar org-window-configuration nil
3783 "Used in various places to store a window configuration.")
3784 (defvar org-finish-function nil
3785 "Function to be called when `C-c C-c' is used.
3786 This is for getting out of special buffers like remember.")
3789 ;; FIXME: Occasionally check by commenting these, to make sure
3790 ;; no other functions uses these, forgetting to let-bind them.
3791 (defvar entry)
3792 (defvar last-state)
3793 (defvar date)
3795 ;; Defined somewhere in this file, but used before definition.
3796 (defvar org-html-entities)
3797 (defvar org-struct-menu)
3798 (defvar org-org-menu)
3799 (defvar org-tbl-menu)
3800 (defvar org-agenda-keymap)
3802 ;;;; Define the Org-mode
3804 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3805 (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."))
3808 ;; We use a before-change function to check if a table might need
3809 ;; an update.
3810 (defvar org-table-may-need-update t
3811 "Indicates that a table might need an update.
3812 This variable is set by `org-before-change-function'.
3813 `org-table-align' sets it back to nil.")
3814 (defun org-before-change-function (beg end)
3815 "Every change indicates that a table might need an update."
3816 (setq org-table-may-need-update t))
3817 (defvar org-mode-map)
3818 (defvar org-mode-hook nil
3819 "Mode hook for Org-mode, run after the mode was turned on.")
3820 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3821 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3822 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
3823 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
3824 (defvar org-table-buffer-is-an nil)
3825 (defconst org-outline-regexp "\\*+ ")
3827 ;;;###autoload
3828 (define-derived-mode org-mode outline-mode "Org"
3829 "Outline-based notes management and organizer, alias
3830 \"Carsten's outline-mode for keeping track of everything.\"
3832 Org-mode develops organizational tasks around a NOTES file which
3833 contains information about projects as plain text. Org-mode is
3834 implemented on top of outline-mode, which is ideal to keep the content
3835 of large files well structured. It supports ToDo items, deadlines and
3836 time stamps, which magically appear in the diary listing of the Emacs
3837 calendar. Tables are easily created with a built-in table editor.
3838 Plain text URL-like links connect to websites, emails (VM), Usenet
3839 messages (Gnus), BBDB entries, and any files related to the project.
3840 For printing and sharing of notes, an Org-mode file (or a part of it)
3841 can be exported as a structured ASCII or HTML file.
3843 The following commands are available:
3845 \\{org-mode-map}"
3847 ;; Get rid of Outline menus, they are not needed
3848 ;; Need to do this here because define-derived-mode sets up
3849 ;; the keymap so late. Still, it is a waste to call this each time
3850 ;; we switch another buffer into org-mode.
3851 (if (featurep 'xemacs)
3852 (when (boundp 'outline-mode-menu-heading)
3853 ;; Assume this is Greg's port, it used easymenu
3854 (easy-menu-remove outline-mode-menu-heading)
3855 (easy-menu-remove outline-mode-menu-show)
3856 (easy-menu-remove outline-mode-menu-hide))
3857 (define-key org-mode-map [menu-bar headings] 'undefined)
3858 (define-key org-mode-map [menu-bar hide] 'undefined)
3859 (define-key org-mode-map [menu-bar show] 'undefined))
3861 (org-load-modules-maybe)
3862 (easy-menu-add org-org-menu)
3863 (easy-menu-add org-tbl-menu)
3864 (org-install-agenda-files-menu)
3865 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3866 (org-add-to-invisibility-spec '(org-cwidth))
3867 (org-add-to-invisibility-spec '(org-hide-block . t))
3868 (when (featurep 'xemacs)
3869 (org-set-local 'line-move-ignore-invisible t))
3870 (org-set-local 'outline-regexp org-outline-regexp)
3871 (org-set-local 'outline-level 'org-outline-level)
3872 (when (and org-ellipsis
3873 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3874 (fboundp 'make-glyph-code))
3875 (unless org-display-table
3876 (setq org-display-table (make-display-table)))
3877 (set-display-table-slot
3878 org-display-table 4
3879 (vconcat (mapcar
3880 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3881 org-ellipsis)))
3882 (if (stringp org-ellipsis) org-ellipsis "..."))))
3883 (setq buffer-display-table org-display-table))
3884 (org-set-regexps-and-options)
3885 (when (and org-tag-faces (not org-tags-special-faces-re))
3886 ;; tag faces set outside customize.... force initialization.
3887 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3888 ;; Calc embedded
3889 (org-set-local 'calc-embedded-open-mode "# ")
3890 (modify-syntax-entry ?# "<")
3891 (modify-syntax-entry ?@ "w")
3892 (if org-startup-truncated (setq truncate-lines t))
3893 (org-set-local 'font-lock-unfontify-region-function
3894 'org-unfontify-region)
3895 ;; Activate before-change-function
3896 (org-set-local 'org-table-may-need-update t)
3897 (org-add-hook 'before-change-functions 'org-before-change-function nil
3898 'local)
3899 ;; Check for running clock before killing a buffer
3900 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3901 ;; Paragraphs and auto-filling
3902 (org-set-autofill-regexps)
3903 (setq indent-line-function 'org-indent-line-function)
3904 (org-update-radio-target-regexp)
3905 ;; Make sure dependence stuff works reliably, even for users who set it
3906 ;; too late :-(
3907 (if org-enforce-todo-dependencies
3908 (add-hook 'org-blocker-hook
3909 'org-block-todo-from-children-or-siblings-or-parent)
3910 (remove-hook 'org-blocker-hook
3911 'org-block-todo-from-children-or-siblings-or-parent))
3912 (if org-enforce-todo-checkbox-dependencies
3913 (add-hook 'org-blocker-hook
3914 'org-block-todo-from-checkboxes)
3915 (remove-hook 'org-blocker-hook
3916 'org-block-todo-from-checkboxes))
3918 ;; Comment characters
3919 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3920 (org-set-local 'comment-padding " ")
3922 ;; Align options lines
3923 (org-set-local
3924 'align-mode-rules-list
3925 '((org-in-buffer-settings
3926 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3927 (modes . '(org-mode)))))
3929 ;; Imenu
3930 (org-set-local 'imenu-create-index-function
3931 'org-imenu-get-tree)
3933 ;; Make isearch reveal context
3934 (if (or (featurep 'xemacs)
3935 (not (boundp 'outline-isearch-open-invisible-function)))
3936 ;; Emacs 21 and XEmacs make use of the hook
3937 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3938 ;; Emacs 22 deals with this through a special variable
3939 (org-set-local 'outline-isearch-open-invisible-function
3940 (lambda (&rest ignore) (org-show-context 'isearch))))
3942 ;; If empty file that did not turn on org-mode automatically, make it to.
3943 (if (and org-insert-mode-line-in-empty-file
3944 (interactive-p)
3945 (= (point-min) (point-max)))
3946 (insert "# -*- mode: org -*-\n\n"))
3948 (unless org-inhibit-startup
3949 (when org-startup-align-all-tables
3950 (let ((bmp (buffer-modified-p)))
3951 (org-table-map-tables 'org-table-align)
3952 (set-buffer-modified-p bmp)))
3953 (org-set-startup-visibility)))
3955 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3957 (defun org-current-time ()
3958 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3959 (if (> (car org-time-stamp-rounding-minutes) 1)
3960 (let ((r (car org-time-stamp-rounding-minutes))
3961 (time (decode-time)))
3962 (apply 'encode-time
3963 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3964 (nthcdr 2 time))))
3965 (current-time)))
3967 ;;;; Font-Lock stuff, including the activators
3969 (defvar org-mouse-map (make-sparse-keymap))
3970 (org-defkey org-mouse-map
3971 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3972 (org-defkey org-mouse-map
3973 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3974 (when org-mouse-1-follows-link
3975 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3976 (when org-tab-follows-link
3977 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3978 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3980 (require 'font-lock)
3982 (defconst org-non-link-chars "]\t\n\r<>")
3983 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3984 "shell" "elisp"))
3985 (defvar org-link-types-re nil
3986 "Matches a link that has a url-like prefix like \"http:\"")
3987 (defvar org-link-re-with-space nil
3988 "Matches a link with spaces, optional angular brackets around it.")
3989 (defvar org-link-re-with-space2 nil
3990 "Matches a link with spaces, optional angular brackets around it.")
3991 (defvar org-link-re-with-space3 nil
3992 "Matches a link with spaces, only for internal part in bracket links.")
3993 (defvar org-angle-link-re nil
3994 "Matches link with angular brackets, spaces are allowed.")
3995 (defvar org-plain-link-re nil
3996 "Matches plain link, without spaces.")
3997 (defvar org-bracket-link-regexp nil
3998 "Matches a link in double brackets.")
3999 (defvar org-bracket-link-analytic-regexp nil
4000 "Regular expression used to analyze links.
4001 Here is what the match groups contain after a match:
4002 1: http:
4003 2: http
4004 3: path
4005 4: [desc]
4006 5: desc")
4007 (defvar org-bracket-link-analytic-regexp++ nil
4008 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4009 (defvar org-any-link-re nil
4010 "Regular expression matching any link.")
4012 (defun org-make-link-regexps ()
4013 "Update the link regular expressions.
4014 This should be called after the variable `org-link-types' has changed."
4015 (setq org-link-types-re
4016 (concat
4017 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4018 org-link-re-with-space
4019 (concat
4020 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4021 "\\([^" org-non-link-chars " ]"
4022 "[^" org-non-link-chars "]*"
4023 "[^" org-non-link-chars " ]\\)>?")
4024 org-link-re-with-space2
4025 (concat
4026 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4027 "\\([^" org-non-link-chars " ]"
4028 "[^\t\n\r]*"
4029 "[^" org-non-link-chars " ]\\)>?")
4030 org-link-re-with-space3
4031 (concat
4032 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4033 "\\([^" org-non-link-chars " ]"
4034 "[^\t\n\r]*\\)")
4035 org-angle-link-re
4036 (concat
4037 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4038 "\\([^" org-non-link-chars " ]"
4039 "[^" org-non-link-chars "]*"
4040 "\\)>")
4041 org-plain-link-re
4042 (concat
4043 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4044 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4045 org-bracket-link-regexp
4046 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4047 org-bracket-link-analytic-regexp
4048 (concat
4049 "\\[\\["
4050 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4051 "\\([^]]+\\)"
4052 "\\]"
4053 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4054 "\\]")
4055 org-bracket-link-analytic-regexp++
4056 (concat
4057 "\\[\\["
4058 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4059 "\\([^]]+\\)"
4060 "\\]"
4061 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4062 "\\]")
4063 org-any-link-re
4064 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4065 org-angle-link-re "\\)\\|\\("
4066 org-plain-link-re "\\)")))
4068 (org-make-link-regexps)
4070 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4071 "Regular expression for fast time stamp matching.")
4072 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4073 "Regular expression for fast time stamp matching.")
4074 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4075 "Regular expression matching time strings for analysis.
4076 This one does not require the space after the date, so it can be used
4077 on a string that terminates immediately after the date.")
4078 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4079 "Regular expression matching time strings for analysis.")
4080 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4081 "Regular expression matching time stamps, with groups.")
4082 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4083 "Regular expression matching time stamps (also [..]), with groups.")
4084 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4085 "Regular expression matching a time stamp range.")
4086 (defconst org-tr-regexp-both
4087 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4088 "Regular expression matching a time stamp range.")
4089 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4090 org-ts-regexp "\\)?")
4091 "Regular expression matching a time stamp or time stamp range.")
4092 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4093 org-ts-regexp-both "\\)?")
4094 "Regular expression matching a time stamp or time stamp range.
4095 The time stamps may be either active or inactive.")
4097 (defvar org-emph-face nil)
4099 (defun org-do-emphasis-faces (limit)
4100 "Run through the buffer and add overlays to links."
4101 (let (rtn a)
4102 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4103 (if (not (= (char-after (match-beginning 3))
4104 (char-after (match-beginning 4))))
4105 (progn
4106 (setq rtn t)
4107 (setq a (assoc (match-string 3) org-emphasis-alist))
4108 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4109 'face
4110 (nth 1 a))
4111 (and (nth 4 a)
4112 (org-remove-flyspell-overlays-in
4113 (match-beginning 0) (match-end 0)))
4114 (add-text-properties (match-beginning 2) (match-end 2)
4115 '(font-lock-multiline t))
4116 (when org-hide-emphasis-markers
4117 (add-text-properties (match-end 4) (match-beginning 5)
4118 '(invisible org-link))
4119 (add-text-properties (match-beginning 3) (match-end 3)
4120 '(invisible org-link)))))
4121 (backward-char 1))
4122 rtn))
4124 (defun org-emphasize (&optional char)
4125 "Insert or change an emphasis, i.e. a font like bold or italic.
4126 If there is an active region, change that region to a new emphasis.
4127 If there is no region, just insert the marker characters and position
4128 the cursor between them.
4129 CHAR should be either the marker character, or the first character of the
4130 HTML tag associated with that emphasis. If CHAR is a space, the means
4131 to remove the emphasis of the selected region.
4132 If char is not given (for example in an interactive call) it
4133 will be prompted for."
4134 (interactive)
4135 (let ((eal org-emphasis-alist) e det
4136 (erc org-emphasis-regexp-components)
4137 (prompt "")
4138 (string "") beg end move tag c s)
4139 (if (org-region-active-p)
4140 (setq beg (region-beginning) end (region-end)
4141 string (buffer-substring beg end))
4142 (setq move t))
4144 (while (setq e (pop eal))
4145 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4146 c (aref tag 0))
4147 (push (cons c (string-to-char (car e))) det)
4148 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4149 (substring tag 1)))))
4150 (setq det (nreverse det))
4151 (unless char
4152 (message "%s" (concat "Emphasis marker or tag:" prompt))
4153 (setq char (read-char-exclusive)))
4154 (setq char (or (cdr (assoc char det)) char))
4155 (if (equal char ?\ )
4156 (setq s "" move nil)
4157 (unless (assoc (char-to-string char) org-emphasis-alist)
4158 (error "No such emphasis marker: \"%c\"" char))
4159 (setq s (char-to-string char)))
4160 (while (and (> (length string) 1)
4161 (equal (substring string 0 1) (substring string -1))
4162 (assoc (substring string 0 1) org-emphasis-alist))
4163 (setq string (substring string 1 -1)))
4164 (setq string (concat s string s))
4165 (if beg (delete-region beg end))
4166 (unless (or (bolp)
4167 (string-match (concat "[" (nth 0 erc) "\n]")
4168 (char-to-string (char-before (point)))))
4169 (insert " "))
4170 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4171 (char-to-string (char-after (point))))
4172 (insert " ") (backward-char 1))
4173 (insert string)
4174 (and move (backward-char 1))))
4176 (defconst org-nonsticky-props
4177 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4179 (defsubst org-rear-nonsticky-at (pos)
4180 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4182 (defun org-activate-plain-links (limit)
4183 "Run through the buffer and add overlays to links."
4184 (catch 'exit
4185 (let (f)
4186 (while (re-search-forward org-plain-link-re limit t)
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 (throw 'exit t))))))
4198 (defun org-activate-code (limit)
4199 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4200 (progn
4201 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4202 (remove-text-properties (match-beginning 0) (match-end 0)
4203 '(display t invisible t intangible t))
4204 t)))
4206 (defun org-fontify-meta-lines-and-blocks (limit)
4207 "Fontify #+ lines and blocks, in the correct ways."
4208 (let ((case-fold-search t))
4209 (if (re-search-forward
4210 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4211 limit t)
4212 (let ((beg (match-beginning 0))
4213 (beg1 (line-beginning-position 2))
4214 (dc1 (downcase (match-string 2)))
4215 (dc3 (downcase (match-string 3)))
4216 end end1 quoting)
4217 (cond
4218 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4219 ;; a single line of backend-specific content
4220 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4221 (remove-text-properties (match-beginning 0) (match-end 0)
4222 '(display t invisible t intangible t))
4223 (add-text-properties (match-beginning 1) (match-end 3)
4224 '(font-lock-fontified t face org-meta-line))
4225 (add-text-properties (match-beginning 6) (match-end 6)
4226 '(font-lock-fontified t face org-block))
4228 ((and (match-end 4) (equal dc3 "begin"))
4229 ;; Truely a block
4230 (setq quoting (member (downcase (match-string 5))
4231 org-protecting-blocks))
4232 (when (re-search-forward
4233 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4234 nil t) ;; on purpose, we look further than LIMIT
4235 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4236 (when quoting
4237 (remove-text-properties beg end
4238 '(display t invisible t intangible t)))
4239 (add-text-properties
4240 beg end
4241 '(font-lock-fontified t font-lock-multiline t))
4242 (add-text-properties beg beg1 '(face org-meta-line))
4243 (add-text-properties end1 end '(face org-meta-line))
4244 (when quoting
4245 (add-text-properties beg1 end1 '(face org-block)))
4247 ((not (member (char-after beg) '(?\ ?\t)))
4248 ;; just any other in-buffer setting, but not indented
4249 (add-text-properties
4250 beg (match-end 0)
4251 '(font-lock-fontified t face org-meta-line))
4253 ((or (member dc1 '("caption:" "label:" "orgtbl:" "tblfm:" "tblname:"))
4254 (and (match-end 4) (equal dc3 "attr")))
4255 (add-text-properties
4256 beg (match-end 0)
4257 '(font-lock-fontified t face org-meta-line))
4259 (t nil))))))
4261 (defun org-activate-angle-links (limit)
4262 "Run through the buffer and add overlays to links."
4263 (if (re-search-forward org-angle-link-re limit t)
4264 (progn
4265 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4266 (add-text-properties (match-beginning 0) (match-end 0)
4267 (list 'mouse-face 'highlight
4268 'keymap org-mouse-map))
4269 (org-rear-nonsticky-at (match-end 0))
4270 t)))
4272 (defun org-activate-footnote-links (limit)
4273 "Run through the buffer and add overlays to links."
4274 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4275 limit t)
4276 (progn
4277 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4278 (add-text-properties (match-beginning 2) (match-end 2)
4279 (list 'mouse-face 'highlight
4280 'keymap org-mouse-map
4281 'help-echo
4282 (if (= (point-at-bol) (match-beginning 2))
4283 "Footnote definition"
4284 "Footnote reference")
4286 (org-rear-nonsticky-at (match-end 2))
4287 t)))
4289 (defun org-activate-bracket-links (limit)
4290 "Run through the buffer and add overlays to bracketed links."
4291 (if (re-search-forward org-bracket-link-regexp limit t)
4292 (let* ((help (concat "LINK: "
4293 (org-match-string-no-properties 1)))
4294 ;; FIXME: above we should remove the escapes.
4295 ;; but that requires another match, protecting match data,
4296 ;; a lot of overhead for font-lock.
4297 (ip (org-maybe-intangible
4298 (list 'invisible 'org-link
4299 'keymap org-mouse-map 'mouse-face 'highlight
4300 'font-lock-multiline t 'help-echo help)))
4301 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4302 'font-lock-multiline t 'help-echo help)))
4303 ;; We need to remove the invisible property here. Table narrowing
4304 ;; may have made some of this invisible.
4305 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4306 (remove-text-properties (match-beginning 0) (match-end 0)
4307 '(invisible nil))
4308 (if (match-end 3)
4309 (progn
4310 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4311 (org-rear-nonsticky-at (match-beginning 3))
4312 (add-text-properties (match-beginning 3) (match-end 3) vp)
4313 (org-rear-nonsticky-at (match-end 3))
4314 (add-text-properties (match-end 3) (match-end 0) ip)
4315 (org-rear-nonsticky-at (match-end 0)))
4316 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4317 (org-rear-nonsticky-at (match-beginning 1))
4318 (add-text-properties (match-beginning 1) (match-end 1) vp)
4319 (org-rear-nonsticky-at (match-end 1))
4320 (add-text-properties (match-end 1) (match-end 0) ip)
4321 (org-rear-nonsticky-at (match-end 0)))
4322 t)))
4324 (defun org-activate-dates (limit)
4325 "Run through the buffer and add overlays to dates."
4326 (if (re-search-forward org-tsr-regexp-both limit t)
4327 (progn
4328 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4329 (add-text-properties (match-beginning 0) (match-end 0)
4330 (list 'mouse-face 'highlight
4331 'keymap org-mouse-map))
4332 (org-rear-nonsticky-at (match-end 0))
4333 (when org-display-custom-times
4334 (if (match-end 3)
4335 (org-display-custom-time (match-beginning 3) (match-end 3)))
4336 (org-display-custom-time (match-beginning 1) (match-end 1)))
4337 t)))
4339 (defvar org-target-link-regexp nil
4340 "Regular expression matching radio targets in plain text.")
4341 (make-variable-buffer-local 'org-target-link-regexp)
4342 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4343 "Regular expression matching a link target.")
4344 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4345 "Regular expression matching a radio target.")
4346 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4347 "Regular expression matching any target.")
4349 (defun org-activate-target-links (limit)
4350 "Run through the buffer and add overlays to target matches."
4351 (when org-target-link-regexp
4352 (let ((case-fold-search t))
4353 (if (re-search-forward org-target-link-regexp limit t)
4354 (progn
4355 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4356 (add-text-properties (match-beginning 0) (match-end 0)
4357 (list 'mouse-face 'highlight
4358 'keymap org-mouse-map
4359 'help-echo "Radio target link"
4360 'org-linked-text t))
4361 (org-rear-nonsticky-at (match-end 0))
4362 t)))))
4364 (defun org-update-radio-target-regexp ()
4365 "Find all radio targets in this file and update the regular expression."
4366 (interactive)
4367 (when (memq 'radio org-activate-links)
4368 (setq org-target-link-regexp
4369 (org-make-target-link-regexp (org-all-targets 'radio)))
4370 (org-restart-font-lock)))
4372 (defun org-hide-wide-columns (limit)
4373 (let (s e)
4374 (setq s (text-property-any (point) (or limit (point-max))
4375 'org-cwidth t))
4376 (when s
4377 (setq e (next-single-property-change s 'org-cwidth))
4378 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4379 (goto-char e)
4380 t)))
4382 (defvar org-latex-and-specials-regexp nil
4383 "Regular expression for highlighting export special stuff.")
4384 (defvar org-match-substring-regexp)
4385 (defvar org-match-substring-with-braces-regexp)
4386 (defvar org-export-html-special-string-regexps)
4388 (defun org-compute-latex-and-specials-regexp ()
4389 "Compute regular expression for stuff treated specially by exporters."
4390 (if (not org-highlight-latex-fragments-and-specials)
4391 (org-set-local 'org-latex-and-specials-regexp nil)
4392 (require 'org-exp)
4393 (let*
4394 ((matchers (plist-get org-format-latex-options :matchers))
4395 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4396 org-latex-regexps)))
4397 (options (org-combine-plists (org-default-export-plist)
4398 (org-infile-export-plist)))
4399 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4400 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4401 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4402 (org-export-html-expand (plist-get options :expand-quoted-html))
4403 (org-export-with-special-strings (plist-get options :special-strings))
4404 (re-sub
4405 (cond
4406 ((equal org-export-with-sub-superscripts '{})
4407 (list org-match-substring-with-braces-regexp))
4408 (org-export-with-sub-superscripts
4409 (list org-match-substring-regexp))
4410 (t nil)))
4411 (re-latex
4412 (if org-export-with-LaTeX-fragments
4413 (mapcar (lambda (x) (nth 1 x)) latexs)))
4414 (re-macros
4415 (if org-export-with-TeX-macros
4416 (list (concat "\\\\"
4417 (regexp-opt
4418 (append (mapcar 'car org-html-entities)
4419 (if (boundp 'org-latex-entities)
4420 (mapcar (lambda (x)
4421 (or (car-safe x) x))
4422 org-latex-entities)
4423 nil))
4424 'words))) ; FIXME
4426 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4427 (re-special (if org-export-with-special-strings
4428 (mapcar (lambda (x) (car x))
4429 org-export-html-special-string-regexps)))
4430 (re-rest
4431 (delq nil
4432 (list
4433 (if org-export-html-expand "@<[^>\n]+>")
4434 ))))
4435 (org-set-local
4436 'org-latex-and-specials-regexp
4437 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4438 re-rest) "\\|")))))
4440 (defun org-do-latex-and-special-faces (limit)
4441 "Run through the buffer and add overlays to links."
4442 (when org-latex-and-specials-regexp
4443 (let (rtn d)
4444 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4445 limit t))
4446 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4447 'face))
4448 '(org-code org-verbatim underline)))
4449 (progn
4450 (setq rtn t
4451 d (cond ((member (char-after (1+ (match-beginning 0)))
4452 '(?_ ?^)) 1)
4453 (t 0)))
4454 (font-lock-prepend-text-property
4455 (+ d (match-beginning 0)) (match-end 0)
4456 'face 'org-latex-and-export-specials)
4457 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4458 '(font-lock-multiline t)))))
4459 rtn)))
4461 (defun org-restart-font-lock ()
4462 "Restart font-lock-mode, to force refontification."
4463 (when (and (boundp 'font-lock-mode) font-lock-mode)
4464 (font-lock-mode -1)
4465 (font-lock-mode 1)))
4467 (defun org-all-targets (&optional radio)
4468 "Return a list of all targets in this file.
4469 With optional argument RADIO, only find radio targets."
4470 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4471 rtn)
4472 (save-excursion
4473 (goto-char (point-min))
4474 (while (re-search-forward re nil t)
4475 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4476 rtn)))
4478 (defun org-make-target-link-regexp (targets)
4479 "Make regular expression matching all strings in TARGETS.
4480 The regular expression finds the targets also if there is a line break
4481 between words."
4482 (and targets
4483 (concat
4484 "\\<\\("
4485 (mapconcat
4486 (lambda (x)
4487 (while (string-match " +" x)
4488 (setq x (replace-match "\\s-+" t t x)))
4490 targets
4491 "\\|")
4492 "\\)\\>")))
4494 (defun org-activate-tags (limit)
4495 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4496 (progn
4497 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4498 (add-text-properties (match-beginning 1) (match-end 1)
4499 (list 'mouse-face 'highlight
4500 'keymap org-mouse-map))
4501 (org-rear-nonsticky-at (match-end 1))
4502 t)))
4504 (defun org-outline-level ()
4505 (save-excursion
4506 (looking-at outline-regexp)
4507 (if (match-beginning 1)
4508 (+ (org-get-string-indentation (match-string 1)) 1000)
4509 (1- (- (match-end 0) (match-beginning 0))))))
4511 (defvar org-font-lock-keywords nil)
4513 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4514 "Regular expression matching a property line.")
4516 (defvar org-font-lock-hook nil
4517 "Functions to be called for special font lock stuff.")
4519 (defun org-font-lock-hook (limit)
4520 (run-hook-with-args 'org-font-lock-hook limit))
4522 (defun org-set-font-lock-defaults ()
4523 (let* ((em org-fontify-emphasized-text)
4524 (lk org-activate-links)
4525 (org-font-lock-extra-keywords
4526 (list
4527 ;; Call the hook
4528 '(org-font-lock-hook)
4529 ;; Headlines
4530 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4531 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4532 ;; Table lines
4533 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4534 (1 'org-table t))
4535 ;; Table internals
4536 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4537 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4538 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4539 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4540 ;; Drawers
4541 (list org-drawer-regexp '(0 'org-special-keyword t))
4542 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4543 ;; Properties
4544 (list org-property-re
4545 '(1 'org-special-keyword t)
4546 '(3 'org-property-value t))
4547 ;; Links
4548 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4549 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4550 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4551 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4552 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4553 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4554 (if (memq 'footnote lk) '(org-activate-footnote-links
4555 (2 'org-footnote t)))
4556 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4557 '(org-hide-wide-columns (0 nil append))
4558 ;; TODO lines
4559 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4560 '(1 (org-get-todo-face 1) t))
4561 ;; DONE
4562 (if org-fontify-done-headline
4563 (list (concat "^[*]+ +\\<\\("
4564 (mapconcat 'regexp-quote org-done-keywords "\\|")
4565 "\\)\\(.*\\)")
4566 '(2 'org-headline-done t))
4567 nil)
4568 ;; Priorities
4569 '(org-font-lock-add-priority-faces)
4570 ;; Tags
4571 '(org-font-lock-add-tag-faces)
4572 ;; Special keywords
4573 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4574 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4575 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4576 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4577 ;; Emphasis
4578 (if em
4579 (if (featurep 'xemacs)
4580 '(org-do-emphasis-faces (0 nil append))
4581 '(org-do-emphasis-faces)))
4582 ;; Checkboxes
4583 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4584 2 'org-checkbox prepend)
4585 (if org-provide-checkbox-statistics
4586 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4587 (0 (org-get-checkbox-statistics-face) t)))
4588 ;; Description list items
4589 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4590 2 'bold prepend)
4591 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4592 '(1 'org-archived prepend))
4593 ;; Specials
4594 '(org-do-latex-and-special-faces)
4595 ;; Code
4596 '(org-activate-code (1 'org-code t))
4597 ;; COMMENT
4598 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4599 "\\|" org-quote-string "\\)\\>")
4600 '(1 'org-special-keyword t))
4601 '("^#.*" (0 'font-lock-comment-face t))
4602 ;; Blocks and meta lines
4603 '(org-fontify-meta-lines-and-blocks)
4605 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4606 ;; Now set the full font-lock-keywords
4607 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4608 (org-set-local 'font-lock-defaults
4609 '(org-font-lock-keywords t nil nil backward-paragraph))
4610 (kill-local-variable 'font-lock-keywords) nil))
4612 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4613 "Fontify string S like in Org-mode"
4614 (with-temp-buffer
4615 (insert s)
4616 (let ((org-odd-levels-only odd-levels))
4617 (org-mode)
4618 (font-lock-fontify-buffer)
4619 (buffer-string))))
4621 (defvar org-m nil)
4622 (defvar org-l nil)
4623 (defvar org-f nil)
4624 (defun org-get-level-face (n)
4625 "Get the right face for match N in font-lock matching of headlines."
4626 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4627 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4628 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4629 (cond
4630 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4631 ((eq n 2) org-f)
4632 (t (if org-level-color-stars-only nil org-f))))
4634 (defun org-get-todo-face (kwd)
4635 "Get the right face for a TODO keyword KWD.
4636 If KWD is a number, get the corresponding match group."
4637 (if (numberp kwd) (setq kwd (match-string kwd)))
4638 (or (cdr (assoc kwd org-todo-keyword-faces))
4639 (and (member kwd org-done-keywords) 'org-done)
4640 'org-todo))
4642 (defun org-font-lock-add-tag-faces (limit)
4643 "Add the special tag faces."
4644 (when (and org-tag-faces org-tags-special-faces-re)
4645 (while (re-search-forward org-tags-special-faces-re limit t)
4646 (add-text-properties (match-beginning 1) (match-end 1)
4647 (list 'face (org-get-tag-face 1)
4648 'font-lock-fontified t))
4649 (backward-char 1))))
4651 (defun org-font-lock-add-priority-faces (limit)
4652 "Add the special priority faces."
4653 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4654 (add-text-properties
4655 (match-beginning 0) (match-end 0)
4656 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4657 org-priority-faces))
4658 'org-special-keyword)
4659 'font-lock-fontified t))))
4661 (defun org-get-tag-face (kwd)
4662 "Get the right face for a TODO keyword KWD.
4663 If KWD is a number, get the corresponding match group."
4664 (if (numberp kwd) (setq kwd (match-string kwd)))
4665 (or (cdr (assoc kwd org-tag-faces))
4666 'org-tag))
4668 (defun org-unfontify-region (beg end &optional maybe_loudly)
4669 "Remove fontification and activation overlays from links."
4670 (font-lock-default-unfontify-region beg end)
4671 (let* ((buffer-undo-list t)
4672 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4673 (inhibit-modification-hooks t)
4674 deactivate-mark buffer-file-name buffer-file-truename)
4675 (remove-text-properties beg end
4676 '(mouse-face t keymap t org-linked-text t
4677 invisible t intangible t
4678 org-no-flyspell t))))
4680 ;;;; Visibility cycling, including org-goto and indirect buffer
4682 ;;; Cycling
4684 (defvar org-cycle-global-status nil)
4685 (make-variable-buffer-local 'org-cycle-global-status)
4686 (defvar org-cycle-subtree-status nil)
4687 (make-variable-buffer-local 'org-cycle-subtree-status)
4689 ;;;###autoload
4691 (defvar org-inlinetask-min-level)
4693 (defun org-cycle (&optional arg)
4694 "TAB-action and visibility cycling for Org-mode.
4696 This is the command invoked in Org-moe by the TAB key. It's main purpose
4697 is outine visibility cycling, but it also invokes other actions
4698 in special contexts.
4700 - When this function is called with a prefix argument, rotate the entire
4701 buffer through 3 states (global cycling)
4702 1. OVERVIEW: Show only top-level headlines.
4703 2. CONTENTS: Show all headlines of all levels, but no body text.
4704 3. SHOW ALL: Show everything.
4705 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4706 determined by the variable `org-startup-folded', and by any VISIBILITY
4707 properties in the buffer.
4708 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4709 including any drawers.
4711 - When inside a table, re-align the table and move to the next field.
4713 - When point is at the beginning of a headline, rotate the subtree started
4714 by this line through 3 different states (local cycling)
4715 1. FOLDED: Only the main headline is shown.
4716 2. CHILDREN: The main headline and the direct children are shown.
4717 From this state, you can move to one of the children
4718 and zoom in further.
4719 3. SUBTREE: Show the entire subtree, including body text.
4721 - When there is a numeric prefix, go up to a heading with level ARG, do
4722 a `show-subtree' and return to the previous cursor position. If ARG
4723 is negative, go up that many levels.
4725 - When point is not at the beginning of a headline, execute the global
4726 binding for TAB, which is re-indenting the line. See the option
4727 `org-cycle-emulate-tab' for details.
4729 - Special case: if point is at the beginning of the buffer and there is
4730 no headline in line 1, this function will act as if called with prefix arg.
4731 But only if also the variable `org-cycle-global-at-bob' is t."
4732 (interactive "P")
4733 (org-load-modules-maybe)
4734 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4735 (let* ((limit-level
4736 (or org-cycle-max-level
4737 (and (boundp 'org-inlinetask-min-level)
4738 org-inlinetask-min-level
4739 (1- org-inlinetask-min-level))))
4740 (nstars (and limit-level
4741 (if org-odd-levels-only
4742 (and limit-level (1- (* limit-level 2)))
4743 limit-level)))
4744 (outline-regexp
4745 (cond
4746 ((not (org-mode-p)) outline-regexp)
4747 ((or (eq org-cycle-include-plain-lists 'integrate)
4748 (and org-cycle-include-plain-lists (org-at-item-p)))
4749 (concat "\\(?:\\*"
4750 (if nstars (format "\\{1,%d\\}" nstars) "+")
4751 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4752 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4753 (bob-special (and org-cycle-global-at-bob (bobp)
4754 (not (looking-at outline-regexp))))
4755 (org-cycle-hook
4756 (if bob-special
4757 (delq 'org-optimize-window-after-visibility-change
4758 (copy-sequence org-cycle-hook))
4759 org-cycle-hook))
4760 (pos (point)))
4762 (if (or bob-special (equal arg '(4)))
4763 ;; special case: use global cycling
4764 (setq arg t))
4766 (cond
4768 ((equal arg '(16))
4769 (org-set-startup-visibility)
4770 (message "Startup visibility, plus VISIBILITY properties"))
4772 ((equal arg '(64))
4773 (show-all)
4774 (message "Entire buffer visible, including drawers"))
4776 ((org-at-table-p 'any)
4777 ;; Enter the table or move to the next field in the table
4778 (or (org-table-recognize-table.el)
4779 (progn
4780 (if arg (org-table-edit-field t)
4781 (org-table-justify-field-maybe)
4782 (call-interactively 'org-table-next-field)))))
4784 ((run-hook-with-args-until-success
4785 'org-tab-after-check-for-table-hook))
4787 ((eq arg t) ;; Global cycling
4788 (org-cycle-internal-global))
4790 ((and org-drawers org-drawer-regexp
4791 (save-excursion
4792 (beginning-of-line 1)
4793 (looking-at org-drawer-regexp)))
4794 ;; Toggle block visibility
4795 (org-flag-drawer
4796 (not (get-char-property (match-end 0) 'invisible))))
4798 ((integerp arg)
4799 ;; Show-subtree, ARG levels up from here.
4800 (save-excursion
4801 (org-back-to-heading)
4802 (outline-up-heading (if (< arg 0) (- arg)
4803 (- (funcall outline-level) arg)))
4804 (org-show-subtree)))
4806 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4807 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4809 (org-cycle-internal-local))
4811 ;; TAB emulation and template completion
4812 (buffer-read-only (org-back-to-heading))
4814 ((run-hook-with-args-until-success
4815 'org-tab-after-check-for-cycling-hook))
4817 ((org-try-structure-completion))
4819 ((org-try-cdlatex-tab))
4821 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4822 (or (not (bolp))
4823 (not (looking-at outline-regexp))))
4824 (call-interactively (global-key-binding "\t")))
4826 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4827 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4828 (or (and (eq org-cycle-emulate-tab 'white)
4829 (= (match-end 0) (point-at-eol)))
4830 (and (eq org-cycle-emulate-tab 'whitestart)
4831 (>= (match-end 0) pos))))
4833 (eq org-cycle-emulate-tab t))
4834 (call-interactively (global-key-binding "\t")))
4836 (t (save-excursion
4837 (org-back-to-heading)
4838 (org-cycle)))))))
4840 (defun org-cycle-internal-global ()
4841 "Do the global cycling action."
4842 (cond
4843 ((and (eq last-command this-command)
4844 (eq org-cycle-global-status 'overview))
4845 ;; We just created the overview - now do table of contents
4846 ;; This can be slow in very large buffers, so indicate action
4847 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4848 (message "CONTENTS...")
4849 (org-content)
4850 (message "CONTENTS...done")
4851 (setq org-cycle-global-status 'contents)
4852 (run-hook-with-args 'org-cycle-hook 'contents))
4854 ((and (eq last-command this-command)
4855 (eq org-cycle-global-status 'contents))
4856 ;; We just showed the table of contents - now show everything
4857 (run-hook-with-args 'org-pre-cycle-hook 'all)
4858 (show-all)
4859 (message "SHOW ALL")
4860 (setq org-cycle-global-status 'all)
4861 (run-hook-with-args 'org-cycle-hook 'all))
4864 ;; Default action: go to overview
4865 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4866 (org-overview)
4867 (message "OVERVIEW")
4868 (setq org-cycle-global-status 'overview)
4869 (run-hook-with-args 'org-cycle-hook 'overview))))
4871 (defun org-cycle-internal-local ()
4872 "Do the local cycling action."
4873 (org-back-to-heading)
4874 (let ((goal-column 0) eoh eol eos)
4875 ;; First, some boundaries
4876 (save-excursion
4877 (org-back-to-heading)
4878 (save-excursion
4879 (beginning-of-line 2)
4880 (while (and (not (eobp)) ;; this is like `next-line'
4881 (get-char-property (1- (point)) 'invisible))
4882 (beginning-of-line 2)) (setq eol (point)))
4883 (outline-end-of-heading) (setq eoh (point))
4884 (org-end-of-subtree t)
4885 (unless (eobp)
4886 (skip-chars-forward " \t\n")
4887 (beginning-of-line 1) ; in case this is an item
4889 (setq eos (1- (point))))
4890 ;; Find out what to do next and set `this-command'
4891 (cond
4892 ((= eos eoh)
4893 ;; Nothing is hidden behind this heading
4894 (run-hook-with-args 'org-pre-cycle-hook 'empty)
4895 (message "EMPTY ENTRY")
4896 (setq org-cycle-subtree-status nil)
4897 (save-excursion
4898 (goto-char eos)
4899 (outline-next-heading)
4900 (if (org-invisible-p) (org-flag-heading nil))))
4901 ((or (>= eol eos)
4902 (not (string-match "\\S-" (buffer-substring eol eos))))
4903 ;; Entire subtree is hidden in one line: open it
4904 (run-hook-with-args 'org-pre-cycle-hook 'children)
4905 (org-show-entry)
4906 (show-children)
4907 (message "CHILDREN")
4908 (save-excursion
4909 (goto-char eos)
4910 (outline-next-heading)
4911 (if (org-invisible-p) (org-flag-heading nil)))
4912 (setq org-cycle-subtree-status 'children)
4913 (run-hook-with-args 'org-cycle-hook 'children))
4914 ((and (eq last-command this-command)
4915 (eq org-cycle-subtree-status 'children))
4916 ;; We just showed the children, now show everything.
4917 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
4918 (org-show-subtree)
4919 (message "SUBTREE")
4920 (setq org-cycle-subtree-status 'subtree)
4921 (run-hook-with-args 'org-cycle-hook 'subtree))
4923 ;; Default action: hide the subtree.
4924 (run-hook-with-args 'org-pre-cycle-hook 'folded)
4925 (hide-subtree)
4926 (message "FOLDED")
4927 (setq org-cycle-subtree-status 'folded)
4928 (run-hook-with-args 'org-cycle-hook 'folded)))))
4930 ;;;###autoload
4931 (defun org-global-cycle (&optional arg)
4932 "Cycle the global visibility. For details see `org-cycle'.
4933 With C-u prefix arg, switch to startup visibility.
4934 With a numeric prefix, show all headlines up to that level."
4935 (interactive "P")
4936 (let ((org-cycle-include-plain-lists
4937 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4938 (cond
4939 ((integerp arg)
4940 (show-all)
4941 (hide-sublevels arg)
4942 (setq org-cycle-global-status 'contents))
4943 ((equal arg '(4))
4944 (org-set-startup-visibility)
4945 (message "Startup visibility, plus VISIBILITY properties."))
4947 (org-cycle '(4))))))
4949 (defun org-set-startup-visibility ()
4950 "Set the visibility required by startup options and properties."
4951 (cond
4952 ((eq org-startup-folded t)
4953 (org-cycle '(4)))
4954 ((eq org-startup-folded 'content)
4955 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4956 (org-cycle '(4)) (org-cycle '(4)))))
4957 (if org-hide-block-startup (org-hide-block-all))
4958 (org-set-visibility-according-to-property 'no-cleanup)
4959 (org-cycle-hide-archived-subtrees 'all)
4960 (org-cycle-hide-drawers 'all)
4961 (org-cycle-show-empty-lines 'all))
4963 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4964 "Switch subtree visibilities according to :VISIBILITY: property."
4965 (interactive)
4966 (let (org-show-entry-below state)
4967 (save-excursion
4968 (goto-char (point-min))
4969 (while (re-search-forward
4970 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4971 nil t)
4972 (setq state (match-string 1))
4973 (save-excursion
4974 (org-back-to-heading t)
4975 (hide-subtree)
4976 (org-reveal)
4977 (cond
4978 ((equal state '("fold" "folded"))
4979 (hide-subtree))
4980 ((equal state "children")
4981 (org-show-hidden-entry)
4982 (show-children))
4983 ((equal state "content")
4984 (save-excursion
4985 (save-restriction
4986 (org-narrow-to-subtree)
4987 (org-content))))
4988 ((member state '("all" "showall"))
4989 (show-subtree)))))
4990 (unless no-cleanup
4991 (org-cycle-hide-archived-subtrees 'all)
4992 (org-cycle-hide-drawers 'all)
4993 (org-cycle-show-empty-lines 'all)))))
4995 (defun org-overview ()
4996 "Switch to overview mode, showing only top-level headlines.
4997 Really, this shows all headlines with level equal or greater than the level
4998 of the first headline in the buffer. This is important, because if the
4999 first headline is not level one, then (hide-sublevels 1) gives confusing
5000 results."
5001 (interactive)
5002 (let ((level (save-excursion
5003 (goto-char (point-min))
5004 (if (re-search-forward (concat "^" outline-regexp) nil t)
5005 (progn
5006 (goto-char (match-beginning 0))
5007 (funcall outline-level))))))
5008 (and level (hide-sublevels level))))
5010 (defun org-content (&optional arg)
5011 "Show all headlines in the buffer, like a table of contents.
5012 With numerical argument N, show content up to level N."
5013 (interactive "P")
5014 (save-excursion
5015 ;; Visit all headings and show their offspring
5016 (and (integerp arg) (org-overview))
5017 (goto-char (point-max))
5018 (catch 'exit
5019 (while (and (progn (condition-case nil
5020 (outline-previous-visible-heading 1)
5021 (error (goto-char (point-min))))
5023 (looking-at outline-regexp))
5024 (if (integerp arg)
5025 (show-children (1- arg))
5026 (show-branches))
5027 (if (bobp) (throw 'exit nil))))))
5030 (defun org-optimize-window-after-visibility-change (state)
5031 "Adjust the window after a change in outline visibility.
5032 This function is the default value of the hook `org-cycle-hook'."
5033 (when (get-buffer-window (current-buffer))
5034 (cond
5035 ((eq state 'content) nil)
5036 ((eq state 'all) nil)
5037 ((eq state 'folded) nil)
5038 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5039 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5041 (defun org-compact-display-after-subtree-move ()
5042 "Show a compacter version of the tree of the entry's parent."
5043 (save-excursion
5044 (if (org-up-heading-safe)
5045 (progn
5046 (hide-subtree)
5047 (show-entry)
5048 (show-children)
5049 (org-cycle-show-empty-lines 'children)
5050 (org-cycle-hide-drawers 'children))
5051 (org-overview))))
5053 (defun org-cycle-show-empty-lines (state)
5054 "Show empty lines above all visible headlines.
5055 The region to be covered depends on STATE when called through
5056 `org-cycle-hook'. Lisp program can use t for STATE to get the
5057 entire buffer covered. Note that an empty line is only shown if there
5058 are at least `org-cycle-separator-lines' empty lines before the headline."
5059 (when (> org-cycle-separator-lines 0)
5060 (save-excursion
5061 (let* ((n org-cycle-separator-lines)
5062 (re (cond
5063 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5064 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5065 (t (let ((ns (number-to-string (- n 2))))
5066 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5067 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5068 beg end)
5069 (cond
5070 ((memq state '(overview contents t))
5071 (setq beg (point-min) end (point-max)))
5072 ((memq state '(children folded))
5073 (setq beg (point) end (progn (org-end-of-subtree t t)
5074 (beginning-of-line 2)
5075 (point)))))
5076 (when beg
5077 (goto-char beg)
5078 (while (re-search-forward re end t)
5079 (if (not (get-char-property (match-end 1) 'invisible))
5080 (outline-flag-region
5081 (match-beginning 1) (match-end 1) nil)))))))
5082 ;; Never hide empty lines at the end of the file.
5083 (save-excursion
5084 (goto-char (point-max))
5085 (outline-previous-heading)
5086 (outline-end-of-heading)
5087 (if (and (looking-at "[ \t\n]+")
5088 (= (match-end 0) (point-max)))
5089 (outline-flag-region (point) (match-end 0) nil))))
5091 (defun org-show-empty-lines-in-parent ()
5092 "Move to the parent and re-show empty lines before visible headlines."
5093 (save-excursion
5094 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5095 (org-cycle-show-empty-lines context))))
5097 (defun org-cycle-hide-drawers (state)
5098 "Re-hide all drawers after a visibility state change."
5099 (when (and (org-mode-p)
5100 (not (memq state '(overview folded))))
5101 (save-excursion
5102 (let* ((globalp (memq state '(contents all)))
5103 (beg (if globalp (point-min) (point)))
5104 (end (if globalp (point-max) (org-end-of-subtree t))))
5105 (goto-char beg)
5106 (while (re-search-forward org-drawer-regexp end t)
5107 (org-flag-drawer t))))))
5109 (defun org-flag-drawer (flag)
5110 (save-excursion
5111 (beginning-of-line 1)
5112 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5113 (let ((b (match-end 0))
5114 (outline-regexp org-outline-regexp))
5115 (if (re-search-forward
5116 "^[ \t]*:END:"
5117 (save-excursion (outline-next-heading) (point)) t)
5118 (outline-flag-region b (point-at-eol) flag)
5119 (error ":END: line missing"))))))
5121 (defun org-subtree-end-visible-p ()
5122 "Is the end of the current subtree visible?"
5123 (pos-visible-in-window-p
5124 (save-excursion (org-end-of-subtree t) (point))))
5126 (defun org-first-headline-recenter (&optional N)
5127 "Move cursor to the first headline and recenter the headline.
5128 Optional argument N means, put the headline into the Nth line of the window."
5129 (goto-char (point-min))
5130 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5131 (beginning-of-line)
5132 (recenter (prefix-numeric-value N))))
5134 ;;; Folding of blocks
5136 (defconst org-block-regexp
5138 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5139 "Regular expression for hiding blocks.")
5141 (defvar org-hide-block-overlays nil
5142 "Overays hiding blocks.")
5143 (make-variable-buffer-local 'org-hide-block-overlays)
5145 (defun org-block-map (function &optional start end)
5146 "Call func at the head of all source blocks in the current
5147 buffer. Optional arguments START and END can be used to limit
5148 the range."
5149 (let ((start (or start (point-min)))
5150 (end (or end (point-max))))
5151 (save-excursion
5152 (goto-char start)
5153 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5154 (save-excursion
5155 (save-match-data
5156 (goto-char (match-beginning 0))
5157 (funcall function)))))))
5159 (defun org-hide-block-toggle-all ()
5160 "Toggle the visibility of all blocks in the current buffer."
5161 (org-block-map #'org-hide-block-toggle))
5163 (defun org-hide-block-all ()
5164 "Fold all blocks in the current buffer."
5165 (interactive)
5166 (org-show-block-all)
5167 (org-block-map #'org-hide-block-toggle-maybe))
5169 (defun org-show-block-all ()
5170 "Unfold all blocks in the current buffer."
5171 (mapc 'org-delete-overlay org-hide-block-overlays)
5172 (setq org-hide-block-overlays nil))
5174 (defun org-hide-block-toggle-maybe ()
5175 "Toggle visibility of block at point."
5176 (interactive)
5177 (let ((case-fold-search t))
5178 (if (save-excursion
5179 (beginning-of-line 1)
5180 (looking-at org-block-regexp))
5181 (progn (org-hide-block-toggle)
5182 t) ;; to signal that we took action
5183 nil))) ;; to signal that we did not
5185 (defun org-hide-block-toggle (&optional force)
5186 "Toggle the visibility of the current block."
5187 (interactive)
5188 (save-excursion
5189 (beginning-of-line)
5190 (if (re-search-forward org-block-regexp nil t)
5191 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5192 (end (match-end 0))
5193 ov) ;; end of entire body
5194 (if (memq t (mapcar (lambda (overlay)
5195 (eq (org-overlay-get overlay 'invisible)
5196 'org-hide-block))
5197 (org-overlays-at start)))
5198 (if (or (not force) (eq force 'off))
5199 (mapc (lambda (ov)
5200 (when (member ov org-hide-block-overlays)
5201 (setq org-hide-block-overlays
5202 (delq ov org-hide-block-overlays)))
5203 (when (eq (org-overlay-get ov 'invisible)
5204 'org-hide-block)
5205 (org-delete-overlay ov)))
5206 (org-overlays-at start)))
5207 (setq ov (org-make-overlay start end))
5208 (org-overlay-put ov 'invisible 'org-hide-block)
5209 (push ov org-hide-block-overlays)))
5210 (error "Not looking at a source block"))))
5212 ;; org-tab-after-check-for-cycling-hook
5213 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5214 ;; Remove overlays when changing major mode
5215 (add-hook 'org-mode-hook
5216 (lambda () (org-add-hook 'change-major-mode-hook
5217 'org-show-block-all 'append 'local)))
5219 ;;; Org-goto
5221 (defvar org-goto-window-configuration nil)
5222 (defvar org-goto-marker nil)
5223 (defvar org-goto-map
5224 (let ((map (make-sparse-keymap)))
5225 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5226 (while (setq cmd (pop cmds))
5227 (substitute-key-definition cmd cmd map global-map)))
5228 (suppress-keymap map)
5229 (org-defkey map "\C-m" 'org-goto-ret)
5230 (org-defkey map [(return)] 'org-goto-ret)
5231 (org-defkey map [(left)] 'org-goto-left)
5232 (org-defkey map [(right)] 'org-goto-right)
5233 (org-defkey map [(control ?g)] 'org-goto-quit)
5234 (org-defkey map "\C-i" 'org-cycle)
5235 (org-defkey map [(tab)] 'org-cycle)
5236 (org-defkey map [(down)] 'outline-next-visible-heading)
5237 (org-defkey map [(up)] 'outline-previous-visible-heading)
5238 (if org-goto-auto-isearch
5239 (if (fboundp 'define-key-after)
5240 (define-key-after map [t] 'org-goto-local-auto-isearch)
5241 nil)
5242 (org-defkey map "q" 'org-goto-quit)
5243 (org-defkey map "n" 'outline-next-visible-heading)
5244 (org-defkey map "p" 'outline-previous-visible-heading)
5245 (org-defkey map "f" 'outline-forward-same-level)
5246 (org-defkey map "b" 'outline-backward-same-level)
5247 (org-defkey map "u" 'outline-up-heading))
5248 (org-defkey map "/" 'org-occur)
5249 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5250 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5251 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5252 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5253 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5254 map))
5256 (defconst org-goto-help
5257 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5258 RET=jump to location [Q]uit and return to previous location
5259 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5261 (defvar org-goto-start-pos) ; dynamically scoped parameter
5263 ;; FIXME: Docstring doe not mention both interfaces
5264 (defun org-goto (&optional alternative-interface)
5265 "Look up a different location in the current file, keeping current visibility.
5267 When you want look-up or go to a different location in a document, the
5268 fastest way is often to fold the entire buffer and then dive into the tree.
5269 This method has the disadvantage, that the previous location will be folded,
5270 which may not be what you want.
5272 This command works around this by showing a copy of the current buffer
5273 in an indirect buffer, in overview mode. You can dive into the tree in
5274 that copy, use org-occur and incremental search to find a location.
5275 When pressing RET or `Q', the command returns to the original buffer in
5276 which the visibility is still unchanged. After RET is will also jump to
5277 the location selected in the indirect buffer and expose the
5278 the headline hierarchy above."
5279 (interactive "P")
5280 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5281 (org-refile-use-outline-path t)
5282 (org-refile-target-verify-function nil)
5283 (interface
5284 (if (not alternative-interface)
5285 org-goto-interface
5286 (if (eq org-goto-interface 'outline)
5287 'outline-path-completion
5288 'outline)))
5289 (org-goto-start-pos (point))
5290 (selected-point
5291 (if (eq interface 'outline)
5292 (car (org-get-location (current-buffer) org-goto-help))
5293 (nth 3 (org-refile-get-location "Goto: ")))))
5294 (if selected-point
5295 (progn
5296 (org-mark-ring-push org-goto-start-pos)
5297 (goto-char selected-point)
5298 (if (or (org-invisible-p) (org-invisible-p2))
5299 (org-show-context 'org-goto)))
5300 (message "Quit"))))
5302 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5303 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5304 (defvar org-goto-local-auto-isearch-map) ; defined below
5306 (defun org-get-location (buf help)
5307 "Let the user select a location in the Org-mode buffer BUF.
5308 This function uses a recursive edit. It returns the selected position
5309 or nil."
5310 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5311 (isearch-hide-immediately nil)
5312 (isearch-search-fun-function
5313 (lambda () 'org-goto-local-search-headings))
5314 (org-goto-selected-point org-goto-exit-command))
5315 (save-excursion
5316 (save-window-excursion
5317 (delete-other-windows)
5318 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5319 (switch-to-buffer
5320 (condition-case nil
5321 (make-indirect-buffer (current-buffer) "*org-goto*")
5322 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5323 (with-output-to-temp-buffer "*Help*"
5324 (princ help))
5325 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5326 (setq buffer-read-only nil)
5327 (let ((org-startup-truncated t)
5328 (org-startup-folded nil)
5329 (org-startup-align-all-tables nil))
5330 (org-mode)
5331 (org-overview))
5332 (setq buffer-read-only t)
5333 (if (and (boundp 'org-goto-start-pos)
5334 (integer-or-marker-p org-goto-start-pos))
5335 (let ((org-show-hierarchy-above t)
5336 (org-show-siblings t)
5337 (org-show-following-heading t))
5338 (goto-char org-goto-start-pos)
5339 (and (org-invisible-p) (org-show-context)))
5340 (goto-char (point-min)))
5341 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5342 (message "Select location and press RET")
5343 (use-local-map org-goto-map)
5344 (recursive-edit)
5346 (kill-buffer "*org-goto*")
5347 (cons org-goto-selected-point org-goto-exit-command)))
5349 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5350 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5351 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5352 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5354 (defun org-goto-local-search-headings (string bound noerror)
5355 "Search and make sure that any matches are in headlines."
5356 (catch 'return
5357 (while (if isearch-forward
5358 (search-forward string bound noerror)
5359 (search-backward string bound noerror))
5360 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5361 (and (member :headline context)
5362 (not (member :tags context))))
5363 (throw 'return (point))))))
5365 (defun org-goto-local-auto-isearch ()
5366 "Start isearch."
5367 (interactive)
5368 (goto-char (point-min))
5369 (let ((keys (this-command-keys)))
5370 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5371 (isearch-mode t)
5372 (isearch-process-search-char (string-to-char keys)))))
5374 (defun org-goto-ret (&optional arg)
5375 "Finish `org-goto' by going to the new location."
5376 (interactive "P")
5377 (setq org-goto-selected-point (point)
5378 org-goto-exit-command 'return)
5379 (throw 'exit nil))
5381 (defun org-goto-left ()
5382 "Finish `org-goto' by going to the new location."
5383 (interactive)
5384 (if (org-on-heading-p)
5385 (progn
5386 (beginning-of-line 1)
5387 (setq org-goto-selected-point (point)
5388 org-goto-exit-command 'left)
5389 (throw 'exit nil))
5390 (error "Not on a heading")))
5392 (defun org-goto-right ()
5393 "Finish `org-goto' by going to the new location."
5394 (interactive)
5395 (if (org-on-heading-p)
5396 (progn
5397 (setq org-goto-selected-point (point)
5398 org-goto-exit-command 'right)
5399 (throw 'exit nil))
5400 (error "Not on a heading")))
5402 (defun org-goto-quit ()
5403 "Finish `org-goto' without cursor motion."
5404 (interactive)
5405 (setq org-goto-selected-point nil)
5406 (setq org-goto-exit-command 'quit)
5407 (throw 'exit nil))
5409 ;;; Indirect buffer display of subtrees
5411 (defvar org-indirect-dedicated-frame nil
5412 "This is the frame being used for indirect tree display.")
5413 (defvar org-last-indirect-buffer nil)
5415 (defun org-tree-to-indirect-buffer (&optional arg)
5416 "Create indirect buffer and narrow it to current subtree.
5417 With numerical prefix ARG, go up to this level and then take that tree.
5418 If ARG is negative, go up that many levels.
5419 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5420 indirect buffer previously made with this command, to avoid proliferation of
5421 indirect buffers. However, when you call the command with a `C-u' prefix, or
5422 when `org-indirect-buffer-display' is `new-frame', the last buffer
5423 is kept so that you can work with several indirect buffers at the same time.
5424 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5425 requests that a new frame be made for the new buffer, so that the dedicated
5426 frame is not changed."
5427 (interactive "P")
5428 (let ((cbuf (current-buffer))
5429 (cwin (selected-window))
5430 (pos (point))
5431 beg end level heading ibuf)
5432 (save-excursion
5433 (org-back-to-heading t)
5434 (when (numberp arg)
5435 (setq level (org-outline-level))
5436 (if (< arg 0) (setq arg (+ level arg)))
5437 (while (> (setq level (org-outline-level)) arg)
5438 (outline-up-heading 1 t)))
5439 (setq beg (point)
5440 heading (org-get-heading))
5441 (org-end-of-subtree t) (setq end (point)))
5442 (if (and (buffer-live-p org-last-indirect-buffer)
5443 (not (eq org-indirect-buffer-display 'new-frame))
5444 (not arg))
5445 (kill-buffer org-last-indirect-buffer))
5446 (setq ibuf (org-get-indirect-buffer cbuf)
5447 org-last-indirect-buffer ibuf)
5448 (cond
5449 ((or (eq org-indirect-buffer-display 'new-frame)
5450 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5451 (select-frame (make-frame))
5452 (delete-other-windows)
5453 (switch-to-buffer ibuf)
5454 (org-set-frame-title heading))
5455 ((eq org-indirect-buffer-display 'dedicated-frame)
5456 (raise-frame
5457 (select-frame (or (and org-indirect-dedicated-frame
5458 (frame-live-p org-indirect-dedicated-frame)
5459 org-indirect-dedicated-frame)
5460 (setq org-indirect-dedicated-frame (make-frame)))))
5461 (delete-other-windows)
5462 (switch-to-buffer ibuf)
5463 (org-set-frame-title (concat "Indirect: " heading)))
5464 ((eq org-indirect-buffer-display 'current-window)
5465 (switch-to-buffer ibuf))
5466 ((eq org-indirect-buffer-display 'other-window)
5467 (pop-to-buffer ibuf))
5468 (t (error "Invalid value.")))
5469 (if (featurep 'xemacs)
5470 (save-excursion (org-mode) (turn-on-font-lock)))
5471 (narrow-to-region beg end)
5472 (show-all)
5473 (goto-char pos)
5474 (and (window-live-p cwin) (select-window cwin))))
5476 (defun org-get-indirect-buffer (&optional buffer)
5477 (setq buffer (or buffer (current-buffer)))
5478 (let ((n 1) (base (buffer-name buffer)) bname)
5479 (while (buffer-live-p
5480 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5481 (setq n (1+ n)))
5482 (condition-case nil
5483 (make-indirect-buffer buffer bname 'clone)
5484 (error (make-indirect-buffer buffer bname)))))
5486 (defun org-set-frame-title (title)
5487 "Set the title of the current frame to the string TITLE."
5488 ;; FIXME: how to name a single frame in XEmacs???
5489 (unless (featurep 'xemacs)
5490 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5492 ;;;; Structure editing
5494 ;;; Inserting headlines
5496 (defun org-previous-line-empty-p ()
5497 (save-excursion
5498 (and (not (bobp))
5499 (or (beginning-of-line 0) t)
5500 (save-match-data
5501 (looking-at "[ \t]*$")))))
5503 (defun org-insert-heading (&optional force-heading)
5504 "Insert a new heading or item with same depth at point.
5505 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5506 If point is at the beginning of a headline, insert a sibling before the
5507 current headline. If point is not at the beginning, do not split the line,
5508 but create the new headline after the current line."
5509 (interactive "P")
5510 (if (= (buffer-size) 0)
5511 (insert "\n* ")
5512 (when (or force-heading (not (org-insert-item)))
5513 (let* ((empty-line-p nil)
5514 (head (save-excursion
5515 (condition-case nil
5516 (progn
5517 (org-back-to-heading)
5518 (setq empty-line-p (org-previous-line-empty-p))
5519 (match-string 0))
5520 (error "*"))))
5521 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5522 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5523 pos hide-previous previous-pos)
5524 (cond
5525 ((and (org-on-heading-p) (bolp)
5526 (or (bobp)
5527 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5528 ;; insert before the current line
5529 (open-line (if blank 2 1)))
5530 ((and (bolp)
5531 (or (bobp)
5532 (save-excursion
5533 (backward-char 1) (not (org-invisible-p)))))
5534 ;; insert right here
5535 nil)
5537 ;; somewhere in the line
5538 (save-excursion
5539 (setq previous-pos (point-at-bol))
5540 (end-of-line)
5541 (setq hide-previous (org-invisible-p)))
5542 (and org-insert-heading-respect-content (org-show-subtree))
5543 (let ((split
5544 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5545 (save-excursion
5546 (let ((p (point)))
5547 (goto-char (point-at-bol))
5548 (and (looking-at org-complex-heading-regexp)
5549 (> p (match-beginning 4)))))))
5550 tags pos)
5551 (cond
5552 (org-insert-heading-respect-content
5553 (org-end-of-subtree nil t)
5554 (or (bolp) (newline))
5555 (or (org-previous-line-empty-p)
5556 (and blank (newline)))
5557 (open-line 1))
5558 ((org-on-heading-p)
5559 (when hide-previous
5560 (show-children)
5561 (org-show-entry))
5562 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5563 (setq tags (and (match-end 2) (match-string 2)))
5564 (and (match-end 1)
5565 (delete-region (match-beginning 1) (match-end 1)))
5566 (setq pos (point-at-bol))
5567 (or split (end-of-line 1))
5568 (delete-horizontal-space)
5569 (newline (if blank 2 1))
5570 (when tags
5571 (save-excursion
5572 (goto-char pos)
5573 (end-of-line 1)
5574 (insert " " tags)
5575 (org-set-tags nil 'align))))
5577 (or split (end-of-line 1))
5578 (newline (if blank 2 1)))))))
5579 (insert head) (just-one-space)
5580 (setq pos (point))
5581 (end-of-line 1)
5582 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5583 (when (and org-insert-heading-respect-content hide-previous)
5584 (save-excursion
5585 (goto-char previous-pos)
5586 (hide-subtree)))
5587 (run-hooks 'org-insert-heading-hook)))))
5589 (defun org-get-heading (&optional no-tags)
5590 "Return the heading of the current entry, without the stars."
5591 (save-excursion
5592 (org-back-to-heading t)
5593 (if (looking-at
5594 (if no-tags
5595 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5596 "\\*+[ \t]+\\([^\r\n]*\\)"))
5597 (match-string 1) "")))
5599 (defun org-heading-components ()
5600 "Return the components of the current heading.
5601 This is a list with the following elements:
5602 - the level as an integer
5603 - the reduced level, different if `org-odd-levels-only' is set.
5604 - the TODO keyword, or nil
5605 - the priority character, like ?A, or nil if no priority is given
5606 - the headline text itself, or the tags string if no headline text
5607 - the tags string, or nil."
5608 (save-excursion
5609 (org-back-to-heading t)
5610 (if (looking-at org-complex-heading-regexp)
5611 (list (length (match-string 1))
5612 (org-reduced-level (length (match-string 1)))
5613 (org-match-string-no-properties 2)
5614 (and (match-end 3) (aref (match-string 3) 2))
5615 (org-match-string-no-properties 4)
5616 (org-match-string-no-properties 5)))))
5618 (defun org-get-entry ()
5619 "Get the entry text, after heading, entire subtree."
5620 (save-excursion
5621 (org-back-to-heading t)
5622 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5624 (defun org-insert-heading-after-current ()
5625 "Insert a new heading with same level as current, after current subtree."
5626 (interactive)
5627 (org-back-to-heading)
5628 (org-insert-heading)
5629 (org-move-subtree-down)
5630 (end-of-line 1))
5632 (defun org-insert-heading-respect-content ()
5633 (interactive)
5634 (let ((org-insert-heading-respect-content t))
5635 (org-insert-heading t)))
5637 (defun org-insert-todo-heading-respect-content (&optional force-state)
5638 (interactive "P")
5639 (let ((org-insert-heading-respect-content t))
5640 (org-insert-todo-heading force-state t)))
5642 (defun org-insert-todo-heading (arg &optional force-heading)
5643 "Insert a new heading with the same level and TODO state as current heading.
5644 If the heading has no TODO state, or if the state is DONE, use the first
5645 state (TODO by default). Also with prefix arg, force first state."
5646 (interactive "P")
5647 (when (or force-heading (not (org-insert-item 'checkbox)))
5648 (org-insert-heading force-heading)
5649 (save-excursion
5650 (org-back-to-heading)
5651 (outline-previous-heading)
5652 (looking-at org-todo-line-regexp))
5653 (let*
5654 ((new-mark-x
5655 (if (or arg
5656 (not (match-beginning 2))
5657 (member (match-string 2) org-done-keywords))
5658 (car org-todo-keywords-1)
5659 (match-string 2)))
5660 (new-mark
5662 (run-hook-with-args-until-success
5663 'org-todo-get-default-hook new-mark-x nil)
5664 new-mark-x)))
5665 (beginning-of-line 1)
5666 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5667 (if org-treat-insert-todo-heading-as-state-change
5668 (org-todo new-mark)
5669 (insert new-mark " "))))
5670 (when org-provide-todo-statistics
5671 (org-update-parent-todo-statistics))))
5673 (defun org-insert-subheading (arg)
5674 "Insert a new subheading and demote it.
5675 Works for outline headings and for plain lists alike."
5676 (interactive "P")
5677 (org-insert-heading arg)
5678 (cond
5679 ((org-on-heading-p) (org-do-demote))
5680 ((org-at-item-p) (org-indent-item 1))))
5682 (defun org-insert-todo-subheading (arg)
5683 "Insert a new subheading with TODO keyword or checkbox and demote it.
5684 Works for outline headings and for plain lists alike."
5685 (interactive "P")
5686 (org-insert-todo-heading arg)
5687 (cond
5688 ((org-on-heading-p) (org-do-demote))
5689 ((org-at-item-p) (org-indent-item 1))))
5691 ;;; Promotion and Demotion
5693 (defun org-promote-subtree ()
5694 "Promote the entire subtree.
5695 See also `org-promote'."
5696 (interactive)
5697 (save-excursion
5698 (org-map-tree 'org-promote))
5699 (org-fix-position-after-promote))
5701 (defun org-demote-subtree ()
5702 "Demote the entire subtree. See `org-demote'.
5703 See also `org-promote'."
5704 (interactive)
5705 (save-excursion
5706 (org-map-tree 'org-demote))
5707 (org-fix-position-after-promote))
5710 (defun org-do-promote ()
5711 "Promote the current heading higher up the tree.
5712 If the region is active in `transient-mark-mode', promote all headings
5713 in the region."
5714 (interactive)
5715 (save-excursion
5716 (if (org-region-active-p)
5717 (org-map-region 'org-promote (region-beginning) (region-end))
5718 (org-promote)))
5719 (org-fix-position-after-promote))
5721 (defun org-do-demote ()
5722 "Demote the current heading lower down the tree.
5723 If the region is active in `transient-mark-mode', demote all headings
5724 in the region."
5725 (interactive)
5726 (save-excursion
5727 (if (org-region-active-p)
5728 (org-map-region 'org-demote (region-beginning) (region-end))
5729 (org-demote)))
5730 (org-fix-position-after-promote))
5732 (defun org-fix-position-after-promote ()
5733 "Make sure that after pro/demotion cursor position is right."
5734 (let ((pos (point)))
5735 (when (save-excursion
5736 (beginning-of-line 1)
5737 (looking-at org-todo-line-regexp)
5738 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5739 (cond ((eobp) (insert " "))
5740 ((eolp) (insert " "))
5741 ((equal (char-after) ?\ ) (forward-char 1))))))
5743 (defun org-reduced-level (l)
5744 "Compute the effective level of a heading.
5745 This takes into account the setting of `org-odd-levels-only'."
5746 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5748 (defun org-get-valid-level (level &optional change)
5749 "Rectify a level change under the influence of `org-odd-levels-only'
5750 LEVEL is a current level, CHANGE is by how much the level should be
5751 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5752 even level numbers will become the next higher odd number."
5753 (if org-odd-levels-only
5754 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5755 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5756 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5757 (max 1 (+ level (or change 0)))))
5759 (if (boundp 'define-obsolete-function-alias)
5760 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5761 (define-obsolete-function-alias 'org-get-legal-level
5762 'org-get-valid-level)
5763 (define-obsolete-function-alias 'org-get-legal-level
5764 'org-get-valid-level "23.1")))
5766 (defun org-promote ()
5767 "Promote the current heading higher up the tree.
5768 If the region is active in `transient-mark-mode', promote all headings
5769 in the region."
5770 (org-back-to-heading t)
5771 (let* ((level (save-match-data (funcall outline-level)))
5772 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5773 (diff (abs (- level (length up-head) -1))))
5774 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5775 (replace-match up-head nil t)
5776 ;; Fixup tag positioning
5777 (and org-auto-align-tags (org-set-tags nil t))
5778 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5780 (defun org-demote ()
5781 "Demote the current heading lower down the tree.
5782 If the region is active in `transient-mark-mode', demote all headings
5783 in the region."
5784 (org-back-to-heading t)
5785 (let* ((level (save-match-data (funcall outline-level)))
5786 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5787 (diff (abs (- level (length down-head) -1))))
5788 (replace-match down-head nil t)
5789 ;; Fixup tag positioning
5790 (and org-auto-align-tags (org-set-tags nil t))
5791 (if org-adapt-indentation (org-fixup-indentation diff))))
5793 (defun org-map-tree (fun)
5794 "Call FUN for every heading underneath the current one."
5795 (org-back-to-heading)
5796 (let ((level (funcall outline-level)))
5797 (save-excursion
5798 (funcall fun)
5799 (while (and (progn
5800 (outline-next-heading)
5801 (> (funcall outline-level) level))
5802 (not (eobp)))
5803 (funcall fun)))))
5805 (defun org-map-region (fun beg end)
5806 "Call FUN for every heading between BEG and END."
5807 (let ((org-ignore-region t))
5808 (save-excursion
5809 (setq end (copy-marker end))
5810 (goto-char beg)
5811 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5812 (< (point) end))
5813 (funcall fun))
5814 (while (and (progn
5815 (outline-next-heading)
5816 (< (point) end))
5817 (not (eobp)))
5818 (funcall fun)))))
5820 (defun org-fixup-indentation (diff)
5821 "Change the indentation in the current entry by DIFF
5822 However, if any line in the current entry has no indentation, or if it
5823 would end up with no indentation after the change, nothing at all is done."
5824 (save-excursion
5825 (let ((end (save-excursion (outline-next-heading)
5826 (point-marker)))
5827 (prohibit (if (> diff 0)
5828 "^\\S-"
5829 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5830 col)
5831 (unless (save-excursion (end-of-line 1)
5832 (re-search-forward prohibit end t))
5833 (while (and (< (point) end)
5834 (re-search-forward "^[ \t]+" end t))
5835 (goto-char (match-end 0))
5836 (setq col (current-column))
5837 (if (< diff 0) (replace-match ""))
5838 (org-indent-to-column (+ diff col))))
5839 (move-marker end nil))))
5841 (defun org-convert-to-odd-levels ()
5842 "Convert an org-mode file with all levels allowed to one with odd levels.
5843 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5844 level 5 etc."
5845 (interactive)
5846 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5847 (let ((org-odd-levels-only nil) n)
5848 (save-excursion
5849 (goto-char (point-min))
5850 (while (re-search-forward "^\\*\\*+ " nil t)
5851 (setq n (- (length (match-string 0)) 2))
5852 (while (>= (setq n (1- n)) 0)
5853 (org-demote))
5854 (end-of-line 1))))))
5857 (defun org-convert-to-oddeven-levels ()
5858 "Convert an org-mode file with only odd levels to one with odd and even levels.
5859 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5860 section with an even level, conversion would destroy the structure of the file. An error
5861 is signaled in this case."
5862 (interactive)
5863 (goto-char (point-min))
5864 ;; First check if there are no even levels
5865 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5866 (org-show-context t)
5867 (error "Not all levels are odd in this file. Conversion not possible."))
5868 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5869 (let ((org-odd-levels-only nil) n)
5870 (save-excursion
5871 (goto-char (point-min))
5872 (while (re-search-forward "^\\*\\*+ " nil t)
5873 (setq n (/ (1- (length (match-string 0))) 2))
5874 (while (>= (setq n (1- n)) 0)
5875 (org-promote))
5876 (end-of-line 1))))))
5878 (defun org-tr-level (n)
5879 "Make N odd if required."
5880 (if org-odd-levels-only (1+ (/ n 2)) n))
5882 ;;; Vertical tree motion, cutting and pasting of subtrees
5884 (defun org-move-subtree-up (&optional arg)
5885 "Move the current subtree up past ARG headlines of the same level."
5886 (interactive "p")
5887 (org-move-subtree-down (- (prefix-numeric-value arg))))
5889 (defun org-move-subtree-down (&optional arg)
5890 "Move the current subtree down past ARG headlines of the same level."
5891 (interactive "p")
5892 (setq arg (prefix-numeric-value arg))
5893 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5894 'outline-get-last-sibling))
5895 (ins-point (make-marker))
5896 (cnt (abs arg))
5897 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5898 ;; Select the tree
5899 (org-back-to-heading)
5900 (setq beg0 (point))
5901 (save-excursion
5902 (setq ne-beg (org-back-over-empty-lines))
5903 (setq beg (point)))
5904 (save-match-data
5905 (save-excursion (outline-end-of-heading)
5906 (setq folded (org-invisible-p)))
5907 (outline-end-of-subtree))
5908 (outline-next-heading)
5909 (setq ne-end (org-back-over-empty-lines))
5910 (setq end (point))
5911 (goto-char beg0)
5912 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5913 ;; include less whitespace
5914 (save-excursion
5915 (goto-char beg)
5916 (forward-line (- ne-beg ne-end))
5917 (setq beg (point))))
5918 ;; Find insertion point, with error handling
5919 (while (> cnt 0)
5920 (or (and (funcall movfunc) (looking-at outline-regexp))
5921 (progn (goto-char beg0)
5922 (error "Cannot move past superior level or buffer limit")))
5923 (setq cnt (1- cnt)))
5924 (if (> arg 0)
5925 ;; Moving forward - still need to move over subtree
5926 (progn (org-end-of-subtree t t)
5927 (save-excursion
5928 (org-back-over-empty-lines)
5929 (or (bolp) (newline)))))
5930 (setq ne-ins (org-back-over-empty-lines))
5931 (move-marker ins-point (point))
5932 (setq txt (buffer-substring beg end))
5933 (org-save-markers-in-region beg end)
5934 (delete-region beg end)
5935 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5936 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5937 (and (not (bolp)) (looking-at "\n") (forward-char 1))
5938 (let ((bbb (point)))
5939 (insert-before-markers txt)
5940 (org-reinstall-markers-in-region bbb)
5941 (move-marker ins-point bbb))
5942 (or (bolp) (insert "\n"))
5943 (setq ins-end (point))
5944 (goto-char ins-point)
5945 (org-skip-whitespace)
5946 (when (and (< arg 0)
5947 (org-first-sibling-p)
5948 (> ne-ins ne-beg))
5949 ;; Move whitespace back to beginning
5950 (save-excursion
5951 (goto-char ins-end)
5952 (let ((kill-whole-line t))
5953 (kill-line (- ne-ins ne-beg)) (point)))
5954 (insert (make-string (- ne-ins ne-beg) ?\n)))
5955 (move-marker ins-point nil)
5956 (org-compact-display-after-subtree-move)
5957 (org-show-empty-lines-in-parent)
5958 (unless folded
5959 (org-show-entry)
5960 (show-children)
5961 (org-cycle-hide-drawers 'children))))
5963 (defvar org-subtree-clip ""
5964 "Clipboard for cut and paste of subtrees.
5965 This is actually only a copy of the kill, because we use the normal kill
5966 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5968 (defvar org-subtree-clip-folded nil
5969 "Was the last copied subtree folded?
5970 This is used to fold the tree back after pasting.")
5972 (defun org-cut-subtree (&optional n)
5973 "Cut the current subtree into the clipboard.
5974 With prefix arg N, cut this many sequential subtrees.
5975 This is a short-hand for marking the subtree and then cutting it."
5976 (interactive "p")
5977 (org-copy-subtree n 'cut))
5979 (defun org-copy-subtree (&optional n cut force-store-markers)
5980 "Cut the current subtree into the clipboard.
5981 With prefix arg N, cut this many sequential subtrees.
5982 This is a short-hand for marking the subtree and then copying it.
5983 If CUT is non-nil, actually cut the subtree.
5984 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5985 of some markers in the region, even if CUT is non-nil. This is
5986 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5987 (interactive "p")
5988 (let (beg end folded (beg0 (point)))
5989 (if (interactive-p)
5990 (org-back-to-heading nil) ; take what looks like a subtree
5991 (org-back-to-heading t)) ; take what is really there
5992 (org-back-over-empty-lines)
5993 (setq beg (point))
5994 (skip-chars-forward " \t\r\n")
5995 (save-match-data
5996 (save-excursion (outline-end-of-heading)
5997 (setq folded (org-invisible-p)))
5998 (condition-case nil
5999 (outline-forward-same-level (1- n))
6000 (error nil))
6001 (org-end-of-subtree t t))
6002 (org-back-over-empty-lines)
6003 (setq end (point))
6004 (goto-char beg0)
6005 (when (> end beg)
6006 (setq org-subtree-clip-folded folded)
6007 (when (or cut force-store-markers)
6008 (org-save-markers-in-region beg end))
6009 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6010 (setq org-subtree-clip (current-kill 0))
6011 (message "%s: Subtree(s) with %d characters"
6012 (if cut "Cut" "Copied")
6013 (length org-subtree-clip)))))
6015 (defun org-paste-subtree (&optional level tree for-yank)
6016 "Paste the clipboard as a subtree, with modification of headline level.
6017 The entire subtree is promoted or demoted in order to match a new headline
6018 level.
6020 If the cursor is at the beginning of a headline, the same level as
6021 that headline is used to paste the tree
6023 If not, the new level is derived from the *visible* headings
6024 before and after the insertion point, and taken to be the inferior headline
6025 level of the two. So if the previous visible heading is level 3 and the
6026 next is level 4 (or vice versa), level 4 will be used for insertion.
6027 This makes sure that the subtree remains an independent subtree and does
6028 not swallow low level entries.
6030 You can also force a different level, either by using a numeric prefix
6031 argument, or by inserting the heading marker by hand. For example, if the
6032 cursor is after \"*****\", then the tree will be shifted to level 5.
6034 If optional TREE is given, use this text instead of the kill ring.
6036 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6037 move back over whitespace before inserting, and move point to the end of
6038 the inserted text when done."
6039 (interactive "P")
6040 (unless (org-kill-is-subtree-p tree)
6041 (error "%s"
6042 (substitute-command-keys
6043 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6044 (let* ((visp (not (org-invisible-p)))
6045 (txt (or tree (and kill-ring (current-kill 0))))
6046 (^re (concat "^\\(" outline-regexp "\\)"))
6047 (re (concat "\\(" outline-regexp "\\)"))
6048 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6050 (old-level (if (string-match ^re txt)
6051 (- (match-end 0) (match-beginning 0) 1)
6052 -1))
6053 (force-level (cond (level (prefix-numeric-value level))
6054 ((and (looking-at "[ \t]*$")
6055 (string-match
6056 ^re_ (buffer-substring
6057 (point-at-bol) (point))))
6058 (- (match-end 1) (match-beginning 1)))
6059 ((and (bolp)
6060 (looking-at org-outline-regexp))
6061 (- (match-end 0) (point) 1))
6062 (t nil)))
6063 (previous-level (save-excursion
6064 (condition-case nil
6065 (progn
6066 (outline-previous-visible-heading 1)
6067 (if (looking-at re)
6068 (- (match-end 0) (match-beginning 0) 1)
6070 (error 1))))
6071 (next-level (save-excursion
6072 (condition-case nil
6073 (progn
6074 (or (looking-at outline-regexp)
6075 (outline-next-visible-heading 1))
6076 (if (looking-at re)
6077 (- (match-end 0) (match-beginning 0) 1)
6079 (error 1))))
6080 (new-level (or force-level (max previous-level next-level)))
6081 (shift (if (or (= old-level -1)
6082 (= new-level -1)
6083 (= old-level new-level))
6085 (- new-level old-level)))
6086 (delta (if (> shift 0) -1 1))
6087 (func (if (> shift 0) 'org-demote 'org-promote))
6088 (org-odd-levels-only nil)
6089 beg end newend)
6090 ;; Remove the forced level indicator
6091 (if force-level
6092 (delete-region (point-at-bol) (point)))
6093 ;; Paste
6094 (beginning-of-line 1)
6095 (unless for-yank (org-back-over-empty-lines))
6096 (setq beg (point))
6097 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6098 (insert-before-markers txt)
6099 (unless (string-match "\n\\'" txt) (insert "\n"))
6100 (setq newend (point))
6101 (org-reinstall-markers-in-region beg)
6102 (setq end (point))
6103 (goto-char beg)
6104 (skip-chars-forward " \t\n\r")
6105 (setq beg (point))
6106 (if (and (org-invisible-p) visp)
6107 (save-excursion (outline-show-heading)))
6108 ;; Shift if necessary
6109 (unless (= shift 0)
6110 (save-restriction
6111 (narrow-to-region beg end)
6112 (while (not (= shift 0))
6113 (org-map-region func (point-min) (point-max))
6114 (setq shift (+ delta shift)))
6115 (goto-char (point-min))
6116 (setq newend (point-max))))
6117 (when (or (interactive-p) for-yank)
6118 (message "Clipboard pasted as level %d subtree" new-level))
6119 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6120 kill-ring
6121 (eq org-subtree-clip (current-kill 0))
6122 org-subtree-clip-folded)
6123 ;; The tree was folded before it was killed/copied
6124 (hide-subtree))
6125 (and for-yank (goto-char newend))))
6127 (defun org-kill-is-subtree-p (&optional txt)
6128 "Check if the current kill is an outline subtree, or a set of trees.
6129 Returns nil if kill does not start with a headline, or if the first
6130 headline level is not the largest headline level in the tree.
6131 So this will actually accept several entries of equal levels as well,
6132 which is OK for `org-paste-subtree'.
6133 If optional TXT is given, check this string instead of the current kill."
6134 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6135 (start-level (and kill
6136 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6137 org-outline-regexp "\\)")
6138 kill)
6139 (- (match-end 2) (match-beginning 2) 1)))
6140 (re (concat "^" org-outline-regexp))
6141 (start (1+ (or (match-beginning 2) -1))))
6142 (if (not start-level)
6143 (progn
6144 nil) ;; does not even start with a heading
6145 (catch 'exit
6146 (while (setq start (string-match re kill (1+ start)))
6147 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6148 (throw 'exit nil)))
6149 t))))
6151 (defvar org-markers-to-move nil
6152 "Markers that should be moved with a cut-and-paste operation.
6153 Those markers are stored together with their positions relative to
6154 the start of the region.")
6156 (defun org-save-markers-in-region (beg end)
6157 "Check markers in region.
6158 If these markers are between BEG and END, record their position relative
6159 to BEG, so that after moving the block of text, we can put the markers back
6160 into place.
6161 This function gets called just before an entry or tree gets cut from the
6162 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6163 called immediately, to move the markers with the entries."
6164 (setq org-markers-to-move nil)
6165 (when (featurep 'org-clock)
6166 (org-clock-save-markers-for-cut-and-paste beg end))
6167 (when (featurep 'org-agenda)
6168 (org-agenda-save-markers-for-cut-and-paste beg end)))
6170 (defun org-check-and-save-marker (marker beg end)
6171 "Check if MARKER is between BEG and END.
6172 If yes, remember the marker and the distance to BEG."
6173 (when (and (marker-buffer marker)
6174 (equal (marker-buffer marker) (current-buffer)))
6175 (if (and (>= marker beg) (< marker end))
6176 (push (cons marker (- marker beg)) org-markers-to-move))))
6178 (defun org-reinstall-markers-in-region (beg)
6179 "Move all remembered markers to their position relative to BEG."
6180 (mapc (lambda (x)
6181 (move-marker (car x) (+ beg (cdr x))))
6182 org-markers-to-move)
6183 (setq org-markers-to-move nil))
6185 (defun org-narrow-to-subtree ()
6186 "Narrow buffer to the current subtree."
6187 (interactive)
6188 (save-excursion
6189 (save-match-data
6190 (narrow-to-region
6191 (progn (org-back-to-heading t) (point))
6192 (progn (org-end-of-subtree t) (point))))))
6194 (defun org-clone-subtree-with-time-shift (n &optional shift)
6195 "Clone the task (subtree) at point N times.
6196 The clones will be inserted as siblings.
6198 In interactive use, the user will be prompted for the number of clones
6199 to be produced, and for a time SHIFT, which may be a repeater as used
6200 in time stamps, for example `+3d'.
6202 When a valid repeater is given and the entry contains any time stamps,
6203 the clones will become a sequence in time, with time stamps in the
6204 subtree shifted for each clone produced. If SHIFT is nil or the
6205 empty string, time stamps will be left alone.
6207 If the original subtree did contain time stamps with a repeater,
6208 the following will happen:
6209 - the repeater will be removed in each clone
6210 - an additional clone will be produced, with the current, unshifted
6211 date(s) in the entry.
6212 - the original entry will be placed *after* all the clones, with
6213 repeater intact.
6214 - the start days in the repeater in the original entry will be shifted
6215 to past the last clone.
6216 I this way you can spell out a number of instances of a repeating task,
6217 and still retain the repeater to cover future instances of the task."
6218 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6219 (let (beg end template task
6220 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6221 (if (not (and (integerp n) (> n 0)))
6222 (error "Invalid number of replications %s" n))
6223 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6224 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6225 shift)))
6226 (error "Invalid shift specification %s" shift))
6227 (when doshift
6228 (setq shift-n (string-to-number (match-string 1 shift))
6229 shift-what (cdr (assoc (match-string 2 shift)
6230 '(("d" . day) ("w" . week)
6231 ("m" . month) ("y" . year))))))
6232 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6233 (setq nmin 1 nmax n)
6234 (org-back-to-heading t)
6235 (setq beg (point))
6236 (org-end-of-subtree t t)
6237 (setq end (point))
6238 (setq template (buffer-substring beg end))
6239 (when (and doshift
6240 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6241 (delete-region beg end)
6242 (setq end beg)
6243 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6244 (goto-char end)
6245 (loop for n from nmin to nmax do
6246 (if (not doshift)
6247 (setq task template)
6248 (with-temp-buffer
6249 (insert template)
6250 (org-mode)
6251 (goto-char (point-min))
6252 (while (re-search-forward org-ts-regexp-both nil t)
6253 (org-timestamp-change (* n shift-n) shift-what))
6254 (unless (= n n-no-remove)
6255 (goto-char (point-min))
6256 (while (re-search-forward org-ts-regexp nil t)
6257 (save-excursion
6258 (goto-char (match-beginning 0))
6259 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6260 (delete-region (match-beginning 1) (match-end 1))))))
6261 (setq task (buffer-string))))
6262 (insert task))
6263 (goto-char beg)))
6265 ;;; Outline Sorting
6267 (defun org-sort (with-case)
6268 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6269 Optional argument WITH-CASE means sort case-sensitively.
6270 With a double prefix argument, also remove duplicate entries."
6271 (interactive "P")
6272 (if (org-at-table-p)
6273 (org-call-with-arg 'org-table-sort-lines with-case)
6274 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6276 (defun org-sort-remove-invisible (s)
6277 (remove-text-properties 0 (length s) org-rm-props s)
6278 (while (string-match org-bracket-link-regexp s)
6279 (setq s (replace-match (if (match-end 2)
6280 (match-string 3 s)
6281 (match-string 1 s)) t t s)))
6284 (defvar org-priority-regexp) ; defined later in the file
6286 (defvar org-after-sorting-entries-or-items-hook nil
6287 "Hook that is run after a bunch of entries or items have been sorted.
6288 When children are sorted, the cursor is in the parent line when this
6289 hook gets called. When a region or a plain list is sorted, the cursor
6290 will be in the first entry of the sorted region/list.")
6292 (defun org-sort-entries-or-items
6293 (&optional with-case sorting-type getkey-func compare-func property)
6294 "Sort entries on a certain level of an outline tree, or plain list items.
6295 If there is an active region, the entries in the region are sorted.
6296 Else, if the cursor is before the first entry, sort the top-level items.
6297 Else, the children of the entry at point are sorted.
6298 If the cursor is at the first item in a plain list, the list items will be
6299 sorted.
6301 Sorting can be alphabetically, numerically, by date/time as given by
6302 a time stamp, by a property or by priority.
6304 The command prompts for the sorting type unless it has been given to the
6305 function through the SORTING-TYPE argument, which needs to a character,
6306 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6307 precise meaning of each character:
6309 n Numerically, by converting the beginning of the entry/item to a number.
6310 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6311 t By date/time, either the first active time stamp in the entry, or, if
6312 none exist, by the first inactive one.
6313 In items, only the first line will be chekced.
6314 s By the scheduled date/time.
6315 d By deadline date/time.
6316 c By creation time, which is assumed to be the first inactive time stamp
6317 at the beginning of a line.
6318 p By priority according to the cookie.
6319 r By the value of a property.
6321 Capital letters will reverse the sort order.
6323 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6324 called with point at the beginning of the record. It must return either
6325 a string or a number that should serve as the sorting key for that record.
6327 Comparing entries ignores case by default. However, with an optional argument
6328 WITH-CASE, the sorting considers case as well."
6329 (interactive "P")
6330 (let ((case-func (if with-case 'identity 'downcase))
6331 start beg end stars re re2
6332 txt what tmp plain-list-p)
6333 ;; Find beginning and end of region to sort
6334 (cond
6335 ((org-region-active-p)
6336 ;; we will sort the region
6337 (setq end (region-end)
6338 what "region")
6339 (goto-char (region-beginning))
6340 (if (not (org-on-heading-p)) (outline-next-heading))
6341 (setq start (point)))
6342 ((org-at-item-p)
6343 ;; we will sort this plain list
6344 (org-beginning-of-item-list) (setq start (point))
6345 (org-end-of-item-list) (setq end (point))
6346 (goto-char start)
6347 (setq plain-list-p t
6348 what "plain list"))
6349 ((or (org-on-heading-p)
6350 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6351 ;; we will sort the children of the current headline
6352 (org-back-to-heading)
6353 (setq start (point)
6354 end (progn (org-end-of-subtree t t)
6355 (org-back-over-empty-lines)
6356 (point))
6357 what "children")
6358 (goto-char start)
6359 (show-subtree)
6360 (outline-next-heading))
6362 ;; we will sort the top-level entries in this file
6363 (goto-char (point-min))
6364 (or (org-on-heading-p) (outline-next-heading))
6365 (setq start (point) end (point-max) what "top-level")
6366 (goto-char start)
6367 (show-all)))
6369 (setq beg (point))
6370 (if (>= beg end) (error "Nothing to sort"))
6372 (unless plain-list-p
6373 (looking-at "\\(\\*+\\)")
6374 (setq stars (match-string 1)
6375 re (concat "^" (regexp-quote stars) " +")
6376 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6377 txt (buffer-substring beg end))
6378 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6379 (if (and (not (equal stars "*")) (string-match re2 txt))
6380 (error "Region to sort contains a level above the first entry")))
6382 (unless sorting-type
6383 (message
6384 (if plain-list-p
6385 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6386 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6387 [t]ime [s]cheduled [d]eadline [c]reated
6388 A/N/T/S/D/C/P/O/F means reversed:")
6389 what)
6390 (setq sorting-type (read-char-exclusive))
6392 (and (= (downcase sorting-type) ?f)
6393 (setq getkey-func
6394 (org-ido-completing-read "Sort using function: "
6395 obarray 'fboundp t nil nil))
6396 (setq getkey-func (intern getkey-func)))
6398 (and (= (downcase sorting-type) ?r)
6399 (setq property
6400 (org-ido-completing-read "Property: "
6401 (mapcar 'list (org-buffer-property-keys t))
6402 nil t))))
6404 (message "Sorting entries...")
6406 (save-restriction
6407 (narrow-to-region start end)
6409 (let ((dcst (downcase sorting-type))
6410 (case-fold-search nil)
6411 (now (current-time)))
6412 (sort-subr
6413 (/= dcst sorting-type)
6414 ;; This function moves to the beginning character of the "record" to
6415 ;; be sorted.
6416 (if plain-list-p
6417 (lambda nil
6418 (if (org-at-item-p) t (goto-char (point-max))))
6419 (lambda nil
6420 (if (re-search-forward re nil t)
6421 (goto-char (match-beginning 0))
6422 (goto-char (point-max)))))
6423 ;; This function moves to the last character of the "record" being
6424 ;; sorted.
6425 (if plain-list-p
6426 'org-end-of-item
6427 (lambda nil
6428 (save-match-data
6429 (condition-case nil
6430 (outline-forward-same-level 1)
6431 (error
6432 (goto-char (point-max)))))))
6434 ;; This function returns the value that gets sorted against.
6435 (if plain-list-p
6436 (lambda nil
6437 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6438 (cond
6439 ((= dcst ?n)
6440 (string-to-number (buffer-substring (match-end 0)
6441 (point-at-eol))))
6442 ((= dcst ?a)
6443 (buffer-substring (match-end 0) (point-at-eol)))
6444 ((= dcst ?t)
6445 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6446 (re-search-forward org-ts-regexp-both
6447 (point-at-eol) t))
6448 (org-time-string-to-seconds (match-string 0))
6449 (time-to-seconds now)))
6450 ((= dcst ?f)
6451 (if getkey-func
6452 (progn
6453 (setq tmp (funcall getkey-func))
6454 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6455 tmp)
6456 (error "Invalid key function `%s'" getkey-func)))
6457 (t (error "Invalid sorting type `%c'" sorting-type)))))
6458 (lambda nil
6459 (cond
6460 ((= dcst ?n)
6461 (if (looking-at org-complex-heading-regexp)
6462 (string-to-number (match-string 4))
6463 nil))
6464 ((= dcst ?a)
6465 (if (looking-at org-complex-heading-regexp)
6466 (funcall case-func (match-string 4))
6467 nil))
6468 ((= dcst ?t)
6469 (let ((end (save-excursion (outline-next-heading) (point))))
6470 (if (or (re-search-forward org-ts-regexp end t)
6471 (re-search-forward org-ts-regexp-both end t))
6472 (org-time-string-to-seconds (match-string 0))
6473 (time-to-seconds now))))
6474 ((= dcst ?c)
6475 (let ((end (save-excursion (outline-next-heading) (point))))
6476 (if (re-search-forward
6477 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6478 end t)
6479 (org-time-string-to-seconds (match-string 0))
6480 (time-to-seconds now))))
6481 ((= dcst ?s)
6482 (let ((end (save-excursion (outline-next-heading) (point))))
6483 (if (re-search-forward org-scheduled-time-regexp end t)
6484 (org-time-string-to-seconds (match-string 1))
6485 (time-to-seconds now))))
6486 ((= dcst ?d)
6487 (let ((end (save-excursion (outline-next-heading) (point))))
6488 (if (re-search-forward org-deadline-time-regexp end t)
6489 (org-time-string-to-seconds (match-string 1))
6490 (time-to-seconds now))))
6491 ((= dcst ?p)
6492 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6493 (string-to-char (match-string 2))
6494 org-default-priority))
6495 ((= dcst ?r)
6496 (or (org-entry-get nil property) ""))
6497 ((= dcst ?o)
6498 (if (looking-at org-complex-heading-regexp)
6499 (- 9999 (length (member (match-string 2)
6500 org-todo-keywords-1)))))
6501 ((= dcst ?f)
6502 (if getkey-func
6503 (progn
6504 (setq tmp (funcall getkey-func))
6505 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6506 tmp)
6507 (error "Invalid key function `%s'" getkey-func)))
6508 (t (error "Invalid sorting type `%c'" sorting-type)))))
6510 (cond
6511 ((= dcst ?a) 'string<)
6512 ((= dcst ?f) compare-func)
6513 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6514 (t nil)))))
6515 (run-hooks 'org-after-sorting-entries-or-items-hook)
6516 (message "Sorting entries...done")))
6518 (defun org-do-sort (table what &optional with-case sorting-type)
6519 "Sort TABLE of WHAT according to SORTING-TYPE.
6520 The user will be prompted for the SORTING-TYPE if the call to this
6521 function does not specify it. WHAT is only for the prompt, to indicate
6522 what is being sorted. The sorting key will be extracted from
6523 the car of the elements of the table.
6524 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6525 (unless sorting-type
6526 (message
6527 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6528 what)
6529 (setq sorting-type (read-char-exclusive)))
6530 (let ((dcst (downcase sorting-type))
6531 extractfun comparefun)
6532 ;; Define the appropriate functions
6533 (cond
6534 ((= dcst ?n)
6535 (setq extractfun 'string-to-number
6536 comparefun (if (= dcst sorting-type) '< '>)))
6537 ((= dcst ?a)
6538 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6539 (lambda(x) (downcase (org-sort-remove-invisible x))))
6540 comparefun (if (= dcst sorting-type)
6541 'string<
6542 (lambda (a b) (and (not (string< a b))
6543 (not (string= a b)))))))
6544 ((= dcst ?t)
6545 (setq extractfun
6546 (lambda (x)
6547 (if (or (string-match org-ts-regexp x)
6548 (string-match org-ts-regexp-both x))
6549 (time-to-seconds
6550 (org-time-string-to-time (match-string 0 x)))
6552 comparefun (if (= dcst sorting-type) '< '>)))
6553 (t (error "Invalid sorting type `%c'" sorting-type)))
6555 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6556 table)
6557 (lambda (a b) (funcall comparefun (car a) (car b))))))
6560 ;;; The orgstruct minor mode
6562 ;; Define a minor mode which can be used in other modes in order to
6563 ;; integrate the org-mode structure editing commands.
6565 ;; This is really a hack, because the org-mode structure commands use
6566 ;; keys which normally belong to the major mode. Here is how it
6567 ;; works: The minor mode defines all the keys necessary to operate the
6568 ;; structure commands, but wraps the commands into a function which
6569 ;; tests if the cursor is currently at a headline or a plain list
6570 ;; item. If that is the case, the structure command is used,
6571 ;; temporarily setting many Org-mode variables like regular
6572 ;; expressions for filling etc. However, when any of those keys is
6573 ;; used at a different location, function uses `key-binding' to look
6574 ;; up if the key has an associated command in another currently active
6575 ;; keymap (minor modes, major mode, global), and executes that
6576 ;; command. There might be problems if any of the keys is otherwise
6577 ;; used as a prefix key.
6579 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6580 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6581 ;; addresses this by checking explicitly for both bindings.
6583 (defvar orgstruct-mode-map (make-sparse-keymap)
6584 "Keymap for the minor `orgstruct-mode'.")
6586 (defvar org-local-vars nil
6587 "List of local variables, for use by `orgstruct-mode'")
6589 ;;;###autoload
6590 (define-minor-mode orgstruct-mode
6591 "Toggle the minor more `orgstruct-mode'.
6592 This mode is for using Org-mode structure commands in other modes.
6593 The following key behave as if Org-mode was active, if the cursor
6594 is on a headline, or on a plain list item (both in the definition
6595 of Org-mode).
6597 M-up Move entry/item up
6598 M-down Move entry/item down
6599 M-left Promote
6600 M-right Demote
6601 M-S-up Move entry/item up
6602 M-S-down Move entry/item down
6603 M-S-left Promote subtree
6604 M-S-right Demote subtree
6605 M-q Fill paragraph and items like in Org-mode
6606 C-c ^ Sort entries
6607 C-c - Cycle list bullet
6608 TAB Cycle item visibility
6609 M-RET Insert new heading/item
6610 S-M-RET Insert new TODO heading / Checkbox item
6611 C-c C-c Set tags / toggle checkbox"
6612 nil " OrgStruct" nil
6613 (org-load-modules-maybe)
6614 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6616 ;;;###autoload
6617 (defun turn-on-orgstruct ()
6618 "Unconditionally turn on `orgstruct-mode'."
6619 (orgstruct-mode 1))
6621 (defun orgstruct++-mode (&optional arg)
6622 "Toggle `orgstruct-mode', the enhanced version of it.
6623 In addition to setting orgstruct-mode, this also exports all indentation and
6624 autofilling variables from org-mode into the buffer. It will also
6625 recognize item context in multiline items.
6626 Note that turning off orgstruct-mode will *not* remove the
6627 indentation/paragraph settings. This can only be done by refreshing the
6628 major mode, for example with \[normal-mode]."
6629 (interactive "P")
6630 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6631 (if (< arg 1)
6632 (orgstruct-mode -1)
6633 (orgstruct-mode 1)
6634 (let (var val)
6635 (mapc
6636 (lambda (x)
6637 (when (string-match
6638 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6639 (symbol-name (car x)))
6640 (setq var (car x) val (nth 1 x))
6641 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6642 org-local-vars)
6643 (org-set-local 'orgstruct-is-++ t))))
6645 (defvar orgstruct-is-++ nil
6646 "Is orgstruct-mode in ++ version in the current-buffer?")
6647 (make-variable-buffer-local 'orgstruct-is-++)
6649 ;;;###autoload
6650 (defun turn-on-orgstruct++ ()
6651 "Unconditionally turn on `orgstruct++-mode'."
6652 (orgstruct++-mode 1))
6654 (defun orgstruct-error ()
6655 "Error when there is no default binding for a structure key."
6656 (interactive)
6657 (error "This key has no function outside structure elements"))
6659 (defun orgstruct-setup ()
6660 "Setup orgstruct keymaps."
6661 (let ((nfunc 0)
6662 (bindings
6663 (list
6664 '([(meta up)] org-metaup)
6665 '([(meta down)] org-metadown)
6666 '([(meta left)] org-metaleft)
6667 '([(meta right)] org-metaright)
6668 '([(meta shift up)] org-shiftmetaup)
6669 '([(meta shift down)] org-shiftmetadown)
6670 '([(meta shift left)] org-shiftmetaleft)
6671 '([(meta shift right)] org-shiftmetaright)
6672 '([?\e (up)] org-metaup)
6673 '([?\e (down)] org-metadown)
6674 '([?\e (left)] org-metaleft)
6675 '([?\e (right)] org-metaright)
6676 '([?\e (shift up)] org-shiftmetaup)
6677 '([?\e (shift down)] org-shiftmetadown)
6678 '([?\e (shift left)] org-shiftmetaleft)
6679 '([?\e (shift right)] org-shiftmetaright)
6680 '([(shift up)] org-shiftup)
6681 '([(shift down)] org-shiftdown)
6682 '([(shift left)] org-shiftleft)
6683 '([(shift right)] org-shiftright)
6684 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6685 '("\M-q" fill-paragraph)
6686 '("\C-c^" org-sort)
6687 '("\C-c-" org-cycle-list-bullet)))
6688 elt key fun cmd)
6689 (while (setq elt (pop bindings))
6690 (setq nfunc (1+ nfunc))
6691 (setq key (org-key (car elt))
6692 fun (nth 1 elt)
6693 cmd (orgstruct-make-binding fun nfunc key))
6694 (org-defkey orgstruct-mode-map key cmd))
6696 ;; Special treatment needed for TAB and RET
6697 (org-defkey orgstruct-mode-map [(tab)]
6698 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6699 (org-defkey orgstruct-mode-map "\C-i"
6700 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6702 (org-defkey orgstruct-mode-map "\M-\C-m"
6703 (orgstruct-make-binding 'org-insert-heading 105
6704 "\M-\C-m" [(meta return)]))
6705 (org-defkey orgstruct-mode-map [(meta return)]
6706 (orgstruct-make-binding 'org-insert-heading 106
6707 [(meta return)] "\M-\C-m"))
6709 (org-defkey orgstruct-mode-map [(shift meta return)]
6710 (orgstruct-make-binding 'org-insert-todo-heading 107
6711 [(meta return)] "\M-\C-m"))
6713 (org-defkey orgstruct-mode-map "\e\C-m"
6714 (orgstruct-make-binding 'org-insert-heading 108
6715 "\e\C-m" [?\e (return)]))
6716 (org-defkey orgstruct-mode-map [?\e (return)]
6717 (orgstruct-make-binding 'org-insert-heading 109
6718 [?\e (return)] "\e\C-m"))
6719 (org-defkey orgstruct-mode-map [?\e (shift return)]
6720 (orgstruct-make-binding 'org-insert-todo-heading 110
6721 [?\e (return)] "\e\C-m"))
6723 (unless org-local-vars
6724 (setq org-local-vars (org-get-local-variables)))
6728 (defun orgstruct-make-binding (fun n &rest keys)
6729 "Create a function for binding in the structure minor mode.
6730 FUN is the command to call inside a table. N is used to create a unique
6731 command name. KEYS are keys that should be checked in for a command
6732 to execute outside of tables."
6733 (eval
6734 (list 'defun
6735 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6736 '(arg)
6737 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6738 "Outside of structure, run the binding of `"
6739 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6740 "'.")
6741 '(interactive "p")
6742 (list 'if
6743 `(org-context-p 'headline 'item
6744 (and orgstruct-is-++
6745 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6746 'item-body))
6747 (list 'org-run-like-in-org-mode (list 'quote fun))
6748 (list 'let '(orgstruct-mode)
6749 (list 'call-interactively
6750 (append '(or)
6751 (mapcar (lambda (k)
6752 (list 'key-binding k))
6753 keys)
6754 '('orgstruct-error))))))))
6756 (defun org-context-p (&rest contexts)
6757 "Check if local context is any of CONTEXTS.
6758 Possible values in the list of contexts are `table', `headline', and `item'."
6759 (let ((pos (point)))
6760 (goto-char (point-at-bol))
6761 (prog1 (or (and (memq 'table contexts)
6762 (looking-at "[ \t]*|"))
6763 (and (memq 'headline contexts)
6764 ;;????????? (looking-at "\\*+"))
6765 (looking-at outline-regexp))
6766 (and (memq 'item contexts)
6767 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6768 (and (memq 'item-body contexts)
6769 (org-in-item-p)))
6770 (goto-char pos))))
6772 (defun org-get-local-variables ()
6773 "Return a list of all local variables in an org-mode buffer."
6774 (let (varlist)
6775 (with-current-buffer (get-buffer-create "*Org tmp*")
6776 (erase-buffer)
6777 (org-mode)
6778 (setq varlist (buffer-local-variables)))
6779 (kill-buffer "*Org tmp*")
6780 (delq nil
6781 (mapcar
6782 (lambda (x)
6783 (setq x
6784 (if (symbolp x)
6785 (list x)
6786 (list (car x) (list 'quote (cdr x)))))
6787 (if (string-match
6788 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6789 (symbol-name (car x)))
6790 x nil))
6791 varlist))))
6793 ;;;###autoload
6794 (defun org-run-like-in-org-mode (cmd)
6795 "Run a command, pretending that the current buffer is in Org-mode.
6796 This will temporarily bind local variables that are typically bound in
6797 Org-mode to the values they have in Org-mode, and then interactively
6798 call CMD."
6799 (org-load-modules-maybe)
6800 (unless org-local-vars
6801 (setq org-local-vars (org-get-local-variables)))
6802 (eval (list 'let org-local-vars
6803 (list 'call-interactively (list 'quote cmd)))))
6805 ;;;; Archiving
6807 (defun org-get-category (&optional pos)
6808 "Get the category applying to position POS."
6809 (get-text-property (or pos (point)) 'org-category))
6811 (defun org-refresh-category-properties ()
6812 "Refresh category text properties in the buffer."
6813 (let ((def-cat (cond
6814 ((null org-category)
6815 (if buffer-file-name
6816 (file-name-sans-extension
6817 (file-name-nondirectory buffer-file-name))
6818 "???"))
6819 ((symbolp org-category) (symbol-name org-category))
6820 (t org-category)))
6821 beg end cat pos optionp)
6822 (org-unmodified
6823 (save-excursion
6824 (save-restriction
6825 (widen)
6826 (goto-char (point-min))
6827 (put-text-property (point) (point-max) 'org-category def-cat)
6828 (while (re-search-forward
6829 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6830 (setq pos (match-end 0)
6831 optionp (equal (char-after (match-beginning 0)) ?#)
6832 cat (org-trim (match-string 2)))
6833 (if optionp
6834 (setq beg (point-at-bol) end (point-max))
6835 (org-back-to-heading t)
6836 (setq beg (point) end (org-end-of-subtree t t)))
6837 (put-text-property beg end 'org-category cat)
6838 (goto-char pos)))))))
6841 ;;;; Link Stuff
6843 ;;; Link abbreviations
6845 (defun org-link-expand-abbrev (link)
6846 "Apply replacements as defined in `org-link-abbrev-alist."
6847 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6848 (let* ((key (match-string 1 link))
6849 (as (or (assoc key org-link-abbrev-alist-local)
6850 (assoc key org-link-abbrev-alist)))
6851 (tag (and (match-end 2) (match-string 3 link)))
6852 rpl)
6853 (if (not as)
6854 link
6855 (setq rpl (cdr as))
6856 (cond
6857 ((symbolp rpl) (funcall rpl tag))
6858 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6859 ((string-match "%h" rpl)
6860 (replace-match (url-hexify-string (or tag "")) t t rpl))
6861 (t (concat rpl tag)))))
6862 link))
6864 ;;; Storing and inserting links
6866 (defvar org-insert-link-history nil
6867 "Minibuffer history for links inserted with `org-insert-link'.")
6869 (defvar org-stored-links nil
6870 "Contains the links stored with `org-store-link'.")
6872 (defvar org-store-link-plist nil
6873 "Plist with info about the most recently link created with `org-store-link'.")
6875 (defvar org-link-protocols nil
6876 "Link protocols added to Org-mode using `org-add-link-type'.")
6878 (defvar org-store-link-functions nil
6879 "List of functions that are called to create and store a link.
6880 Each function will be called in turn until one returns a non-nil
6881 value. Each function should check if it is responsible for creating
6882 this link (for example by looking at the major mode).
6883 If not, it must exit and return nil.
6884 If yes, it should return a non-nil value after a calling
6885 `org-store-link-props' with a list of properties and values.
6886 Special properties are:
6888 :type The link prefix. like \"http\". This must be given.
6889 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6890 This is obligatory as well.
6891 :description Optional default description for the second pair
6892 of brackets in an Org-mode link. The user can still change
6893 this when inserting this link into an Org-mode buffer.
6895 In addition to these, any additional properties can be specified
6896 and then used in remember templates.")
6898 (defun org-add-link-type (type &optional follow export)
6899 "Add TYPE to the list of `org-link-types'.
6900 Re-compute all regular expressions depending on `org-link-types'
6902 FOLLOW and EXPORT are two functions.
6904 FOLLOW should take the link path as the single argument and do whatever
6905 is necessary to follow the link, for example find a file or display
6906 a mail message.
6908 EXPORT should format the link path for export to one of the export formats.
6909 It should be a function accepting three arguments:
6911 path the path of the link, the text after the prefix (like \"http:\")
6912 desc the description of the link, if any, nil if there was no description
6913 format the export format, a symbol like `html' or `latex'.
6915 The function may use the FORMAT information to return different values
6916 depending on the format. The return value will be put literally into
6917 the exported file.
6918 Org-mode has a built-in default for exporting links. If you are happy with
6919 this default, there is no need to define an export function for the link
6920 type. For a simple example of an export function, see `org-bbdb.el'."
6921 (add-to-list 'org-link-types type t)
6922 (org-make-link-regexps)
6923 (if (assoc type org-link-protocols)
6924 (setcdr (assoc type org-link-protocols) (list follow export))
6925 (push (list type follow export) org-link-protocols)))
6927 ;;;###autoload
6928 (defun org-store-link (arg)
6929 "\\<org-mode-map>Store an org-link to the current location.
6930 This link is added to `org-stored-links' and can later be inserted
6931 into an org-buffer with \\[org-insert-link].
6933 For some link types, a prefix arg is interpreted:
6934 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6935 For file links, arg negates `org-context-in-file-links'."
6936 (interactive "P")
6937 (org-load-modules-maybe)
6938 (setq org-store-link-plist nil) ; reset
6939 (let (link cpltxt desc description search txt custom-id)
6940 (cond
6942 ((run-hook-with-args-until-success 'org-store-link-functions)
6943 (setq link (plist-get org-store-link-plist :link)
6944 desc (or (plist-get org-store-link-plist :description) link)))
6946 ((equal (buffer-name) "*Org Edit Src Example*")
6947 (let (label gc)
6948 (while (or (not label)
6949 (save-excursion
6950 (save-restriction
6951 (widen)
6952 (goto-char (point-min))
6953 (re-search-forward
6954 (regexp-quote (format org-coderef-label-format label))
6955 nil t))))
6956 (when label (message "Label exists already") (sit-for 2))
6957 (setq label (read-string "Code line label: " label)))
6958 (end-of-line 1)
6959 (setq link (format org-coderef-label-format label))
6960 (setq gc (- 79 (length link)))
6961 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6962 (insert link)
6963 (setq link (concat "(" label ")") desc nil)))
6965 ((eq major-mode 'calendar-mode)
6966 (let ((cd (calendar-cursor-to-date)))
6967 (setq link
6968 (format-time-string
6969 (car org-time-stamp-formats)
6970 (apply 'encode-time
6971 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6972 nil nil nil))))
6973 (org-store-link-props :type "calendar" :date cd)))
6975 ((eq major-mode 'w3-mode)
6976 (setq cpltxt (if (and (buffer-name)
6977 (not (string-match "Untitled" (buffer-name))))
6978 (buffer-name)
6979 (url-view-url t))
6980 link (org-make-link (url-view-url t)))
6981 (org-store-link-props :type "w3" :url (url-view-url t)))
6983 ((eq major-mode 'w3m-mode)
6984 (setq cpltxt (or w3m-current-title w3m-current-url)
6985 link (org-make-link w3m-current-url))
6986 (org-store-link-props :type "w3m" :url (url-view-url t)))
6988 ((setq search (run-hook-with-args-until-success
6989 'org-create-file-search-functions))
6990 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6991 "::" search))
6992 (setq cpltxt (or description link)))
6994 ((eq major-mode 'image-mode)
6995 (setq cpltxt (concat "file:"
6996 (abbreviate-file-name buffer-file-name))
6997 link (org-make-link cpltxt))
6998 (org-store-link-props :type "image" :file buffer-file-name))
7000 ((eq major-mode 'dired-mode)
7001 ;; link to the file in the current line
7002 (setq cpltxt (concat "file:"
7003 (abbreviate-file-name
7004 (expand-file-name
7005 (dired-get-filename nil t))))
7006 link (org-make-link cpltxt)))
7008 ((and buffer-file-name (org-mode-p))
7009 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7010 (cond
7011 ((org-in-regexp "<<\\(.*?\\)>>")
7012 (setq cpltxt
7013 (concat "file:"
7014 (abbreviate-file-name buffer-file-name)
7015 "::" (match-string 1))
7016 link (org-make-link cpltxt)))
7017 ((and (featurep 'org-id)
7018 (or (eq org-link-to-org-use-id t)
7019 (and (eq org-link-to-org-use-id 'create-if-interactive)
7020 (interactive-p))
7021 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7022 (interactive-p)
7023 (not custom-id))
7024 (and org-link-to-org-use-id
7025 (condition-case nil
7026 (org-entry-get nil "ID")
7027 (error nil)))))
7028 ;; We can make a link using the ID.
7029 (setq link (condition-case nil
7030 (prog1 (org-id-store-link)
7031 (setq desc (plist-get org-store-link-plist
7032 :description)))
7033 (error
7034 ;; probably before first headline, link to file only
7035 (concat "file:"
7036 (abbreviate-file-name buffer-file-name))))))
7038 ;; Just link to current headline
7039 (setq cpltxt (concat "file:"
7040 (abbreviate-file-name buffer-file-name)))
7041 ;; Add a context search string
7042 (when (org-xor org-context-in-file-links arg)
7043 (setq txt (cond
7044 ((org-on-heading-p) nil)
7045 ((org-region-active-p)
7046 (buffer-substring (region-beginning) (region-end)))
7047 (t nil)))
7048 (when (or (null txt) (string-match "\\S-" txt))
7049 (setq cpltxt
7050 (concat cpltxt "::"
7051 (condition-case nil
7052 (org-make-org-heading-search-string txt)
7053 (error "")))
7054 desc (or (nth 4 (org-heading-components)) "NONE"))))
7055 (if (string-match "::\\'" cpltxt)
7056 (setq cpltxt (substring cpltxt 0 -2)))
7057 (setq link (org-make-link cpltxt)))))
7059 ((buffer-file-name (buffer-base-buffer))
7060 ;; Just link to this file here.
7061 (setq cpltxt (concat "file:"
7062 (abbreviate-file-name
7063 (buffer-file-name (buffer-base-buffer)))))
7064 ;; Add a context string
7065 (when (org-xor org-context-in-file-links arg)
7066 (setq txt (if (org-region-active-p)
7067 (buffer-substring (region-beginning) (region-end))
7068 (buffer-substring (point-at-bol) (point-at-eol))))
7069 ;; Only use search option if there is some text.
7070 (when (string-match "\\S-" txt)
7071 (setq cpltxt
7072 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7073 desc "NONE")))
7074 (setq link (org-make-link cpltxt)))
7076 ((interactive-p)
7077 (error "Cannot link to a buffer which is not visiting a file"))
7079 (t (setq link nil)))
7081 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7082 (setq link (or link cpltxt)
7083 desc (or desc cpltxt))
7084 (if (equal desc "NONE") (setq desc nil))
7086 (if (and (or (interactive-p) executing-kbd-macro) link)
7087 (progn
7088 (setq org-stored-links
7089 (cons (list link desc) org-stored-links))
7090 (message "Stored: %s" (or desc link))
7091 (when custom-id
7092 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7093 "::#" custom-id))
7094 (setq org-stored-links
7095 (cons (list link desc) org-stored-links))))
7096 (and link (org-make-link-string link desc)))))
7098 (defun org-store-link-props (&rest plist)
7099 "Store link properties, extract names and addresses."
7100 (let (x adr)
7101 (when (setq x (plist-get plist :from))
7102 (setq adr (mail-extract-address-components x))
7103 (setq plist (plist-put plist :fromname (car adr)))
7104 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7105 (when (setq x (plist-get plist :to))
7106 (setq adr (mail-extract-address-components x))
7107 (setq plist (plist-put plist :toname (car adr)))
7108 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7109 (let ((from (plist-get plist :from))
7110 (to (plist-get plist :to)))
7111 (when (and from to org-from-is-user-regexp)
7112 (setq plist
7113 (plist-put plist :fromto
7114 (if (string-match org-from-is-user-regexp from)
7115 (concat "to %t")
7116 (concat "from %f"))))))
7117 (setq org-store-link-plist plist))
7119 (defun org-add-link-props (&rest plist)
7120 "Add these properties to the link property list."
7121 (let (key value)
7122 (while plist
7123 (setq key (pop plist) value (pop plist))
7124 (setq org-store-link-plist
7125 (plist-put org-store-link-plist key value)))))
7127 (defun org-email-link-description (&optional fmt)
7128 "Return the description part of an email link.
7129 This takes information from `org-store-link-plist' and formats it
7130 according to FMT (default from `org-email-link-description-format')."
7131 (setq fmt (or fmt org-email-link-description-format))
7132 (let* ((p org-store-link-plist)
7133 (to (plist-get p :toaddress))
7134 (from (plist-get p :fromaddress))
7135 (table
7136 (list
7137 (cons "%c" (plist-get p :fromto))
7138 (cons "%F" (plist-get p :from))
7139 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7140 (cons "%T" (plist-get p :to))
7141 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7142 (cons "%s" (plist-get p :subject))
7143 (cons "%m" (plist-get p :message-id)))))
7144 (when (string-match "%c" fmt)
7145 ;; Check if the user wrote this message
7146 (if (and org-from-is-user-regexp from to
7147 (save-match-data (string-match org-from-is-user-regexp from)))
7148 (setq fmt (replace-match "to %t" t t fmt))
7149 (setq fmt (replace-match "from %f" t t fmt))))
7150 (org-replace-escapes fmt table)))
7152 (defun org-make-org-heading-search-string (&optional string heading)
7153 "Make search string for STRING or current headline."
7154 (interactive)
7155 (let ((s (or string (org-get-heading))))
7156 (unless (and string (not heading))
7157 ;; We are using a headline, clean up garbage in there.
7158 (if (string-match org-todo-regexp s)
7159 (setq s (replace-match "" t t s)))
7160 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7161 (setq s (replace-match "" t t s)))
7162 (setq s (org-trim s))
7163 (if (string-match (concat "^\\(" org-quote-string "\\|"
7164 org-comment-string "\\)") s)
7165 (setq s (replace-match "" t t s)))
7166 (while (string-match org-ts-regexp s)
7167 (setq s (replace-match "" t t s))))
7168 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7169 (setq s (replace-match " " t t s)))
7170 (or string (setq s (concat "*" s))) ; Add * for headlines
7171 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7173 (defun org-make-link (&rest strings)
7174 "Concatenate STRINGS."
7175 (apply 'concat strings))
7177 (defun org-make-link-string (link &optional description)
7178 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7179 (unless (string-match "\\S-" link)
7180 (error "Empty link"))
7181 (when (stringp description)
7182 ;; Remove brackets from the description, they are fatal.
7183 (while (string-match "\\[" description)
7184 (setq description (replace-match "{" t t description)))
7185 (while (string-match "\\]" description)
7186 (setq description (replace-match "}" t t description))))
7187 (when (equal (org-link-escape link) description)
7188 ;; No description needed, it is identical
7189 (setq description nil))
7190 (when (and (not description)
7191 (not (equal link (org-link-escape link))))
7192 (setq description (org-extract-attributes link)))
7193 (concat "[[" (org-link-escape link) "]"
7194 (if description (concat "[" description "]") "")
7195 "]"))
7197 (defconst org-link-escape-chars
7198 '((?\ . "%20")
7199 (?\[ . "%5B")
7200 (?\] . "%5D")
7201 (?\340 . "%E0") ; `a
7202 (?\342 . "%E2") ; ^a
7203 (?\347 . "%E7") ; ,c
7204 (?\350 . "%E8") ; `e
7205 (?\351 . "%E9") ; 'e
7206 (?\352 . "%EA") ; ^e
7207 (?\356 . "%EE") ; ^i
7208 (?\364 . "%F4") ; ^o
7209 (?\371 . "%F9") ; `u
7210 (?\373 . "%FB") ; ^u
7211 (?\; . "%3B")
7212 (?? . "%3F")
7213 (?= . "%3D")
7214 (?+ . "%2B")
7216 "Association list of escapes for some characters problematic in links.
7217 This is the list that is used for internal purposes.")
7219 (defvar org-url-encoding-use-url-hexify nil)
7221 (defconst org-link-escape-chars-browser
7222 '((?\ . "%20")) ; 32 for the SPC char
7223 "Association list of escapes for some characters problematic in links.
7224 This is the list that is used before handing over to the browser.")
7226 (defun org-link-escape (text &optional table)
7227 "Escape characters in TEXT that are problematic for links."
7228 (if org-url-encoding-use-url-hexify
7229 (url-hexify-string text)
7230 (setq table (or table org-link-escape-chars))
7231 (when text
7232 (let ((re (mapconcat (lambda (x) (regexp-quote
7233 (char-to-string (car x))))
7234 table "\\|")))
7235 (while (string-match re text)
7236 (setq text
7237 (replace-match
7238 (cdr (assoc (string-to-char (match-string 0 text))
7239 table))
7240 t t text)))
7241 text))))
7243 (defun org-link-unescape (text &optional table)
7244 "Reverse the action of `org-link-escape'."
7245 (if org-url-encoding-use-url-hexify
7246 (url-unhex-string text)
7247 (setq table (or table org-link-escape-chars))
7248 (when text
7249 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7250 table "\\|")))
7251 (while (string-match re text)
7252 (setq text
7253 (replace-match
7254 (char-to-string (car (rassoc (match-string 0 text) table)))
7255 t t text)))
7256 text))))
7258 (defun org-xor (a b)
7259 "Exclusive or."
7260 (if a (not b) b))
7262 (defun org-fixup-message-id-for-http (s)
7263 "Replace special characters in a message id, so it can be used in an http query."
7264 (while (string-match "<" s)
7265 (setq s (replace-match "%3C" t t s)))
7266 (while (string-match ">" s)
7267 (setq s (replace-match "%3E" t t s)))
7268 (while (string-match "@" s)
7269 (setq s (replace-match "%40" t t s)))
7272 ;;;###autoload
7273 (defun org-insert-link-global ()
7274 "Insert a link like Org-mode does.
7275 This command can be called in any mode to insert a link in Org-mode syntax."
7276 (interactive)
7277 (org-load-modules-maybe)
7278 (org-run-like-in-org-mode 'org-insert-link))
7280 (defun org-insert-link (&optional complete-file link-location)
7281 "Insert a link. At the prompt, enter the link.
7283 Completion can be used to insert any of the link protocol prefixes like
7284 http or ftp in use.
7286 The history can be used to select a link previously stored with
7287 `org-store-link'. When the empty string is entered (i.e. if you just
7288 press RET at the prompt), the link defaults to the most recently
7289 stored link. As SPC triggers completion in the minibuffer, you need to
7290 use M-SPC or C-q SPC to force the insertion of a space character.
7292 You will also be prompted for a description, and if one is given, it will
7293 be displayed in the buffer instead of the link.
7295 If there is already a link at point, this command will allow you to edit link
7296 and description parts.
7298 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7299 be selected using completion. The path to the file will be relative to the
7300 current directory if the file is in the current directory or a subdirectory.
7301 Otherwise, the link will be the absolute path as completed in the minibuffer
7302 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7303 option `org-link-file-path-type'.
7305 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7306 the current directory or below.
7308 With three \\[universal-argument] prefixes, negate the meaning of
7309 `org-keep-stored-link-after-insertion'.
7311 If `org-make-link-description-function' is non-nil, this function will be
7312 called with the link target, and the result will be the default
7313 link description.
7315 If the LINK-LOCATION parameter is non-nil, this value will be
7316 used as the link location instead of reading one interactively."
7317 (interactive "P")
7318 (let* ((wcf (current-window-configuration))
7319 (region (if (org-region-active-p)
7320 (buffer-substring (region-beginning) (region-end))))
7321 (remove (and region (list (region-beginning) (region-end))))
7322 (desc region)
7323 tmphist ; byte-compile incorrectly complains about this
7324 (link link-location)
7325 entry file all-prefixes)
7326 (cond
7327 (link-location) ; specified by arg, just use it.
7328 ((org-in-regexp org-bracket-link-regexp 1)
7329 ;; We do have a link at point, and we are going to edit it.
7330 (setq remove (list (match-beginning 0) (match-end 0)))
7331 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7332 (setq link (read-string "Link: "
7333 (org-link-unescape
7334 (org-match-string-no-properties 1)))))
7335 ((or (org-in-regexp org-angle-link-re)
7336 (org-in-regexp org-plain-link-re))
7337 ;; Convert to bracket link
7338 (setq remove (list (match-beginning 0) (match-end 0))
7339 link (read-string "Link: "
7340 (org-remove-angle-brackets (match-string 0)))))
7341 ((member complete-file '((4) (16)))
7342 ;; Completing read for file names.
7343 (setq link (org-file-complete-link complete-file)))
7345 ;; Read link, with completion for stored links.
7346 (with-output-to-temp-buffer "*Org Links*"
7347 (princ "Insert a link.
7348 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7349 (when org-stored-links
7350 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7351 (princ (mapconcat
7352 (lambda (x)
7353 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7354 (reverse org-stored-links) "\n"))))
7355 (let ((cw (selected-window)))
7356 (select-window (get-buffer-window "*Org Links*"))
7357 (setq truncate-lines t)
7358 (unless (pos-visible-in-window-p (point-max))
7359 (org-fit-window-to-buffer))
7360 (and (window-live-p cw) (select-window cw)))
7361 ;; Fake a link history, containing the stored links.
7362 (setq tmphist (append (mapcar 'car org-stored-links)
7363 org-insert-link-history))
7364 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7365 (mapcar 'car org-link-abbrev-alist)
7366 org-link-types))
7367 (unwind-protect
7368 (progn
7369 (setq link
7370 (let ((org-completion-use-ido nil))
7371 (org-completing-read
7372 "Link: "
7373 (mapcar (lambda (x) (list (concat x ":")))
7374 all-prefixes)
7375 nil nil nil
7376 'tmphist
7377 (or (car (car org-stored-links))))))
7378 (if (or (member link all-prefixes)
7379 (and (equal ":" (substring link -1))
7380 (member (substring link 0 -1) all-prefixes)
7381 (setq link (substring link 0 -1))))
7382 (setq link (org-link-try-special-completion link))))
7383 (set-window-configuration wcf)
7384 (kill-buffer "*Org Links*"))
7385 (setq entry (assoc link org-stored-links))
7386 (or entry (push link org-insert-link-history))
7387 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7388 (not org-keep-stored-link-after-insertion))
7389 (setq org-stored-links (delq (assoc link org-stored-links)
7390 org-stored-links)))
7391 (setq desc (or desc (nth 1 entry)))))
7393 (if (string-match org-plain-link-re link)
7394 ;; URL-like link, normalize the use of angular brackets.
7395 (setq link (org-make-link (org-remove-angle-brackets link))))
7397 ;; Check if we are linking to the current file with a search option
7398 ;; If yes, simplify the link by using only the search option.
7399 (when (and buffer-file-name
7400 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7401 (let* ((path (match-string 1 link))
7402 (case-fold-search nil)
7403 (search (match-string 2 link)))
7404 (save-match-data
7405 (if (equal (file-truename buffer-file-name) (file-truename path))
7406 ;; We are linking to this same file, with a search option
7407 (setq link search)))))
7409 ;; Check if we can/should use a relative path. If yes, simplify the link
7410 (when (string-match "^file:\\(.*\\)" link)
7411 (let* ((path (match-string 1 link))
7412 (origpath path)
7413 (case-fold-search nil))
7414 (cond
7415 ((or (eq org-link-file-path-type 'absolute)
7416 (equal complete-file '(16)))
7417 (setq path (abbreviate-file-name (expand-file-name path))))
7418 ((eq org-link-file-path-type 'noabbrev)
7419 (setq path (expand-file-name path)))
7420 ((eq org-link-file-path-type 'relative)
7421 (setq path (file-relative-name path)))
7423 (save-match-data
7424 (if (string-match (concat "^" (regexp-quote
7425 (file-name-as-directory
7426 (expand-file-name "."))))
7427 (expand-file-name path))
7428 ;; We are linking a file with relative path name.
7429 (setq path (substring (expand-file-name path)
7430 (match-end 0)))
7431 (setq path (abbreviate-file-name (expand-file-name path)))))))
7432 (setq link (concat "file:" path))
7433 (if (equal desc origpath)
7434 (setq desc path))))
7436 (if org-make-link-description-function
7437 (setq desc (funcall org-make-link-description-function link desc)))
7439 (setq desc (read-string "Description: " desc))
7440 (unless (string-match "\\S-" desc) (setq desc nil))
7441 (if remove (apply 'delete-region remove))
7442 (insert (org-make-link-string link desc))))
7444 (defun org-link-try-special-completion (type)
7445 "If there is completion support for link type TAPE, offer it."
7446 (let ((fun (intern (concat "org-" type "-complete-link"))))
7447 (if (functionp fun)
7448 (funcall fun)
7449 (read-string "Link (no completion support): " (concat type ":")))))
7451 (defun org-file-complete-link (&optional arg)
7452 "Create a file link using completion."
7453 (let (file link)
7454 (setq file (read-file-name "File: "))
7455 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7456 (pwd1 (file-name-as-directory (abbreviate-file-name
7457 (expand-file-name ".")))))
7458 (cond
7459 ((equal arg '(16))
7460 (setq link (org-make-link
7461 "file:"
7462 (abbreviate-file-name (expand-file-name file)))))
7463 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7464 (setq link (org-make-link "file:" (match-string 1 file))))
7465 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7466 (expand-file-name file))
7467 (setq link (org-make-link
7468 "file:" (match-string 1 (expand-file-name file)))))
7469 (t (setq link (org-make-link "file:" file)))))
7470 link))
7472 (defun org-completing-read (&rest args)
7473 "Completing-read with SPACE being a normal character."
7474 (let ((minibuffer-local-completion-map
7475 (copy-keymap minibuffer-local-completion-map)))
7476 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7477 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7478 (apply 'org-ido-completing-read args)))
7480 (defun org-completing-read-no-ido (&rest args)
7481 (let (org-completion-use-ido)
7482 (apply 'org-completing-read args)))
7484 (defun org-ido-completing-read (&rest args)
7485 "Completing-read using `ido-mode' speedups if available"
7486 (if (and org-completion-use-ido
7487 (fboundp 'ido-completing-read)
7488 (boundp 'ido-mode) ido-mode
7489 (listp (second args)))
7490 (let ((ido-enter-matching-directory nil))
7491 (apply 'ido-completing-read (concat (car args))
7492 (mapcar (lambda (x) (car x)) (nth 1 args))
7493 (cddr args)))
7494 (apply 'completing-read args)))
7496 (defun org-extract-attributes (s)
7497 "Extract the attributes cookie from a string and set as text property."
7498 (let (a attr (start 0) key value)
7499 (save-match-data
7500 (when (string-match "{{\\([^}]+\\)}}$" s)
7501 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7502 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7503 (setq key (match-string 1 a) value (match-string 2 a)
7504 start (match-end 0)
7505 attr (plist-put attr (intern key) value))))
7506 (org-add-props s nil 'org-attr attr))
7509 (defun org-extract-attributes-from-string (tag)
7510 (let (key value attr)
7511 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7512 (setq key (match-string 1 tag) value (match-string 2 tag)
7513 tag (replace-match "" t t tag)
7514 attr (plist-put attr (intern key) value)))
7515 (cons tag attr)))
7517 (defun org-attributes-to-string (plist)
7518 "Format a property list into an HTML attribute list."
7519 (let ((s "") key value)
7520 (while plist
7521 (setq key (pop plist) value (pop plist))
7522 (and value
7523 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7526 ;;; Opening/following a link
7528 (defvar org-link-search-failed nil)
7530 (defun org-next-link ()
7531 "Move forward to the next link.
7532 If the link is in hidden text, expose it."
7533 (interactive)
7534 (when (and org-link-search-failed (eq this-command last-command))
7535 (goto-char (point-min))
7536 (message "Link search wrapped back to beginning of buffer"))
7537 (setq org-link-search-failed nil)
7538 (let* ((pos (point))
7539 (ct (org-context))
7540 (a (assoc :link ct)))
7541 (if a (goto-char (nth 2 a)))
7542 (if (re-search-forward org-any-link-re nil t)
7543 (progn
7544 (goto-char (match-beginning 0))
7545 (if (org-invisible-p) (org-show-context)))
7546 (goto-char pos)
7547 (setq org-link-search-failed t)
7548 (error "No further link found"))))
7550 (defun org-previous-link ()
7551 "Move backward to the previous link.
7552 If the link is in hidden text, expose it."
7553 (interactive)
7554 (when (and org-link-search-failed (eq this-command last-command))
7555 (goto-char (point-max))
7556 (message "Link search wrapped back to end of buffer"))
7557 (setq org-link-search-failed nil)
7558 (let* ((pos (point))
7559 (ct (org-context))
7560 (a (assoc :link ct)))
7561 (if a (goto-char (nth 1 a)))
7562 (if (re-search-backward org-any-link-re nil t)
7563 (progn
7564 (goto-char (match-beginning 0))
7565 (if (org-invisible-p) (org-show-context)))
7566 (goto-char pos)
7567 (setq org-link-search-failed t)
7568 (error "No further link found"))))
7570 (defun org-translate-link (s)
7571 "Translate a link string if a translation function has been defined."
7572 (if (and org-link-translation-function
7573 (fboundp org-link-translation-function)
7574 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7575 (progn
7576 (setq s (funcall org-link-translation-function
7577 (match-string 1) (match-string 2)))
7578 (concat (car s) ":" (cdr s)))
7581 (defun org-translate-link-from-planner (type path)
7582 "Translate a link from Emacs Planner syntax so that Org can follow it.
7583 This is still an experimental function, your mileage may vary."
7584 (cond
7585 ((member type '("http" "https" "news" "ftp"))
7586 ;; standard Internet links are the same.
7587 nil)
7588 ((and (equal type "irc") (string-match "^//" path))
7589 ;; Planner has two / at the beginning of an irc link, we have 1.
7590 ;; We should have zero, actually....
7591 (setq path (substring path 1)))
7592 ((and (equal type "lisp") (string-match "^/" path))
7593 ;; Planner has a slash, we do not.
7594 (setq type "elisp" path (substring path 1)))
7595 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7596 ;; A typical message link. Planner has the id after the fina slash,
7597 ;; we separate it with a hash mark
7598 (setq path (concat (match-string 1 path) "#"
7599 (org-remove-angle-brackets (match-string 2 path)))))
7601 (cons type path))
7603 (defun org-find-file-at-mouse (ev)
7604 "Open file link or URL at mouse."
7605 (interactive "e")
7606 (mouse-set-point ev)
7607 (org-open-at-point 'in-emacs))
7609 (defun org-open-at-mouse (ev)
7610 "Open file link or URL at mouse."
7611 (interactive "e")
7612 (mouse-set-point ev)
7613 (if (eq major-mode 'org-agenda-mode)
7614 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7615 (org-open-at-point))
7617 (defvar org-window-config-before-follow-link nil
7618 "The window configuration before following a link.
7619 This is saved in case the need arises to restore it.")
7621 (defvar org-open-link-marker (make-marker)
7622 "Marker pointing to the location where `org-open-at-point; was called.")
7624 ;;;###autoload
7625 (defun org-open-at-point-global ()
7626 "Follow a link like Org-mode does.
7627 This command can be called in any mode to follow a link that has
7628 Org-mode syntax."
7629 (interactive)
7630 (org-run-like-in-org-mode 'org-open-at-point))
7632 ;;;###autoload
7633 (defun org-open-link-from-string (s &optional arg)
7634 "Open a link in the string S, as if it was in Org-mode."
7635 (interactive "sLink: \nP")
7636 (let ((reference-buffer (current-buffer)))
7637 (with-temp-buffer
7638 (let ((org-inhibit-startup t))
7639 (org-mode)
7640 (insert s)
7641 (goto-char (point-min))
7642 (org-open-at-point arg reference-buffer)))))
7644 (defun org-open-at-point (&optional in-emacs reference-buffer)
7645 "Open link at or after point.
7646 If there is no link at point, this function will search forward up to
7647 the end of the current line.
7648 Normally, files will be opened by an appropriate application. If the
7649 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7650 With a double prefix argument, try to open outside of Emacs, in the
7651 application the system uses for this file type."
7652 (interactive "P")
7653 (org-load-modules-maybe)
7654 (move-marker org-open-link-marker (point))
7655 (setq org-window-config-before-follow-link (current-window-configuration))
7656 (org-remove-occur-highlights nil nil t)
7657 (cond
7658 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7659 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7660 (org-footnote-action))
7662 (let (type path link line search (pos (point)))
7663 (catch 'match
7664 (save-excursion
7665 (skip-chars-forward "^]\n\r")
7666 (when (org-in-regexp org-bracket-link-regexp)
7667 (setq link (org-extract-attributes
7668 (org-link-unescape (org-match-string-no-properties 1))))
7669 (while (string-match " *\n *" link)
7670 (setq link (replace-match " " t t link)))
7671 (setq link (org-link-expand-abbrev link))
7672 (cond
7673 ((or (file-name-absolute-p link)
7674 (string-match "^\\.\\.?/" link))
7675 (setq type "file" path link))
7676 ((string-match org-link-re-with-space3 link)
7677 (setq type (match-string 1 link) path (match-string 2 link)))
7678 (t (setq type "thisfile" path link)))
7679 (throw 'match t)))
7681 (when (get-text-property (point) 'org-linked-text)
7682 (setq type "thisfile"
7683 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7684 (1+ (point)) (point))
7685 path (buffer-substring
7686 (previous-single-property-change pos 'org-linked-text)
7687 (next-single-property-change pos 'org-linked-text)))
7688 (throw 'match t))
7690 (save-excursion
7691 (when (or (org-in-regexp org-angle-link-re)
7692 (org-in-regexp org-plain-link-re))
7693 (setq type (match-string 1) path (match-string 2))
7694 (throw 'match t)))
7695 (save-excursion
7696 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7697 (setq type "tags"
7698 path (match-string 1))
7699 (while (string-match ":" path)
7700 (setq path (replace-match "+" t t path)))
7701 (throw 'match t)))
7702 (when (org-in-regexp "<\\([^><\n]+\\)>")
7703 (setq type "tree-match"
7704 path (match-string 1))
7705 (throw 'match t)))
7706 (unless path
7707 (error "No link found"))
7709 ;; switch back to reference buffer
7710 ;; needed when if called in a temporary buffer through
7711 ;; org-open-link-from-string
7712 (and reference-buffer (switch-to-buffer reference-buffer))
7714 ;; Remove any trailing spaces in path
7715 (if (string-match " +\\'" path)
7716 (setq path (replace-match "" t t path)))
7717 (if (and org-link-translation-function
7718 (fboundp org-link-translation-function))
7719 ;; Check if we need to translate the link
7720 (let ((tmp (funcall org-link-translation-function type path)))
7721 (setq type (car tmp) path (cdr tmp))))
7723 (cond
7725 ((assoc type org-link-protocols)
7726 (funcall (nth 1 (assoc type org-link-protocols)) path))
7728 ((equal type "mailto")
7729 (let ((cmd (car org-link-mailto-program))
7730 (args (cdr org-link-mailto-program)) args1
7731 (address path) (subject "") a)
7732 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7733 (setq address (match-string 1 path)
7734 subject (org-link-escape (match-string 2 path))))
7735 (while args
7736 (cond
7737 ((not (stringp (car args))) (push (pop args) args1))
7738 (t (setq a (pop args))
7739 (if (string-match "%a" a)
7740 (setq a (replace-match address t t a)))
7741 (if (string-match "%s" a)
7742 (setq a (replace-match subject t t a)))
7743 (push a args1))))
7744 (apply cmd (nreverse args1))))
7746 ((member type '("http" "https" "ftp" "news"))
7747 (browse-url (concat type ":" (org-link-escape
7748 path org-link-escape-chars-browser))))
7750 ((member type '("message"))
7751 (browse-url (concat type ":" path)))
7753 ((string= type "tags")
7754 (org-tags-view in-emacs path))
7755 ((string= type "thisfile")
7756 (if in-emacs
7757 (switch-to-buffer-other-window
7758 (org-get-buffer-for-internal-link (current-buffer)))
7759 (org-mark-ring-push))
7760 (let ((cmd `(org-link-search
7761 ,path
7762 ,(cond ((equal in-emacs '(4)) 'occur)
7763 ((equal in-emacs '(16)) 'org-occur)
7764 (t nil))
7765 ,pos)))
7766 (condition-case nil (eval cmd)
7767 (error (progn (widen) (eval cmd))))))
7769 ((string= type "tree-match")
7770 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7772 ((string= type "file")
7773 (if (string-match "::\\([0-9]+\\)\\'" path)
7774 (setq line (string-to-number (match-string 1 path))
7775 path (substring path 0 (match-beginning 0)))
7776 (if (string-match "::\\(.+\\)\\'" path)
7777 (setq search (match-string 1 path)
7778 path (substring path 0 (match-beginning 0)))))
7779 (if (string-match "[*?{]" (file-name-nondirectory path))
7780 (dired path)
7781 (org-open-file path in-emacs line search)))
7783 ((string= type "news")
7784 (require 'org-gnus)
7785 (org-gnus-follow-link path))
7787 ((string= type "shell")
7788 (let ((cmd path))
7789 (if (or (not org-confirm-shell-link-function)
7790 (funcall org-confirm-shell-link-function
7791 (format "Execute \"%s\" in shell? "
7792 (org-add-props cmd nil
7793 'face 'org-warning))))
7794 (progn
7795 (message "Executing %s" cmd)
7796 (shell-command cmd))
7797 (error "Abort"))))
7799 ((string= type "elisp")
7800 (let ((cmd path))
7801 (if (or (not org-confirm-elisp-link-function)
7802 (funcall org-confirm-elisp-link-function
7803 (format "Execute \"%s\" as elisp? "
7804 (org-add-props cmd nil
7805 'face 'org-warning))))
7806 (message "%s => %s" cmd
7807 (if (equal (string-to-char cmd) ?\()
7808 (eval (read cmd))
7809 (call-interactively (read cmd))))
7810 (error "Abort"))))
7813 (browse-url-at-point))))))
7814 (move-marker org-open-link-marker nil)
7815 (run-hook-with-args 'org-follow-link-hook))
7817 ;;;; Time estimates
7819 (defun org-get-effort (&optional pom)
7820 "Get the effort estimate for the current entry."
7821 (org-entry-get pom org-effort-property))
7823 ;;; File search
7825 (defvar org-create-file-search-functions nil
7826 "List of functions to construct the right search string for a file link.
7827 These functions are called in turn with point at the location to
7828 which the link should point.
7830 A function in the hook should first test if it would like to
7831 handle this file type, for example by checking the major-mode or
7832 the file extension. If it decides not to handle this file, it
7833 should just return nil to give other functions a chance. If it
7834 does handle the file, it must return the search string to be used
7835 when following the link. The search string will be part of the
7836 file link, given after a double colon, and `org-open-at-point'
7837 will automatically search for it. If special measures must be
7838 taken to make the search successful, another function should be
7839 added to the companion hook `org-execute-file-search-functions',
7840 which see.
7842 A function in this hook may also use `setq' to set the variable
7843 `description' to provide a suggestion for the descriptive text to
7844 be used for this link when it gets inserted into an Org-mode
7845 buffer with \\[org-insert-link].")
7847 (defvar org-execute-file-search-functions nil
7848 "List of functions to execute a file search triggered by a link.
7850 Functions added to this hook must accept a single argument, the
7851 search string that was part of the file link, the part after the
7852 double colon. The function must first check if it would like to
7853 handle this search, for example by checking the major-mode or the
7854 file extension. If it decides not to handle this search, it
7855 should just return nil to give other functions a chance. If it
7856 does handle the search, it must return a non-nil value to keep
7857 other functions from trying.
7859 Each function can access the current prefix argument through the
7860 variable `current-prefix-argument'. Note that a single prefix is
7861 used to force opening a link in Emacs, so it may be good to only
7862 use a numeric or double prefix to guide the search function.
7864 In case this is needed, a function in this hook can also restore
7865 the window configuration before `org-open-at-point' was called using:
7867 (set-window-configuration org-window-config-before-follow-link)")
7869 (defun org-link-search (s &optional type avoid-pos)
7870 "Search for a link search option.
7871 If S is surrounded by forward slashes, it is interpreted as a
7872 regular expression. In org-mode files, this will create an `org-occur'
7873 sparse tree. In ordinary files, `occur' will be used to list matches.
7874 If the current buffer is in `dired-mode', grep will be used to search
7875 in all files. If AVOID-POS is given, ignore matches near that position."
7876 (let ((case-fold-search t)
7877 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7878 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7879 (append '(("") (" ") ("\t") ("\n"))
7880 org-emphasis-alist)
7881 "\\|") "\\)"))
7882 (pos (point))
7883 (pre nil) (post nil)
7884 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7885 (cond
7886 ;; First check if there are any special
7887 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7888 ;; Now try the builtin stuff
7889 ((and (equal (string-to-char s0) ?#)
7890 (> (length s0) 1)
7891 (save-excursion
7892 (goto-char (point-min))
7893 (and
7894 (re-search-forward
7895 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
7896 (setq type 'dedicated
7897 pos (match-beginning 0))))
7898 ;; There is an exact target for this
7899 (goto-char pos)
7900 (org-back-to-heading t)))
7901 ((save-excursion
7902 (goto-char (point-min))
7903 (and
7904 (re-search-forward
7905 (concat "<<" (regexp-quote s0) ">>") nil t)
7906 (setq type 'dedicated
7907 pos (match-beginning 0))))
7908 ;; There is an exact target for this
7909 (goto-char pos))
7910 ((and (string-match "^(\\(.*\\))$" s0)
7911 (save-excursion
7912 (goto-char (point-min))
7913 (and
7914 (re-search-forward
7915 (concat "[^[]" (regexp-quote
7916 (format org-coderef-label-format
7917 (match-string 1 s0))))
7918 nil t)
7919 (setq type 'dedicated
7920 pos (1+ (match-beginning 0))))))
7921 ;; There is a coderef target for this
7922 (goto-char pos))
7923 ((string-match "^/\\(.*\\)/$" s)
7924 ;; A regular expression
7925 (cond
7926 ((org-mode-p)
7927 (org-occur (match-string 1 s)))
7928 ;;((eq major-mode 'dired-mode)
7929 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7930 (t (org-do-occur (match-string 1 s)))))
7932 ;; A normal search strings
7933 (when (equal (string-to-char s) ?*)
7934 ;; Anchor on headlines, post may include tags.
7935 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7936 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7937 s (substring s 1)))
7938 (remove-text-properties
7939 0 (length s)
7940 '(face nil mouse-face nil keymap nil fontified nil) s)
7941 ;; Make a series of regular expressions to find a match
7942 (setq words (org-split-string s "[ \n\r\t]+")
7944 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7945 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7946 "\\)" markers)
7947 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7948 re2a (concat "[ \t\r\n]" re2a_)
7949 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7950 re4 (concat "[^a-zA-Z_]" re4_)
7952 re1 (concat pre re2 post)
7953 re3 (concat pre (if pre re4_ re4) post)
7954 re5 (concat pre ".*" re4)
7955 re2 (concat pre re2)
7956 re2a (concat pre (if pre re2a_ re2a))
7957 re4 (concat pre (if pre re4_ re4))
7958 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7959 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7960 re5 "\\)"
7962 (cond
7963 ((eq type 'org-occur) (org-occur reall))
7964 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7965 (t (goto-char (point-min))
7966 (setq type 'fuzzy)
7967 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7968 (org-search-not-self 1 re1 nil t)
7969 (org-search-not-self 1 re2 nil t)
7970 (org-search-not-self 1 re2a nil t)
7971 (org-search-not-self 1 re3 nil t)
7972 (org-search-not-self 1 re4 nil t)
7973 (org-search-not-self 1 re5 nil t)
7975 (goto-char (match-beginning 1))
7976 (goto-char pos)
7977 (error "No match")))))
7979 ;; Normal string-search
7980 (goto-char (point-min))
7981 (if (search-forward s nil t)
7982 (goto-char (match-beginning 0))
7983 (error "No match"))))
7984 (and (org-mode-p) (org-show-context 'link-search))
7985 type))
7987 (defun org-search-not-self (group &rest args)
7988 "Execute `re-search-forward', but only accept matches that do not
7989 enclose the position of `org-open-link-marker'."
7990 (let ((m org-open-link-marker))
7991 (catch 'exit
7992 (while (apply 're-search-forward args)
7993 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7994 (goto-char (match-end group))
7995 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7996 (> (match-beginning 0) (marker-position m))
7997 (< (match-end 0) (marker-position m)))
7998 (save-match-data
7999 (or (not (org-in-regexp
8000 org-bracket-link-analytic-regexp 1))
8001 (not (match-end 4)) ; no description
8002 (and (<= (match-beginning 4) (point))
8003 (>= (match-end 4) (point))))))
8004 (throw 'exit (point))))))))
8006 (defun org-get-buffer-for-internal-link (buffer)
8007 "Return a buffer to be used for displaying the link target of internal links."
8008 (cond
8009 ((not org-display-internal-link-with-indirect-buffer)
8010 buffer)
8011 ((string-match "(Clone)$" (buffer-name buffer))
8012 (message "Buffer is already a clone, not making another one")
8013 ;; we also do not modify visibility in this case
8014 buffer)
8015 (t ; make a new indirect buffer for displaying the link
8016 (let* ((bn (buffer-name buffer))
8017 (ibn (concat bn "(Clone)"))
8018 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8019 (with-current-buffer ib (org-overview))
8020 ib))))
8022 (defun org-do-occur (regexp &optional cleanup)
8023 "Call the Emacs command `occur'.
8024 If CLEANUP is non-nil, remove the printout of the regular expression
8025 in the *Occur* buffer. This is useful if the regex is long and not useful
8026 to read."
8027 (occur regexp)
8028 (when cleanup
8029 (let ((cwin (selected-window)) win beg end)
8030 (when (setq win (get-buffer-window "*Occur*"))
8031 (select-window win))
8032 (goto-char (point-min))
8033 (when (re-search-forward "match[a-z]+" nil t)
8034 (setq beg (match-end 0))
8035 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8036 (setq end (1- (match-beginning 0)))))
8037 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8038 (goto-char (point-min))
8039 (select-window cwin))))
8041 ;;; The mark ring for links jumps
8043 (defvar org-mark-ring nil
8044 "Mark ring for positions before jumps in Org-mode.")
8045 (defvar org-mark-ring-last-goto nil
8046 "Last position in the mark ring used to go back.")
8047 ;; Fill and close the ring
8048 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8049 (loop for i from 1 to org-mark-ring-length do
8050 (push (make-marker) org-mark-ring))
8051 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8052 org-mark-ring)
8054 (defun org-mark-ring-push (&optional pos buffer)
8055 "Put the current position or POS into the mark ring and rotate it."
8056 (interactive)
8057 (setq pos (or pos (point)))
8058 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8059 (move-marker (car org-mark-ring)
8060 (or pos (point))
8061 (or buffer (current-buffer)))
8062 (message "%s"
8063 (substitute-command-keys
8064 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8066 (defun org-mark-ring-goto (&optional n)
8067 "Jump to the previous position in the mark ring.
8068 With prefix arg N, jump back that many stored positions. When
8069 called several times in succession, walk through the entire ring.
8070 Org-mode commands jumping to a different position in the current file,
8071 or to another Org-mode file, automatically push the old position
8072 onto the ring."
8073 (interactive "p")
8074 (let (p m)
8075 (if (eq last-command this-command)
8076 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8077 (setq p org-mark-ring))
8078 (setq org-mark-ring-last-goto p)
8079 (setq m (car p))
8080 (switch-to-buffer (marker-buffer m))
8081 (goto-char m)
8082 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8084 (defun org-remove-angle-brackets (s)
8085 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8086 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8088 (defun org-add-angle-brackets (s)
8089 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8090 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8092 (defun org-remove-double-quotes (s)
8093 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8094 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8097 ;;; Following specific links
8099 (defun org-follow-timestamp-link ()
8100 (cond
8101 ((org-at-date-range-p t)
8102 (let ((org-agenda-start-on-weekday)
8103 (t1 (match-string 1))
8104 (t2 (match-string 2)))
8105 (setq t1 (time-to-days (org-time-string-to-time t1))
8106 t2 (time-to-days (org-time-string-to-time t2)))
8107 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8108 ((org-at-timestamp-p t)
8109 (org-agenda-list nil (time-to-days (org-time-string-to-time
8110 (substring (match-string 1) 0 10)))
8112 (t (error "This should not happen"))))
8115 ;;; Following file links
8116 (defvar org-wait nil)
8117 (defun org-open-file (path &optional in-emacs line search)
8118 "Open the file at PATH.
8119 First, this expands any special file name abbreviations. Then the
8120 configuration variable `org-file-apps' is checked if it contains an
8121 entry for this file type, and if yes, the corresponding command is launched.
8123 If no application is found, Emacs simply visits the file.
8125 With optional prefix argument IN-EMACS, Emacs will visit the file.
8126 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8127 and o use an external application to visit the file.
8129 Optional LINE specifies a line to go to, optional SEARCH a string to
8130 search for. If LINE or SEARCH is given, the file will always be
8131 opened in Emacs.
8132 If the file does not exist, an error is thrown."
8133 (setq in-emacs (or in-emacs line search))
8134 (let* ((file (if (equal path "")
8135 buffer-file-name
8136 (substitute-in-file-name (expand-file-name path))))
8137 (apps (append org-file-apps (org-default-apps)))
8138 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8139 (dirp (if remp nil (file-directory-p file)))
8140 (file (if (and dirp org-open-directory-means-index-dot-org)
8141 (concat (file-name-as-directory file) "index.org")
8142 file))
8143 (a-m-a-p (assq 'auto-mode apps))
8144 (dfile (downcase file))
8145 (old-buffer (current-buffer))
8146 (old-pos (point))
8147 (old-mode major-mode)
8148 ext cmd)
8149 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8150 (setq ext (match-string 1 dfile))
8151 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8152 (setq ext (match-string 1 dfile))))
8153 (cond
8154 ((equal in-emacs '(16))
8155 (setq cmd (cdr (assoc 'system apps))))
8156 (in-emacs (setq cmd 'emacs))
8158 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8159 (and dirp (cdr (assoc 'directory apps)))
8160 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8161 'string-match)
8162 (cdr (assoc ext apps))
8163 (cdr (assoc t apps))))))
8164 (when (eq cmd 'system)
8165 (setq cmd (cdr (assoc 'system apps))))
8166 (when (eq cmd 'default)
8167 (setq cmd (cdr (assoc t apps))))
8168 (when (eq cmd 'mailcap)
8169 (require 'mailcap)
8170 (mailcap-parse-mailcaps)
8171 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8172 (command (mailcap-mime-info mime-type)))
8173 (if (stringp command)
8174 (setq cmd command)
8175 (setq cmd 'emacs))))
8176 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8177 (not (file-exists-p file))
8178 (not org-open-non-existing-files))
8179 (error "No such file: %s" file))
8180 (cond
8181 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8182 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8183 (while (string-match "['\"]%s['\"]" cmd)
8184 (setq cmd (replace-match "%s" t t cmd)))
8185 (while (string-match "%s" cmd)
8186 (setq cmd (replace-match
8187 (save-match-data
8188 (shell-quote-argument
8189 (convert-standard-filename file)))
8190 t t cmd)))
8191 (save-window-excursion
8192 (start-process-shell-command cmd nil cmd)
8193 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8195 ((or (stringp cmd)
8196 (eq cmd 'emacs))
8197 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8198 (widen)
8199 (if line (goto-line line)
8200 (if search (org-link-search search))))
8201 ((consp cmd)
8202 (let ((file (convert-standard-filename file)))
8203 (eval cmd)))
8204 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8205 (and (org-mode-p) (eq old-mode 'org-mode)
8206 (or (not (equal old-buffer (current-buffer)))
8207 (not (equal old-pos (point))))
8208 (org-mark-ring-push old-pos old-buffer))))
8210 (defun org-default-apps ()
8211 "Return the default applications for this operating system."
8212 (cond
8213 ((eq system-type 'darwin)
8214 org-file-apps-defaults-macosx)
8215 ((eq system-type 'windows-nt)
8216 org-file-apps-defaults-windowsnt)
8217 (t org-file-apps-defaults-gnu)))
8219 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8220 "Convert extensions to regular expressions in the cars of LIST.
8221 Also, weed out any non-string entries, because the return value is used
8222 only for regexp matching.
8223 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8224 point to the symbol `emacs', indicating that the file should
8225 be opened in Emacs."
8226 (append
8227 (delq nil
8228 (mapcar (lambda (x)
8229 (if (not (stringp (car x)))
8231 (if (string-match "\\W" (car x))
8233 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8234 list))
8235 (if add-auto-mode
8236 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8238 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8239 (defun org-file-remote-p (file)
8240 "Test whether FILE specifies a location on a remote system.
8241 Return non-nil if the location is indeed remote.
8243 For example, the filename \"/user@host:/foo\" specifies a location
8244 on the system \"/user@host:\"."
8245 (cond ((fboundp 'file-remote-p)
8246 (file-remote-p file))
8247 ((fboundp 'tramp-handle-file-remote-p)
8248 (tramp-handle-file-remote-p file))
8249 ((and (boundp 'ange-ftp-name-format)
8250 (string-match (car ange-ftp-name-format) file))
8252 (t nil)))
8255 ;;;; Refiling
8257 (defun org-get-org-file ()
8258 "Read a filename, with default directory `org-directory'."
8259 (let ((default (or org-default-notes-file remember-data-file)))
8260 (read-file-name (format "File name [%s]: " default)
8261 (file-name-as-directory org-directory)
8262 default)))
8264 (defun org-notes-order-reversed-p ()
8265 "Check if the current file should receive notes in reversed order."
8266 (cond
8267 ((not org-reverse-note-order) nil)
8268 ((eq t org-reverse-note-order) t)
8269 ((not (listp org-reverse-note-order)) nil)
8270 (t (catch 'exit
8271 (let ((all org-reverse-note-order)
8272 entry)
8273 (while (setq entry (pop all))
8274 (if (string-match (car entry) buffer-file-name)
8275 (throw 'exit (cdr entry))))
8276 nil)))))
8278 (defvar org-refile-target-table nil
8279 "The list of refile targets, created by `org-refile'.")
8281 (defvar org-agenda-new-buffers nil
8282 "Buffers created to visit agenda files.")
8284 (defun org-get-refile-targets (&optional default-buffer)
8285 "Produce a table with refile targets."
8286 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8287 targets txt re files f desc descre fast-path-p level pos0)
8288 (message "Getting targets...")
8289 (with-current-buffer (or default-buffer (current-buffer))
8290 (while (setq entry (pop entries))
8291 (setq files (car entry) desc (cdr entry))
8292 (setq fast-path-p nil)
8293 (cond
8294 ((null files) (setq files (list (current-buffer))))
8295 ((eq files 'org-agenda-files)
8296 (setq files (org-agenda-files 'unrestricted)))
8297 ((and (symbolp files) (fboundp files))
8298 (setq files (funcall files)))
8299 ((and (symbolp files) (boundp files))
8300 (setq files (symbol-value files))))
8301 (if (stringp files) (setq files (list files)))
8302 (cond
8303 ((eq (car desc) :tag)
8304 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8305 ((eq (car desc) :todo)
8306 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8307 ((eq (car desc) :regexp)
8308 (setq descre (cdr desc)))
8309 ((eq (car desc) :level)
8310 (setq descre (concat "^\\*\\{" (number-to-string
8311 (if org-odd-levels-only
8312 (1- (* 2 (cdr desc)))
8313 (cdr desc)))
8314 "\\}[ \t]")))
8315 ((eq (car desc) :maxlevel)
8316 (setq fast-path-p t)
8317 (setq descre (concat "^\\*\\{1," (number-to-string
8318 (if org-odd-levels-only
8319 (1- (* 2 (cdr desc)))
8320 (cdr desc)))
8321 "\\}[ \t]")))
8322 (t (error "Bad refiling target description %s" desc)))
8323 (while (setq f (pop files))
8324 (save-excursion
8325 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8326 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8327 (setq f (expand-file-name f))
8328 (if (eq org-refile-use-outline-path 'file)
8329 (push (list (file-name-nondirectory f) f nil nil) targets))
8330 (save-excursion
8331 (save-restriction
8332 (widen)
8333 (goto-char (point-min))
8334 (while (re-search-forward descre nil t)
8335 (goto-char (setq pos0 (point-at-bol)))
8336 (catch 'next
8337 (when org-refile-target-verify-function
8338 (save-match-data
8339 (or (funcall org-refile-target-verify-function)
8340 (throw 'next t))))
8341 (when (looking-at org-complex-heading-regexp)
8342 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8343 txt (org-link-display-format (match-string 4))
8344 re (concat "^" (regexp-quote
8345 (buffer-substring (match-beginning 1)
8346 (match-end 4)))))
8347 (if (match-end 5) (setq re (concat re "[ \t]+"
8348 (regexp-quote
8349 (match-string 5)))))
8350 (setq re (concat re "[ \t]*$"))
8351 (when org-refile-use-outline-path
8352 (setq txt (mapconcat 'org-protect-slash
8353 (append
8354 (if (eq org-refile-use-outline-path 'file)
8355 (list (file-name-nondirectory
8356 (buffer-file-name (buffer-base-buffer))))
8357 (if (eq org-refile-use-outline-path 'full-file-path)
8358 (list (buffer-file-name (buffer-base-buffer)))))
8359 (org-get-outline-path fast-path-p level txt)
8360 (list txt))
8361 "/")))
8362 (push (list txt f re (point)) targets)))
8363 (when (= (point) pos0)
8364 ;; verification function has not moved point
8365 (goto-char (point-at-eol))))))))))
8366 (message "Getting targets...done")
8367 (nreverse targets)))
8369 (defun org-protect-slash (s)
8370 (while (string-match "/" s)
8371 (setq s (replace-match "\\" t t s)))
8374 (defvar org-olpa (make-vector 20 nil))
8376 (defun org-get-outline-path (&optional fastp level heading)
8377 "Return the outline path to the current entry, as a list."
8378 (if fastp
8379 (progn
8380 (if (> level 19)
8381 (error "Outline path failure, more than 19 levels."))
8382 (loop for i from level upto 19 do
8383 (aset org-olpa i nil))
8384 (prog1
8385 (delq nil (append org-olpa nil))
8386 (aset org-olpa level heading)))
8387 (let (rtn)
8388 (save-excursion
8389 (while (org-up-heading-safe)
8390 (when (looking-at org-complex-heading-regexp)
8391 (push (org-match-string-no-properties 4) rtn)))
8392 rtn))))
8394 (defvar org-refile-history nil
8395 "History for refiling operations.")
8397 (defvar org-after-refile-insert-hook nil
8398 "Hook run after `org-refile' has inserted its stuff at the new location.
8399 Note that this is still *before* the stuff will be removed from
8400 the *old* location.")
8402 (defun org-refile (&optional goto default-buffer rfloc)
8403 "Move the entry at point to another heading.
8404 The list of target headings is compiled using the information in
8405 `org-refile-targets', which see. This list is created before each use
8406 and will therefore always be up-to-date.
8408 At the target location, the entry is filed as a subitem of the target heading.
8409 Depending on `org-reverse-note-order', the new subitem will either be the
8410 first or the last subitem.
8412 If there is an active region, all entries in that region will be moved.
8413 However, the region must fulfil the requirement that the first heading
8414 is the first one sets the top-level of the moved text - at most siblings
8415 below it are allowed.
8417 With prefix arg GOTO, the command will only visit the target location,
8418 not actually move anything.
8419 With a double prefix `C-u C-u', go to the location where the last refiling
8420 operation has put the subtree.
8422 RFLOC can be a refile location obtained in a different way.
8424 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8425 (interactive "P")
8426 (let* ((cbuf (current-buffer))
8427 (regionp (org-region-active-p))
8428 (region-start (and regionp (region-beginning)))
8429 (region-end (and regionp (region-end)))
8430 (region-length (and regionp (- region-end region-start)))
8431 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8432 pos it nbuf file re level reversed)
8433 (when regionp (goto-char region-start)
8434 (unless (org-kill-is-subtree-p
8435 (buffer-substring region-start region-end))
8436 (error "The region is not a (sequence of) subtree(s)")))
8437 (if (equal goto '(16))
8438 (org-refile-goto-last-stored)
8439 (when (setq it (or rfloc
8440 (org-refile-get-location
8441 (if goto "Goto: " "Refile to: ") default-buffer
8442 org-refile-allow-creating-parent-nodes)))
8443 (setq file (nth 1 it)
8444 re (nth 2 it)
8445 pos (nth 3 it))
8446 (if (and (not goto)
8448 (equal (buffer-file-name) file)
8449 (if regionp
8450 (and (>= pos region-start)
8451 (<= pos region-end))
8452 (and (>= pos (point))
8453 (< pos (save-excursion
8454 (org-end-of-subtree t t))))))
8455 (error "Cannot refile to position inside the tree or region"))
8457 (setq nbuf (or (find-buffer-visiting file)
8458 (find-file-noselect file)))
8459 (if goto
8460 (progn
8461 (switch-to-buffer nbuf)
8462 (goto-char pos)
8463 (org-show-context 'org-goto))
8464 (if regionp
8465 (progn
8466 (kill-new (buffer-substring region-start region-end))
8467 (org-save-markers-in-region region-start region-end))
8468 (org-copy-subtree 1 nil t))
8469 (save-excursion
8470 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8471 (find-file-noselect file))))
8472 (setq reversed (org-notes-order-reversed-p))
8473 (save-excursion
8474 (save-restriction
8475 (widen)
8476 (if pos
8477 (progn
8478 (goto-char pos)
8479 (looking-at outline-regexp)
8480 (setq level (org-get-valid-level (funcall outline-level) 1))
8481 (goto-char
8482 (if reversed
8483 (or (outline-next-heading) (point-max))
8484 (or (save-excursion (outline-get-next-sibling))
8485 (org-end-of-subtree t t)
8486 (point-max)))))
8487 (setq level 1)
8488 (if (not reversed)
8489 (goto-char (point-max))
8490 (goto-char (point-min))
8491 (or (outline-next-heading) (goto-char (point-max)))))
8492 (if (not (bolp)) (newline))
8493 (bookmark-set "org-refile-last-stored")
8494 (org-paste-subtree level)
8495 (if (fboundp 'deactivate-mark) (deactivate-mark))
8496 (run-hooks 'org-after-refile-insert-hook))))
8497 (if regionp
8498 (delete-region (point) (+ (point) region-length))
8499 (org-cut-subtree))
8500 (setq org-markers-to-move nil)
8501 (message "Refiled to \"%s\"" (car it))))))
8502 (org-reveal))
8504 (defun org-refile-goto-last-stored ()
8505 "Go to the location where the last refile was stored."
8506 (interactive)
8507 (bookmark-jump "org-refile-last-stored")
8508 (message "This is the location of the last refile"))
8510 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8511 "Prompt the user for a refile location, using PROMPT."
8512 (let ((org-refile-targets org-refile-targets)
8513 (org-refile-use-outline-path org-refile-use-outline-path))
8514 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8515 (unless org-refile-target-table
8516 (error "No refile targets"))
8517 (let* ((cbuf (current-buffer))
8518 (partial-completion-mode nil)
8519 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8520 (cfunc (if (and org-refile-use-outline-path
8521 org-outline-path-complete-in-steps)
8522 'org-olpath-completing-read
8523 'org-ido-completing-read))
8524 (extra (if org-refile-use-outline-path "/" ""))
8525 (filename (and cfn (expand-file-name cfn)))
8526 (tbl (mapcar
8527 (lambda (x)
8528 (if (and (not (member org-refile-use-outline-path
8529 '(file full-file-path)))
8530 (not (equal filename (nth 1 x))))
8531 (cons (concat (car x) extra " ("
8532 (file-name-nondirectory (nth 1 x)) ")")
8533 (cdr x))
8534 (cons (concat (car x) extra) (cdr x))))
8535 org-refile-target-table))
8536 (completion-ignore-case t)
8537 pa answ parent-target child parent)
8538 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8539 nil 'org-refile-history))
8540 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8541 (if pa
8543 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8544 (setq parent (match-string 1 answ)
8545 child (match-string 2 answ))
8546 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8547 (when (and parent-target
8548 (or (eq new-nodes t)
8549 (and (eq new-nodes 'confirm)
8550 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8551 (org-refile-new-child parent-target child))))))
8553 (defun org-refile-new-child (parent-target child)
8554 "Use refile target PARENT-TARGET to add new CHILD below it."
8555 (unless parent-target
8556 (error "Cannot find parent for new node"))
8557 (let ((file (nth 1 parent-target))
8558 (pos (nth 3 parent-target))
8559 level)
8560 (with-current-buffer (or (find-buffer-visiting file)
8561 (find-file-noselect file))
8562 (save-excursion
8563 (save-restriction
8564 (widen)
8565 (if pos
8566 (goto-char pos)
8567 (goto-char (point-max))
8568 (if (not (bolp)) (newline)))
8569 (when (looking-at outline-regexp)
8570 (setq level (funcall outline-level))
8571 (org-end-of-subtree t t))
8572 (org-back-over-empty-lines)
8573 (insert "\n" (make-string
8574 (if pos (org-get-valid-level level 1) 1) ?*)
8575 " " child "\n")
8576 (beginning-of-line 0)
8577 (list (concat (car parent-target) "/" child) file "" (point)))))))
8579 (defun org-olpath-completing-read (prompt collection &rest args)
8580 "Read an outline path like a file name."
8581 (let ((thetable collection)
8582 (org-completion-use-ido nil)) ; does not work with ido.
8583 (apply
8584 'org-ido-completing-read prompt
8585 (lambda (string predicate &optional flag)
8586 (let (rtn r f (l (length string)))
8587 (cond
8588 ((eq flag nil)
8589 ;; try completion
8590 (try-completion string thetable))
8591 ((eq flag t)
8592 ;; all-completions
8593 (setq rtn (all-completions string thetable predicate))
8594 (mapcar
8595 (lambda (x)
8596 (setq r (substring x l))
8597 (if (string-match " ([^)]*)$" x)
8598 (setq f (match-string 0 x))
8599 (setq f ""))
8600 (if (string-match "/" r)
8601 (concat string (substring r 0 (match-end 0)) f)
8603 rtn))
8604 ((eq flag 'lambda)
8605 ;; exact match?
8606 (assoc string thetable)))
8608 args)))
8610 ;;;; Dynamic blocks
8612 (defun org-find-dblock (name)
8613 "Find the first dynamic block with name NAME in the buffer.
8614 If not found, stay at current position and return nil."
8615 (let (pos)
8616 (save-excursion
8617 (goto-char (point-min))
8618 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8619 nil t)
8620 (match-beginning 0))))
8621 (if pos (goto-char pos))
8622 pos))
8624 (defconst org-dblock-start-re
8625 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8626 "Matches the startline of a dynamic block, with parameters.")
8628 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8629 "Matches the end of a dynamic block.")
8631 (defun org-create-dblock (plist)
8632 "Create a dynamic block section, with parameters taken from PLIST.
8633 PLIST must contain a :name entry which is used as name of the block."
8634 (unless (bolp) (newline))
8635 (let ((name (plist-get plist :name)))
8636 (insert "#+BEGIN: " name)
8637 (while plist
8638 (if (eq (car plist) :name)
8639 (setq plist (cddr plist))
8640 (insert " " (prin1-to-string (pop plist)))))
8641 (insert "\n\n#+END:\n")
8642 (beginning-of-line -2)))
8644 (defun org-prepare-dblock ()
8645 "Prepare dynamic block for refresh.
8646 This empties the block, puts the cursor at the insert position and returns
8647 the property list including an extra property :name with the block name."
8648 (unless (looking-at org-dblock-start-re)
8649 (error "Not at a dynamic block"))
8650 (let* ((begdel (1+ (match-end 0)))
8651 (name (org-no-properties (match-string 1)))
8652 (params (append (list :name name)
8653 (read (concat "(" (match-string 3) ")")))))
8654 (unless (re-search-forward org-dblock-end-re nil t)
8655 (error "Dynamic block not terminated"))
8656 (setq params
8657 (append params
8658 (list :content (buffer-substring
8659 begdel (match-beginning 0)))))
8660 (delete-region begdel (match-beginning 0))
8661 (goto-char begdel)
8662 (open-line 1)
8663 params))
8665 (defun org-map-dblocks (&optional command)
8666 "Apply COMMAND to all dynamic blocks in the current buffer.
8667 If COMMAND is not given, use `org-update-dblock'."
8668 (let ((cmd (or command 'org-update-dblock))
8669 pos)
8670 (save-excursion
8671 (goto-char (point-min))
8672 (while (re-search-forward org-dblock-start-re nil t)
8673 (goto-char (setq pos (match-beginning 0)))
8674 (condition-case nil
8675 (funcall cmd)
8676 (error (message "Error during update of dynamic block")))
8677 (goto-char pos)
8678 (unless (re-search-forward org-dblock-end-re nil t)
8679 (error "Dynamic block not terminated"))))))
8681 (defun org-dblock-update (&optional arg)
8682 "User command for updating dynamic blocks.
8683 Update the dynamic block at point. With prefix ARG, update all dynamic
8684 blocks in the buffer."
8685 (interactive "P")
8686 (if arg
8687 (org-update-all-dblocks)
8688 (or (looking-at org-dblock-start-re)
8689 (org-beginning-of-dblock))
8690 (org-update-dblock)))
8692 (defun org-update-dblock ()
8693 "Update the dynamic block at point
8694 This means to empty the block, parse for parameters and then call
8695 the correct writing function."
8696 (save-window-excursion
8697 (let* ((pos (point))
8698 (line (org-current-line))
8699 (params (org-prepare-dblock))
8700 (name (plist-get params :name))
8701 (cmd (intern (concat "org-dblock-write:" name))))
8702 (message "Updating dynamic block `%s' at line %d..." name line)
8703 (funcall cmd params)
8704 (message "Updating dynamic block `%s' at line %d...done" name line)
8705 (goto-char pos))))
8707 (defun org-beginning-of-dblock ()
8708 "Find the beginning of the dynamic block at point.
8709 Error if there is no such block at point."
8710 (let ((pos (point))
8711 beg)
8712 (end-of-line 1)
8713 (if (and (re-search-backward org-dblock-start-re nil t)
8714 (setq beg (match-beginning 0))
8715 (re-search-forward org-dblock-end-re nil t)
8716 (> (match-end 0) pos))
8717 (goto-char beg)
8718 (goto-char pos)
8719 (error "Not in a dynamic block"))))
8721 (defun org-update-all-dblocks ()
8722 "Update all dynamic blocks in the buffer.
8723 This function can be used in a hook."
8724 (when (org-mode-p)
8725 (org-map-dblocks 'org-update-dblock)))
8728 ;;;; Completion
8730 (defconst org-additional-option-like-keywords
8731 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
8732 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
8733 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "ATTR_LaTeX"
8734 "BEGIN:" "END:"
8735 "ORGTBL" "TBLFM:" "TBLNAME:"
8736 "BEGIN_EXAMPLE" "END_EXAMPLE"
8737 "BEGIN_QUOTE" "END_QUOTE"
8738 "BEGIN_VERSE" "END_VERSE"
8739 "BEGIN_CENTER" "END_CENTER"
8740 "BEGIN_SRC" "END_SRC"
8741 "CATEGORY" "COLUMNS"
8742 "CAPTION" "LABEL"
8743 "BIND"))
8745 (defcustom org-structure-template-alist
8747 ("s" "#+begin_src ?\n\n#+end_src"
8748 "<src lang=\"?\">\n\n</src>")
8749 ("e" "#+begin_example\n?\n#+end_example"
8750 "<example>\n?\n</example>")
8751 ("q" "#+begin_quote\n?\n#+end_quote"
8752 "<quote>\n?\n</quote>")
8753 ("v" "#+begin_verse\n?\n#+end_verse"
8754 "<verse>\n?\n/verse>")
8755 ("c" "#+begin_center\n?\n#+end_center"
8756 "<center>\n?\n/center>")
8757 ("l" "#+begin_latex\n?\n#+end_latex"
8758 "<literal style=\"latex\">\n?\n</literal>")
8759 ("L" "#+latex: "
8760 "<literal style=\"latex\">?</literal>")
8761 ("h" "#+begin_html\n?\n#+end_html"
8762 "<literal style=\"html\">\n?\n</literal>")
8763 ("H" "#+html: "
8764 "<literal style=\"html\">?</literal>")
8765 ("a" "#+begin_ascii\n?\n#+end_ascii")
8766 ("A" "#+ascii: ")
8767 ("i" "#+include %file ?"
8768 "<include file=%file markup=\"?\">")
8770 "Structure completion elements.
8771 This is a list of abbreviation keys and values. The value gets inserted
8772 it you type @samp{.} followed by the key and then the completion key,
8773 usually `M-TAB'. %file will be replaced by a file name after prompting
8774 for the file using completion.
8775 There are two templates for each key, the first uses the original Org syntax,
8776 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8777 the default when the /org-mtags.el/ module has been loaded. See also the
8778 variable `org-mtags-prefer-muse-templates'.
8779 This is an experimental feature, it is undecided if it is going to stay in."
8780 :group 'org-completion
8781 :type '(repeat
8782 (string :tag "Key")
8783 (string :tag "Template")
8784 (string :tag "Muse Template")))
8786 (defun org-try-structure-completion ()
8787 "Try to complete a structure template before point.
8788 This looks for strings like \"<e\" on an otherwise empty line and
8789 expands them."
8790 (let ((l (buffer-substring (point-at-bol) (point)))
8792 (when (and (looking-at "[ \t]*$")
8793 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8794 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8795 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8796 (match-beginning 1)) a)
8797 t)))
8799 (defun org-complete-expand-structure-template (start cell)
8800 "Expand a structure template."
8801 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8802 (rpl (nth (if musep 2 1) cell))
8803 (ind ""))
8804 (delete-region start (point))
8805 (when (string-match "\\`#\\+" rpl)
8806 (cond
8807 ((bolp))
8808 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8809 (setq ind (buffer-substring (point-at-bol) (point))))
8810 (t (newline))))
8811 (setq start (point))
8812 (if (string-match "%file" rpl)
8813 (setq rpl (replace-match
8814 (concat
8815 "\""
8816 (save-match-data
8817 (abbreviate-file-name (read-file-name "Include file: ")))
8818 "\"")
8819 t t rpl)))
8820 (setq rpl (mapconcat 'identity (split-string rpl "\n")
8821 (concat "\n" ind)))
8822 (insert rpl)
8823 (if (re-search-backward "\\?" start t) (delete-char 1))))
8826 (defun org-complete (&optional arg)
8827 "Perform completion on word at point.
8828 At the beginning of a headline, this completes TODO keywords as given in
8829 `org-todo-keywords'.
8830 If the current word is preceded by a backslash, completes the TeX symbols
8831 that are supported for HTML support.
8832 If the current word is preceded by \"#+\", completes special words for
8833 setting file options.
8834 In the line after \"#+STARTUP:, complete valid keywords.\"
8835 At all other locations, this simply calls the value of
8836 `org-completion-fallback-command'."
8837 (interactive "P")
8838 (org-without-partial-completion
8839 (catch 'exit
8840 (let* ((a nil)
8841 (end (point))
8842 (beg1 (save-excursion
8843 (skip-chars-backward (org-re "[:alnum:]_@"))
8844 (point)))
8845 (beg (save-excursion
8846 (skip-chars-backward "a-zA-Z0-9_:$")
8847 (point)))
8848 (confirm (lambda (x) (stringp (car x))))
8849 (searchhead (equal (char-before beg) ?*))
8850 (struct
8851 (when (and (member (char-before beg1) '(?. ?<))
8852 (setq a (assoc (buffer-substring beg1 (point))
8853 org-structure-template-alist)))
8854 (org-complete-expand-structure-template (1- beg1) a)
8855 (throw 'exit t)))
8856 (tag (and (equal (char-before beg1) ?:)
8857 (equal (char-after (point-at-bol)) ?*)))
8858 (prop (and (equal (char-before beg1) ?:)
8859 (not (equal (char-after (point-at-bol)) ?*))))
8860 (texp (equal (char-before beg) ?\\))
8861 (link (equal (char-before beg) ?\[))
8862 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8863 beg)
8864 "#+"))
8865 (startup (string-match "^#\\+STARTUP:.*"
8866 (buffer-substring (point-at-bol) (point))))
8867 (completion-ignore-case opt)
8868 (type nil)
8869 (tbl nil)
8870 (table (cond
8871 (opt
8872 (setq type :opt)
8873 (require 'org-exp)
8874 (append
8875 (mapcar
8876 (lambda (x)
8877 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8878 (cons (match-string 2 x) (match-string 1 x)))
8879 (org-split-string (org-get-current-options) "\n"))
8880 (mapcar 'list org-additional-option-like-keywords)))
8881 (startup
8882 (setq type :startup)
8883 org-startup-options)
8884 (link (append org-link-abbrev-alist-local
8885 org-link-abbrev-alist))
8886 (texp
8887 (setq type :tex)
8888 org-html-entities)
8889 ((string-match "\\`\\*+[ \t]+\\'"
8890 (buffer-substring (point-at-bol) beg))
8891 (setq type :todo)
8892 (mapcar 'list org-todo-keywords-1))
8893 (searchhead
8894 (setq type :searchhead)
8895 (save-excursion
8896 (goto-char (point-min))
8897 (while (re-search-forward org-todo-line-regexp nil t)
8898 (push (list
8899 (org-make-org-heading-search-string
8900 (match-string 3) t))
8901 tbl)))
8902 tbl)
8903 (tag (setq type :tag beg beg1)
8904 (or org-tag-alist (org-get-buffer-tags)))
8905 (prop (setq type :prop beg beg1)
8906 (mapcar 'list (org-buffer-property-keys nil t t)))
8907 (t (progn
8908 (call-interactively org-completion-fallback-command)
8909 (throw 'exit nil)))))
8910 (pattern (buffer-substring-no-properties beg end))
8911 (completion (try-completion pattern table confirm)))
8912 (cond ((eq completion t)
8913 (if (not (assoc (upcase pattern) table))
8914 (message "Already complete")
8915 (if (and (equal type :opt)
8916 (not (member (car (assoc (upcase pattern) table))
8917 org-additional-option-like-keywords)))
8918 (insert (substring (cdr (assoc (upcase pattern) table))
8919 (length pattern)))
8920 (if (memq type '(:tag :prop)) (insert ":")))))
8921 ((null completion)
8922 (message "Can't find completion for \"%s\"" pattern)
8923 (ding))
8924 ((not (string= pattern completion))
8925 (delete-region beg end)
8926 (if (string-match " +$" completion)
8927 (setq completion (replace-match "" t t completion)))
8928 (insert completion)
8929 (if (get-buffer-window "*Completions*")
8930 (delete-window (get-buffer-window "*Completions*")))
8931 (if (assoc completion table)
8932 (if (eq type :todo) (insert " ")
8933 (if (memq type '(:tag :prop)) (insert ":"))))
8934 (if (and (equal type :opt) (assoc completion table))
8935 (message "%s" (substitute-command-keys
8936 "Press \\[org-complete] again to insert example settings"))))
8938 (message "Making completion list...")
8939 (let ((list (sort (all-completions pattern table confirm)
8940 'string<)))
8941 (with-output-to-temp-buffer "*Completions*"
8942 (condition-case nil
8943 ;; Protection needed for XEmacs and emacs 21
8944 (display-completion-list list pattern)
8945 (error (display-completion-list list)))))
8946 (message "Making completion list...%s" "done")))))))
8948 ;;;; TODO, DEADLINE, Comments
8950 (defun org-toggle-comment ()
8951 "Change the COMMENT state of an entry."
8952 (interactive)
8953 (save-excursion
8954 (org-back-to-heading)
8955 (let (case-fold-search)
8956 (if (looking-at (concat outline-regexp
8957 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8958 (replace-match "" t t nil 1)
8959 (if (looking-at outline-regexp)
8960 (progn
8961 (goto-char (match-end 0))
8962 (insert org-comment-string " ")))))))
8964 (defvar org-last-todo-state-is-todo nil
8965 "This is non-nil when the last TODO state change led to a TODO state.
8966 If the last change removed the TODO tag or switched to DONE, then
8967 this is nil.")
8969 (defvar org-setting-tags nil) ; dynamically skipped
8971 (defun org-parse-local-options (string var)
8972 "Parse STRING for startup setting relevant for variable VAR."
8973 (let ((rtn (symbol-value var))
8974 e opts)
8975 (save-match-data
8976 (if (or (not string) (not (string-match "\\S-" string)))
8978 (setq opts (delq nil (mapcar (lambda (x)
8979 (setq e (assoc x org-startup-options))
8980 (if (eq (nth 1 e) var) e nil))
8981 (org-split-string string "[ \t]+"))))
8982 (if (not opts)
8984 (setq rtn nil)
8985 (while (setq e (pop opts))
8986 (if (not (nth 3 e))
8987 (setq rtn (nth 2 e))
8988 (if (not (listp rtn)) (setq rtn nil))
8989 (push (nth 2 e) rtn)))
8990 rtn)))))
8992 (defvar org-todo-setup-filter-hook nil
8993 "Hook for functions that pre-filter todo specs.
8995 Each function takes a todo spec and returns either `nil' or the spec
8996 transformed into canonical form." )
8998 (defvar org-todo-get-default-hook nil
8999 "Hook for functions that get a default item for todo.
9001 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9002 `nil' or a string to be used for the todo mark." )
9004 (defvar org-agenda-headline-snapshot-before-repeat)
9006 (defun org-todo (&optional arg)
9007 "Change the TODO state of an item.
9008 The state of an item is given by a keyword at the start of the heading,
9009 like
9010 *** TODO Write paper
9011 *** DONE Call mom
9013 The different keywords are specified in the variable `org-todo-keywords'.
9014 By default the available states are \"TODO\" and \"DONE\".
9015 So for this example: when the item starts with TODO, it is changed to DONE.
9016 When it starts with DONE, the DONE is removed. And when neither TODO nor
9017 DONE are present, add TODO at the beginning of the heading.
9019 With C-u prefix arg, use completion to determine the new state.
9020 With numeric prefix arg, switch to that state.
9021 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9022 With a tripple C-u prefix, circumvent any state blocking.
9024 For calling through lisp, arg is also interpreted in the following way:
9025 'none -> empty state
9026 \"\"(empty string) -> switch to empty state
9027 'done -> switch to DONE
9028 'nextset -> switch to the next set of keywords
9029 'previousset -> switch to the previous set of keywords
9030 \"WAITING\" -> switch to the specified keyword, but only if it
9031 really is a member of `org-todo-keywords'."
9032 (interactive "P")
9033 (if (equal arg '(16)) (setq arg 'nextset))
9034 (let ((org-blocker-hook org-blocker-hook)
9035 (case-fold-search nil))
9036 (when (equal arg '(64))
9037 (setq arg nil org-blocker-hook nil))
9038 (when (and org-blocker-hook
9039 (or org-inhibit-blocking
9040 (org-entry-get nil "NOBLOCKING")))
9041 (setq org-blocker-hook nil))
9042 (save-excursion
9043 (catch 'exit
9044 (org-back-to-heading)
9045 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9046 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9047 (looking-at " *"))
9048 (let* ((match-data (match-data))
9049 (startpos (point-at-bol))
9050 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9051 (org-log-done org-log-done)
9052 (org-log-repeat org-log-repeat)
9053 (org-todo-log-states org-todo-log-states)
9054 (this (match-string 1))
9055 (hl-pos (match-beginning 0))
9056 (head (org-get-todo-sequence-head this))
9057 (ass (assoc head org-todo-kwd-alist))
9058 (interpret (nth 1 ass))
9059 (done-word (nth 3 ass))
9060 (final-done-word (nth 4 ass))
9061 (last-state (or this ""))
9062 (completion-ignore-case t)
9063 (member (member this org-todo-keywords-1))
9064 (tail (cdr member))
9065 (state (cond
9066 ((and org-todo-key-trigger
9067 (or (and (equal arg '(4))
9068 (eq org-use-fast-todo-selection 'prefix))
9069 (and (not arg) org-use-fast-todo-selection
9070 (not (eq org-use-fast-todo-selection
9071 'prefix)))))
9072 ;; Use fast selection
9073 (org-fast-todo-selection))
9074 ((and (equal arg '(4))
9075 (or (not org-use-fast-todo-selection)
9076 (not org-todo-key-trigger)))
9077 ;; Read a state with completion
9078 (org-ido-completing-read
9079 "State: " (mapcar (lambda(x) (list x))
9080 org-todo-keywords-1)
9081 nil t))
9082 ((eq arg 'right)
9083 (if this
9084 (if tail (car tail) nil)
9085 (car org-todo-keywords-1)))
9086 ((eq arg 'left)
9087 (if (equal member org-todo-keywords-1)
9089 (if this
9090 (nth (- (length org-todo-keywords-1)
9091 (length tail) 2)
9092 org-todo-keywords-1)
9093 (org-last org-todo-keywords-1))))
9094 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9095 (setq arg nil))) ; hack to fall back to cycling
9096 (arg
9097 ;; user or caller requests a specific state
9098 (cond
9099 ((equal arg "") nil)
9100 ((eq arg 'none) nil)
9101 ((eq arg 'done) (or done-word (car org-done-keywords)))
9102 ((eq arg 'nextset)
9103 (or (car (cdr (member head org-todo-heads)))
9104 (car org-todo-heads)))
9105 ((eq arg 'previousset)
9106 (let ((org-todo-heads (reverse org-todo-heads)))
9107 (or (car (cdr (member head org-todo-heads)))
9108 (car org-todo-heads))))
9109 ((car (member arg org-todo-keywords-1)))
9110 ((nth (1- (prefix-numeric-value arg))
9111 org-todo-keywords-1))))
9112 ((null member) (or head (car org-todo-keywords-1)))
9113 ((equal this final-done-word) nil) ;; -> make empty
9114 ((null tail) nil) ;; -> first entry
9115 ((memq interpret '(type priority))
9116 (if (eq this-command last-command)
9117 (car tail)
9118 (if (> (length tail) 0)
9119 (or done-word (car org-done-keywords))
9120 nil)))
9122 (car tail))))
9123 (state (or
9124 (run-hook-with-args-until-success
9125 'org-todo-get-default-hook state last-state)
9126 state))
9127 (next (if state (concat " " state " ") " "))
9128 (change-plist (list :type 'todo-state-change :from this :to state
9129 :position startpos))
9130 dolog now-done-p)
9131 (when org-blocker-hook
9132 (setq org-last-todo-state-is-todo
9133 (not (member this org-done-keywords)))
9134 (unless (save-excursion
9135 (save-match-data
9136 (run-hook-with-args-until-failure
9137 'org-blocker-hook change-plist)))
9138 (if (interactive-p)
9139 (error "TODO state change from %s to %s blocked" this state)
9140 ;; fail silently
9141 (message "TODO state change from %s to %s blocked" this state)
9142 (throw 'exit nil))))
9143 (store-match-data match-data)
9144 (replace-match next t t)
9145 (unless (pos-visible-in-window-p hl-pos)
9146 (message "TODO state changed to %s" (org-trim next)))
9147 (unless head
9148 (setq head (org-get-todo-sequence-head state)
9149 ass (assoc head org-todo-kwd-alist)
9150 interpret (nth 1 ass)
9151 done-word (nth 3 ass)
9152 final-done-word (nth 4 ass)))
9153 (when (memq arg '(nextset previousset))
9154 (message "Keyword-Set %d/%d: %s"
9155 (- (length org-todo-sets) -1
9156 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9157 (length org-todo-sets)
9158 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9159 (setq org-last-todo-state-is-todo
9160 (not (member state org-done-keywords)))
9161 (setq now-done-p (and (member state org-done-keywords)
9162 (not (member this org-done-keywords))))
9163 (and logging (org-local-logging logging))
9164 (when (and (or org-todo-log-states org-log-done)
9165 (not (eq org-inhibit-logging t))
9166 (not (memq arg '(nextset previousset))))
9167 ;; we need to look at recording a time and note
9168 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9169 (nth 2 (assoc this org-todo-log-states))))
9170 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9171 (setq dolog 'time))
9172 (when (and state
9173 (member state org-not-done-keywords)
9174 (not (member this org-not-done-keywords)))
9175 ;; This is now a todo state and was not one before
9176 ;; If there was a CLOSED time stamp, get rid of it.
9177 (org-add-planning-info nil nil 'closed))
9178 (when (and now-done-p org-log-done)
9179 ;; It is now done, and it was not done before
9180 (org-add-planning-info 'closed (org-current-time))
9181 (if (and (not dolog) (eq 'note org-log-done))
9182 (org-add-log-setup 'done state this 'findpos 'note)))
9183 (when (and state dolog)
9184 ;; This is a non-nil state, and we need to log it
9185 (org-add-log-setup 'state state this 'findpos dolog)))
9186 ;; Fixup tag positioning
9187 (org-todo-trigger-tag-changes state)
9188 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9189 (when org-provide-todo-statistics
9190 (org-update-parent-todo-statistics))
9191 (run-hooks 'org-after-todo-state-change-hook)
9192 (if (and arg (not (member state org-done-keywords)))
9193 (setq head (org-get-todo-sequence-head state)))
9194 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9195 ;; Do we need to trigger a repeat?
9196 (when now-done-p
9197 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9198 ;; This is for the agenda, take a snapshot of the headline.
9199 (save-match-data
9200 (setq org-agenda-headline-snapshot-before-repeat
9201 (org-get-heading))))
9202 (org-auto-repeat-maybe state))
9203 ;; Fixup cursor location if close to the keyword
9204 (if (and (outline-on-heading-p)
9205 (not (bolp))
9206 (save-excursion (beginning-of-line 1)
9207 (looking-at org-todo-line-regexp))
9208 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9209 (progn
9210 (goto-char (or (match-end 2) (match-end 1)))
9211 (and (looking-at " ") (just-one-space))))
9212 (when org-trigger-hook
9213 (save-excursion
9214 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9216 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9217 "Block turning an entry into a TODO, using the hierarchy.
9218 This checks whether the current task should be blocked from state
9219 changes. Such blocking occurs when:
9221 1. The task has children which are not all in a completed state.
9223 2. A task has a parent with the property :ORDERED:, and there
9224 are siblings prior to the current task with incomplete
9225 status.
9227 3. The parent of the task is blocked because it has siblings that should
9228 be done first, or is child of a block grandparent TODO entry."
9230 (catch 'dont-block
9231 ;; If this is not a todo state change, or if this entry is already DONE,
9232 ;; do not block
9233 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9234 (member (plist-get change-plist :from)
9235 (cons 'done org-done-keywords))
9236 (member (plist-get change-plist :to)
9237 (cons 'todo org-not-done-keywords)))
9238 (throw 'dont-block t))
9239 ;; If this task has children, and any are undone, it's blocked
9240 (save-excursion
9241 (org-back-to-heading t)
9242 (let ((this-level (funcall outline-level)))
9243 (outline-next-heading)
9244 (let ((child-level (funcall outline-level)))
9245 (while (and (not (eobp))
9246 (> child-level this-level))
9247 ;; this todo has children, check whether they are all
9248 ;; completed
9249 (if (and (not (org-entry-is-done-p))
9250 (org-entry-is-todo-p))
9251 (throw 'dont-block nil))
9252 (outline-next-heading)
9253 (setq child-level (funcall outline-level))))))
9254 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9255 ;; any previous siblings are undone, it's blocked
9256 (save-excursion
9257 (org-back-to-heading t)
9258 (let* ((pos (point))
9259 (parent-pos (and (org-up-heading-safe) (point))))
9260 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9261 (when (and (org-entry-get (point) "ORDERED")
9262 (forward-line 1)
9263 (re-search-forward org-not-done-heading-regexp pos t))
9264 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9265 ;; Search further up the hierarchy, to see if an anchestor is blocked
9266 (while t
9267 (goto-char parent-pos)
9268 (if (not (looking-at org-not-done-heading-regexp))
9269 (throw 'dont-block t)) ; do not block, parent is not a TODO
9270 (setq pos (point))
9271 (setq parent-pos (and (org-up-heading-safe) (point)))
9272 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9273 (when (and (org-entry-get (point) "ORDERED")
9274 (forward-line 1)
9275 (re-search-forward org-not-done-heading-regexp pos t))
9276 (throw 'dont-block nil))))))) ; block, older sibling not done.
9278 (defcustom org-track-ordered-property-with-tag nil
9279 "Should the ORDERED property also be shown as a tag?
9280 The ORDERED property decides if an entry should require subtasks to be
9281 completed in sequence. Since a property is not very visible, setting
9282 this option means that toggling the ORDERED property with the command
9283 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9284 not relevant for the behavior, but it makes things more visible.
9286 Note that toggling the tag with tags commands will not change the property
9287 and therefore not influence behavior!
9289 This can be t, meaning the tag ORDERED should be used, It can also be a
9290 string to select a different tag for this task."
9291 :group 'org-todo
9292 :type '(choice
9293 (const :tag "No tracking" nil)
9294 (const :tag "Track with ORDERED tag" t)
9295 (string :tag "Use other tag")))
9297 (defun org-toggle-ordered-property ()
9298 "Toggle the ORDERED property of the current entry.
9299 For better visibility, you can track the value of this property with a tag.
9300 See variable `org-track-ordered-property-with-tag'."
9301 (interactive)
9302 (let* ((t1 org-track-ordered-property-with-tag)
9303 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9304 (save-excursion
9305 (org-back-to-heading)
9306 (if (org-entry-get nil "ORDERED")
9307 (progn
9308 (org-delete-property "ORDERED")
9309 (and tag (org-toggle-tag tag 'off))
9310 (message "Subtasks can be completed in arbitrary order"))
9311 (org-entry-put nil "ORDERED" "t")
9312 (and tag (org-toggle-tag tag 'on))
9313 (message "Subtasks must be completed in sequence")))))
9315 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9316 (defun org-block-todo-from-checkboxes (change-plist)
9317 "Block turning an entry into a TODO, using checkboxes.
9318 This checks whether the current task should be blocked from state
9319 changes because there are uncheckd boxes in this entry."
9320 (catch 'dont-block
9321 ;; If this is not a todo state change, or if this entry is already DONE,
9322 ;; do not block
9323 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9324 (member (plist-get change-plist :from)
9325 (cons 'done org-done-keywords))
9326 (member (plist-get change-plist :to)
9327 (cons 'todo org-not-done-keywords)))
9328 (throw 'dont-block t))
9329 ;; If this task has checkboxes that are not checked, it's blocked
9330 (save-excursion
9331 (org-back-to-heading t)
9332 (let ((beg (point)) end)
9333 (outline-next-heading)
9334 (setq end (point))
9335 (goto-char beg)
9336 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9337 end t)
9338 (progn
9339 (if (boundp 'org-blocked-by-checkboxes)
9340 (setq org-blocked-by-checkboxes t))
9341 (throw 'dont-block nil)))))
9342 t)) ; do not block
9344 (defvar org-entry-property-inherited-from) ;; defined below
9345 (defun org-update-parent-todo-statistics ()
9346 "Update any statistics cookie in the parent of the current headline.
9347 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9348 the entire subtree and this will travel up the hierarchy and update
9349 statistics everywhere."
9350 (interactive)
9351 (let* ((lim 0) prop
9352 (recursive (or (not org-hierarchical-todo-statistics)
9353 (string-match
9354 "\\<recursive\\>"
9355 (or (setq prop (org-entry-get
9356 nil "COOKIE_DATA" 'inherit)) ""))))
9357 (lim (or (and prop (marker-position
9358 org-entry-property-inherited-from))
9359 lim))
9360 (first t)
9361 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9362 level ltoggle l1
9363 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9364 (catch 'exit
9365 (save-excursion
9366 (beginning-of-line 1)
9367 (if (org-at-heading-p)
9368 (setq ltoggle (funcall outline-level))
9369 (error "This should not happen"))
9370 (while (and (setq level (org-up-heading-safe))
9371 (or recursive first)
9372 (>= (point) lim))
9373 (setq first nil)
9374 (unless (and level
9375 (not (string-match
9376 "\\<checkbox\\>"
9377 (downcase
9378 (or (org-entry-get
9379 nil "COOKIE_DATA")
9380 "")))))
9381 (throw 'exit nil))
9382 (while (re-search-forward box-re (point-at-eol) t)
9383 (setq cnt-all 0 cnt-done 0 cookie-present t)
9384 (setq is-percent (match-end 2))
9385 (save-match-data
9386 (unless (outline-next-heading) (throw 'exit nil))
9387 (while (and (looking-at org-complex-heading-regexp)
9388 (> (setq l1 (length (match-string 1))) level))
9389 (setq kwd (and (or recursive (= l1 ltoggle))
9390 (match-string 2)))
9391 (and kwd (setq cnt-all (1+ cnt-all)))
9392 (and (member kwd org-done-keywords)
9393 (setq cnt-done (1+ cnt-done)))
9394 (outline-next-heading)))
9395 (replace-match
9396 (if is-percent
9397 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9398 (format "[%d/%d]" cnt-done cnt-all)))))
9399 (when cookie-present
9400 (run-hook-with-args 'org-after-todo-statistics-hook
9401 cnt-done (- cnt-all cnt-done)))))
9402 (run-hooks 'org-todo-statistics-hook)))
9404 (defvar org-after-todo-statistics-hook nil
9405 "Hook that is called after a TODO statistics cookie has been updated.
9406 Each function is called with two arguments: the number of not-done entries
9407 and the number of done entries.
9409 For example, the following function, when added to this hook, will switch
9410 an entry to DONE when all children are done, and back to TODO when new
9411 entries are set to a TODO status. Note that this hook is only called
9412 when there is a statistics cookie in the headline!
9414 (defun org-summary-todo (n-done n-not-done)
9415 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9416 (let (org-log-done org-log-states) ; turn off logging
9417 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9420 (defvar org-todo-statistics-hook nil
9421 "Hook that is run whenever Org thinks TODO statistics should be updated.
9422 This hook runs even if there is no statisics cookie present, in which case
9423 `org-after-todo-statistics-hook' would not run.")
9425 (defun org-todo-trigger-tag-changes (state)
9426 "Apply the changes defined in `org-todo-state-tags-triggers'."
9427 (let ((l org-todo-state-tags-triggers)
9428 changes)
9429 (when (or (not state) (equal state ""))
9430 (setq changes (append changes (cdr (assoc "" l)))))
9431 (when (and (stringp state) (> (length state) 0))
9432 (setq changes (append changes (cdr (assoc state l)))))
9433 (when (member state org-not-done-keywords)
9434 (setq changes (append changes (cdr (assoc 'todo l)))))
9435 (when (member state org-done-keywords)
9436 (setq changes (append changes (cdr (assoc 'done l)))))
9437 (dolist (c changes)
9438 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9440 (defun org-local-logging (value)
9441 "Get logging settings from a property VALUE."
9442 (let* (words w a)
9443 ;; directly set the variables, they are already local.
9444 (setq org-log-done nil
9445 org-log-repeat nil
9446 org-todo-log-states nil)
9447 (setq words (org-split-string value))
9448 (while (setq w (pop words))
9449 (cond
9450 ((setq a (assoc w org-startup-options))
9451 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9452 (set (nth 1 a) (nth 2 a))))
9453 ((setq a (org-extract-log-state-settings w))
9454 (and (member (car a) org-todo-keywords-1)
9455 (push a org-todo-log-states)))))))
9457 (defun org-get-todo-sequence-head (kwd)
9458 "Return the head of the TODO sequence to which KWD belongs.
9459 If KWD is not set, check if there is a text property remembering the
9460 right sequence."
9461 (let (p)
9462 (cond
9463 ((not kwd)
9464 (or (get-text-property (point-at-bol) 'org-todo-head)
9465 (progn
9466 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9467 nil (point-at-eol)))
9468 (get-text-property p 'org-todo-head))))
9469 ((not (member kwd org-todo-keywords-1))
9470 (car org-todo-keywords-1))
9471 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9473 (defun org-fast-todo-selection ()
9474 "Fast TODO keyword selection with single keys.
9475 Returns the new TODO keyword, or nil if no state change should occur."
9476 (let* ((fulltable org-todo-key-alist)
9477 (done-keywords org-done-keywords) ;; needed for the faces.
9478 (maxlen (apply 'max (mapcar
9479 (lambda (x)
9480 (if (stringp (car x)) (string-width (car x)) 0))
9481 fulltable)))
9482 (expert nil)
9483 (fwidth (+ maxlen 3 1 3))
9484 (ncol (/ (- (window-width) 4) fwidth))
9485 tg cnt e c tbl
9486 groups ingroup)
9487 (save-excursion
9488 (save-window-excursion
9489 (if expert
9490 (set-buffer (get-buffer-create " *Org todo*"))
9491 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9492 (erase-buffer)
9493 (org-set-local 'org-done-keywords done-keywords)
9494 (setq tbl fulltable cnt 0)
9495 (while (setq e (pop tbl))
9496 (cond
9497 ((equal e '(:startgroup))
9498 (push '() groups) (setq ingroup t)
9499 (when (not (= cnt 0))
9500 (setq cnt 0)
9501 (insert "\n"))
9502 (insert "{ "))
9503 ((equal e '(:endgroup))
9504 (setq ingroup nil cnt 0)
9505 (insert "}\n"))
9506 ((equal e '(:newline))
9507 (when (not (= cnt 0))
9508 (setq cnt 0)
9509 (insert "\n")
9510 (setq e (car tbl))
9511 (while (equal (car tbl) '(:newline))
9512 (insert "\n")
9513 (setq tbl (cdr tbl)))))
9515 (setq tg (car e) c (cdr e))
9516 (if ingroup (push tg (car groups)))
9517 (setq tg (org-add-props tg nil 'face
9518 (org-get-todo-face tg)))
9519 (if (and (= cnt 0) (not ingroup)) (insert " "))
9520 (insert "[" c "] " tg (make-string
9521 (- fwidth 4 (length tg)) ?\ ))
9522 (when (= (setq cnt (1+ cnt)) ncol)
9523 (insert "\n")
9524 (if ingroup (insert " "))
9525 (setq cnt 0)))))
9526 (insert "\n")
9527 (goto-char (point-min))
9528 (if (not expert) (org-fit-window-to-buffer))
9529 (message "[a-z..]:Set [SPC]:clear")
9530 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9531 (cond
9532 ((or (= c ?\C-g)
9533 (and (= c ?q) (not (rassoc c fulltable))))
9534 (setq quit-flag t))
9535 ((= c ?\ ) nil)
9536 ((setq e (rassoc c fulltable) tg (car e))
9538 (t (setq quit-flag t)))))))
9540 (defun org-entry-is-todo-p ()
9541 (member (org-get-todo-state) org-not-done-keywords))
9543 (defun org-entry-is-done-p ()
9544 (member (org-get-todo-state) org-done-keywords))
9546 (defun org-get-todo-state ()
9547 (save-excursion
9548 (org-back-to-heading t)
9549 (and (looking-at org-todo-line-regexp)
9550 (match-end 2)
9551 (match-string 2))))
9553 (defun org-at-date-range-p (&optional inactive-ok)
9554 "Is the cursor inside a date range?"
9555 (interactive)
9556 (save-excursion
9557 (catch 'exit
9558 (let ((pos (point)))
9559 (skip-chars-backward "^[<\r\n")
9560 (skip-chars-backward "<[")
9561 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9562 (>= (match-end 0) pos)
9563 (throw 'exit t))
9564 (skip-chars-backward "^<[\r\n")
9565 (skip-chars-backward "<[")
9566 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9567 (>= (match-end 0) pos)
9568 (throw 'exit t)))
9569 nil)))
9571 (defun org-get-repeat ()
9572 "Check if there is a deadline/schedule with repeater in this entry."
9573 (save-match-data
9574 (save-excursion
9575 (org-back-to-heading t)
9576 (if (re-search-forward
9577 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9578 (match-string 1)))))
9580 (defvar org-last-changed-timestamp)
9581 (defvar org-last-inserted-timestamp)
9582 (defvar org-log-post-message)
9583 (defvar org-log-note-purpose)
9584 (defvar org-log-note-how)
9585 (defvar org-log-note-extra)
9586 (defun org-auto-repeat-maybe (done-word)
9587 "Check if the current headline contains a repeated deadline/schedule.
9588 If yes, set TODO state back to what it was and change the base date
9589 of repeating deadline/scheduled time stamps to new date.
9590 This function is run automatically after each state change to a DONE state."
9591 ;; last-state is dynamically scoped into this function
9592 (let* ((repeat (org-get-repeat))
9593 (aa (assoc last-state org-todo-kwd-alist))
9594 (interpret (nth 1 aa))
9595 (head (nth 2 aa))
9596 (whata '(("d" . day) ("m" . month) ("y" . year)))
9597 (msg "Entry repeats: ")
9598 (org-log-done nil)
9599 (org-todo-log-states nil)
9600 (nshiftmax 10) (nshift 0)
9601 re type n what ts time)
9602 (when repeat
9603 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9604 (org-todo (if (eq interpret 'type) last-state head))
9605 (org-entry-put nil "LAST_REPEAT" (format-time-string
9606 (org-time-stamp-format t t)))
9607 (when org-log-repeat
9608 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9609 (memq 'org-add-log-note post-command-hook))
9610 ;; OK, we are already setup for some record
9611 (if (eq org-log-repeat 'note)
9612 ;; make sure we take a note, not only a time stamp
9613 (setq org-log-note-how 'note))
9614 ;; Set up for taking a record
9615 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9616 last-state
9617 'findpos org-log-repeat)))
9618 (org-back-to-heading t)
9619 (org-add-planning-info nil nil 'closed)
9620 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9621 org-deadline-time-regexp "\\)\\|\\("
9622 org-ts-regexp "\\)"))
9623 (while (re-search-forward
9624 re (save-excursion (outline-next-heading) (point)) t)
9625 (setq type (if (match-end 1) org-scheduled-string
9626 (if (match-end 3) org-deadline-string "Plain:"))
9627 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9628 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9629 (setq n (string-to-number (match-string 2 ts))
9630 what (match-string 3 ts))
9631 (if (equal what "w") (setq n (* n 7) what "d"))
9632 ;; Preparation, see if we need to modify the start date for the change
9633 (when (match-end 1)
9634 (setq time (save-match-data (org-time-string-to-time ts)))
9635 (cond
9636 ((equal (match-string 1 ts) ".")
9637 ;; Shift starting date to today
9638 (org-timestamp-change
9639 (- (time-to-days (current-time)) (time-to-days time))
9640 'day))
9641 ((equal (match-string 1 ts) "+")
9642 (while (or (= nshift 0)
9643 (<= (time-to-days time) (time-to-days (current-time))))
9644 (when (= (incf nshift) nshiftmax)
9645 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9646 (error "Abort")))
9647 (org-timestamp-change n (cdr (assoc what whata)))
9648 (org-at-timestamp-p t)
9649 (setq ts (match-string 1))
9650 (setq time (save-match-data (org-time-string-to-time ts))))
9651 (org-timestamp-change (- n) (cdr (assoc what whata)))
9652 ;; rematch, so that we have everything in place for the real shift
9653 (org-at-timestamp-p t)
9654 (setq ts (match-string 1))
9655 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9656 (org-timestamp-change n (cdr (assoc what whata)))
9657 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9658 (setq org-log-post-message msg)
9659 (message "%s" msg))))
9661 (defun org-show-todo-tree (arg)
9662 "Make a compact tree which shows all headlines marked with TODO.
9663 The tree will show the lines where the regexp matches, and all higher
9664 headlines above the match.
9665 With a \\[universal-argument] prefix, prompt for a regexp to match.
9666 With a numeric prefix N, construct a sparse tree for the Nth element
9667 of `org-todo-keywords-1'."
9668 (interactive "P")
9669 (let ((case-fold-search nil)
9670 (kwd-re
9671 (cond ((null arg) org-not-done-regexp)
9672 ((equal arg '(4))
9673 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9674 (mapcar 'list org-todo-keywords-1))))
9675 (concat "\\("
9676 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9677 "\\)\\>")))
9678 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9679 (regexp-quote (nth (1- (prefix-numeric-value arg))
9680 org-todo-keywords-1)))
9681 (t (error "Invalid prefix argument: %s" arg)))))
9682 (message "%d TODO entries found"
9683 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9685 (defun org-deadline (&optional remove time)
9686 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9687 With argument REMOVE, remove any deadline from the item.
9688 When TIME is set, it should be an internal time specification, and the
9689 scheduling will use the corresponding date."
9690 (interactive "P")
9691 (if remove
9692 (progn
9693 (org-remove-timestamp-with-keyword org-deadline-string)
9694 (message "Item no longer has a deadline."))
9695 (if (org-get-repeat)
9696 (error "Cannot change deadline on task with repeater, please do that by hand")
9697 (org-add-planning-info 'deadline time 'closed)
9698 (message "Deadline on %s" org-last-inserted-timestamp))))
9700 (defun org-schedule (&optional remove time)
9701 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9702 With argument REMOVE, remove any scheduling date from the item.
9703 When TIME is set, it should be an internal time specification, and the
9704 scheduling will use the corresponding date."
9705 (interactive "P")
9706 (if remove
9707 (progn
9708 (org-remove-timestamp-with-keyword org-scheduled-string)
9709 (message "Item is no longer scheduled."))
9710 (if (org-get-repeat)
9711 (error "Cannot reschedule task with repeater, please do that by hand")
9712 (org-add-planning-info 'scheduled time 'closed)
9713 (message "Scheduled to %s" org-last-inserted-timestamp))))
9715 (defun org-get-scheduled-time (pom &optional inherit)
9716 "Get the scheduled time as a time tuple, of a format suitable
9717 for calling org-schedule with, or if there is no scheduling,
9718 returns nil."
9719 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9720 (when time
9721 (apply 'encode-time (org-parse-time-string time)))))
9723 (defun org-get-deadline-time (pom &optional inherit)
9724 "Get the deadine as a time tuple, of a format suitable for
9725 calling org-deadlin with, or if there is no scheduling, returns
9726 nil."
9727 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9728 (when time
9729 (apply 'encode-time (org-parse-time-string time)))))
9731 (defun org-remove-timestamp-with-keyword (keyword)
9732 "Remove all time stamps with KEYWORD in the current entry."
9733 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9734 beg)
9735 (save-excursion
9736 (org-back-to-heading t)
9737 (setq beg (point))
9738 (org-end-of-subtree t t)
9739 (while (re-search-backward re beg t)
9740 (replace-match "")
9741 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9742 (equal (char-before) ?\ ))
9743 (backward-delete-char 1)
9744 (if (string-match "^[ \t]*$" (buffer-substring
9745 (point-at-bol) (point-at-eol)))
9746 (delete-region (point-at-bol)
9747 (min (point-max) (1+ (point-at-eol))))))))))
9749 (defun org-add-planning-info (what &optional time &rest remove)
9750 "Insert new timestamp with keyword in the line directly after the headline.
9751 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9752 If non is given, the user is prompted for a date.
9753 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9754 be removed."
9755 (interactive)
9756 (let (org-time-was-given org-end-time-was-given ts
9757 end default-time default-input)
9759 (catch 'exit
9760 (when (and (not time) (memq what '(scheduled deadline)))
9761 ;; Try to get a default date/time from existing timestamp
9762 (save-excursion
9763 (org-back-to-heading t)
9764 (setq end (save-excursion (outline-next-heading) (point)))
9765 (when (re-search-forward (if (eq what 'scheduled)
9766 org-scheduled-time-regexp
9767 org-deadline-time-regexp)
9768 end t)
9769 (setq ts (match-string 1)
9770 default-time
9771 (apply 'encode-time (org-parse-time-string ts))
9772 default-input (and ts (org-get-compact-tod ts))))))
9773 (when what
9774 ;; If necessary, get the time from the user
9775 (setq time (or time (org-read-date nil 'to-time nil nil
9776 default-time default-input))))
9778 (when (and org-insert-labeled-timestamps-at-point
9779 (member what '(scheduled deadline)))
9780 (insert
9781 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9782 (org-insert-time-stamp time org-time-was-given
9783 nil nil nil (list org-end-time-was-given))
9784 (setq what nil))
9785 (save-excursion
9786 (save-restriction
9787 (let (col list elt ts buffer-invisibility-spec)
9788 (org-back-to-heading t)
9789 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9790 (goto-char (match-end 1))
9791 (setq col (current-column))
9792 (goto-char (match-end 0))
9793 (if (eobp) (insert "\n") (forward-char 1))
9794 (when (and (not what)
9795 (not (looking-at
9796 (concat "[ \t]*"
9797 org-keyword-time-not-clock-regexp))))
9798 ;; Nothing to add, nothing to remove...... :-)
9799 (throw 'exit nil))
9800 (if (and (not (looking-at outline-regexp))
9801 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9802 "[^\r\n]*"))
9803 (not (equal (match-string 1) org-clock-string)))
9804 (narrow-to-region (match-beginning 0) (match-end 0))
9805 (insert-before-markers "\n")
9806 (backward-char 1)
9807 (narrow-to-region (point) (point))
9808 (and org-adapt-indentation (org-indent-to-column col)))
9809 ;; Check if we have to remove something.
9810 (setq list (cons what remove))
9811 (while list
9812 (setq elt (pop list))
9813 (goto-char (point-min))
9814 (when (or (and (eq elt 'scheduled)
9815 (re-search-forward org-scheduled-time-regexp nil t))
9816 (and (eq elt 'deadline)
9817 (re-search-forward org-deadline-time-regexp nil t))
9818 (and (eq elt 'closed)
9819 (re-search-forward org-closed-time-regexp nil t)))
9820 (replace-match "")
9821 (if (looking-at "--+<[^>]+>") (replace-match ""))
9822 (if (looking-at " +") (replace-match ""))))
9823 (goto-char (point-max))
9824 (when what
9825 (insert
9826 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9827 (cond ((eq what 'scheduled) org-scheduled-string)
9828 ((eq what 'deadline) org-deadline-string)
9829 ((eq what 'closed) org-closed-string))
9830 " ")
9831 (setq ts (org-insert-time-stamp
9832 time
9833 (or org-time-was-given
9834 (and (eq what 'closed) org-log-done-with-time))
9835 (eq what 'closed)
9836 nil nil (list org-end-time-was-given)))
9837 (end-of-line 1))
9838 (goto-char (point-min))
9839 (widen)
9840 (if (and (looking-at "[ \t]+\n")
9841 (equal (char-before) ?\n))
9842 (delete-region (1- (point)) (point-at-eol)))
9843 ts))))))
9845 (defvar org-log-note-marker (make-marker))
9846 (defvar org-log-note-purpose nil)
9847 (defvar org-log-note-state nil)
9848 (defvar org-log-note-previous-state nil)
9849 (defvar org-log-note-how nil)
9850 (defvar org-log-note-extra nil)
9851 (defvar org-log-note-window-configuration nil)
9852 (defvar org-log-note-return-to (make-marker))
9853 (defvar org-log-post-message nil
9854 "Message to be displayed after a log note has been stored.
9855 The auto-repeater uses this.")
9857 (defun org-add-note ()
9858 "Add a note to the current entry.
9859 This is done in the same way as adding a state change note."
9860 (interactive)
9861 (org-add-log-setup 'note nil nil 'findpos nil))
9863 (defvar org-property-end-re)
9864 (defun org-add-log-setup (&optional purpose state prev-state
9865 findpos how &optional extra)
9866 "Set up the post command hook to take a note.
9867 If this is about to TODO state change, the new state is expected in STATE.
9868 When FINDPOS is non-nil, find the correct position for the note in
9869 the current entry. If not, assume that it can be inserted at point.
9870 HOW is an indicator what kind of note should be created.
9871 EXTRA is additional text that will be inserted into the notes buffer."
9872 (let* ((org-log-into-drawer (org-log-into-drawer))
9873 (drawer (cond ((stringp org-log-into-drawer)
9874 org-log-into-drawer)
9875 (org-log-into-drawer "LOGBOOK")
9876 (t nil))))
9877 (save-restriction
9878 (save-excursion
9879 (when findpos
9880 (org-back-to-heading t)
9881 (narrow-to-region (point) (save-excursion
9882 (outline-next-heading) (point)))
9883 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9884 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9885 "[^\r\n]*\\)?"))
9886 (goto-char (match-end 0))
9887 (cond
9888 (drawer
9889 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9890 nil t)
9891 (progn
9892 (goto-char (match-end 0))
9893 (or org-log-states-order-reversed
9894 (and (re-search-forward org-property-end-re nil t)
9895 (goto-char (1- (match-beginning 0))))))
9896 (insert "\n:" drawer ":\n:END:")
9897 (beginning-of-line 0)
9898 (org-indent-line-function)
9899 (beginning-of-line 2)
9900 (org-indent-line-function)
9901 (end-of-line 0)))
9902 ((and org-log-state-notes-insert-after-drawers
9903 (save-excursion
9904 (forward-line) (looking-at org-drawer-regexp)))
9905 (forward-line)
9906 (while (looking-at org-drawer-regexp)
9907 (goto-char (match-end 0))
9908 (re-search-forward org-property-end-re (point-max) t)
9909 (forward-line))
9910 (forward-line -1)))
9911 (unless org-log-states-order-reversed
9912 (and (= (char-after) ?\n) (forward-char 1))
9913 (org-skip-over-state-notes)
9914 (skip-chars-backward " \t\n\r")))
9915 (move-marker org-log-note-marker (point))
9916 (setq org-log-note-purpose purpose
9917 org-log-note-state state
9918 org-log-note-previous-state prev-state
9919 org-log-note-how how
9920 org-log-note-extra extra)
9921 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9923 (defun org-skip-over-state-notes ()
9924 "Skip past the list of State notes in an entry."
9925 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9926 (while (looking-at "[ \t]*- State")
9927 (condition-case nil
9928 (org-next-item)
9929 (error (org-end-of-item)))))
9931 (defun org-add-log-note (&optional purpose)
9932 "Pop up a window for taking a note, and add this note later at point."
9933 (remove-hook 'post-command-hook 'org-add-log-note)
9934 (setq org-log-note-window-configuration (current-window-configuration))
9935 (delete-other-windows)
9936 (move-marker org-log-note-return-to (point))
9937 (switch-to-buffer (marker-buffer org-log-note-marker))
9938 (goto-char org-log-note-marker)
9939 (org-switch-to-buffer-other-window "*Org Note*")
9940 (erase-buffer)
9941 (if (memq org-log-note-how '(time state))
9942 (let (current-prefix-arg) (org-store-log-note))
9943 (let ((org-inhibit-startup t)) (org-mode))
9944 (insert (format "# Insert note for %s.
9945 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9946 (cond
9947 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9948 ((eq org-log-note-purpose 'done) "closed todo item")
9949 ((eq org-log-note-purpose 'state)
9950 (format "state change from \"%s\" to \"%s\""
9951 (or org-log-note-previous-state "")
9952 (or org-log-note-state "")))
9953 ((eq org-log-note-purpose 'note)
9954 "this entry")
9955 (t (error "This should not happen")))))
9956 (if org-log-note-extra (insert org-log-note-extra))
9957 (org-set-local 'org-finish-function 'org-store-log-note)))
9959 (defvar org-note-abort nil) ; dynamically scoped
9960 (defun org-store-log-note ()
9961 "Finish taking a log note, and insert it to where it belongs."
9962 (let ((txt (buffer-string))
9963 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9964 lines ind)
9965 (kill-buffer (current-buffer))
9966 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9967 (setq txt (replace-match "" t t txt)))
9968 (if (string-match "\\s-+\\'" txt)
9969 (setq txt (replace-match "" t t txt)))
9970 (setq lines (org-split-string txt "\n"))
9971 (when (and note (string-match "\\S-" note))
9972 (setq note
9973 (org-replace-escapes
9974 note
9975 (list (cons "%u" (user-login-name))
9976 (cons "%U" user-full-name)
9977 (cons "%t" (format-time-string
9978 (org-time-stamp-format 'long 'inactive)
9979 (current-time)))
9980 (cons "%s" (if org-log-note-state
9981 (concat "\"" org-log-note-state "\"")
9982 ""))
9983 (cons "%S" (if org-log-note-previous-state
9984 (concat "\"" org-log-note-previous-state "\"")
9985 "\"\"")))))
9986 (if lines (setq note (concat note " \\\\")))
9987 (push note lines))
9988 (when (or current-prefix-arg org-note-abort)
9989 (when org-log-into-drawer
9990 (org-remove-empty-drawer-at
9991 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
9992 org-log-note-marker))
9993 (setq lines nil))
9994 (when lines
9995 (save-excursion
9996 (set-buffer (marker-buffer org-log-note-marker))
9997 (save-excursion
9998 (goto-char org-log-note-marker)
9999 (move-marker org-log-note-marker nil)
10000 (end-of-line 1)
10001 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10002 (insert "- " (pop lines))
10003 (org-indent-line-function)
10004 (beginning-of-line 1)
10005 (looking-at "[ \t]*")
10006 (setq ind (concat (match-string 0) " "))
10007 (end-of-line 1)
10008 (while lines (insert "\n" ind (pop lines)))
10009 (message "Note stored")
10010 (org-back-to-heading t)
10011 (org-cycle-hide-drawers 'children)))))
10012 (set-window-configuration org-log-note-window-configuration)
10013 (with-current-buffer (marker-buffer org-log-note-return-to)
10014 (goto-char org-log-note-return-to))
10015 (move-marker org-log-note-return-to nil)
10016 (and org-log-post-message (message "%s" org-log-post-message)))
10018 (defun org-remove-empty-drawer-at (drawer pos)
10019 "Remove an emptyr DARWER drawer at position POS.
10020 POS may also be a marker."
10021 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10022 (save-excursion
10023 (save-restriction
10024 (widen)
10025 (goto-char pos)
10026 (if (org-in-regexp
10027 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10028 (replace-match ""))))))
10030 (defun org-sparse-tree (&optional arg)
10031 "Create a sparse tree, prompt for the details.
10032 This command can create sparse trees. You first need to select the type
10033 of match used to create the tree:
10035 t Show entries with a specific TODO keyword.
10036 m Show entries selected by a tags/property match.
10037 p Enter a property name and its value (both with completion on existing
10038 names/values) and show entries with that property.
10039 r Show entries matching a regular expression.
10040 d Show deadlines due within `org-deadline-warning-days'.
10041 b Show deadlines and scheduled items before a date.
10042 a Show deadlines and scheduled items after a date."
10043 (interactive "P")
10044 (let (ans kwd value)
10045 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10046 (setq ans (read-char-exclusive))
10047 (cond
10048 ((equal ans ?d)
10049 (call-interactively 'org-check-deadlines))
10050 ((equal ans ?b)
10051 (call-interactively 'org-check-before-date))
10052 ((equal ans ?a)
10053 (call-interactively 'org-check-after-date))
10054 ((equal ans ?t)
10055 (org-show-todo-tree '(4)))
10056 ((member ans '(?T ?m))
10057 (call-interactively 'org-match-sparse-tree))
10058 ((member ans '(?p ?P))
10059 (setq kwd (org-ido-completing-read "Property: "
10060 (mapcar 'list (org-buffer-property-keys))))
10061 (setq value (org-ido-completing-read "Value: "
10062 (mapcar 'list (org-property-values kwd))))
10063 (unless (string-match "\\`{.*}\\'" value)
10064 (setq value (concat "\"" value "\"")))
10065 (org-match-sparse-tree arg (concat kwd "=" value)))
10066 ((member ans '(?r ?R ?/))
10067 (call-interactively 'org-occur))
10068 (t (error "No such sparse tree command \"%c\"" ans)))))
10070 (defvar org-occur-highlights nil
10071 "List of overlays used for occur matches.")
10072 (make-variable-buffer-local 'org-occur-highlights)
10073 (defvar org-occur-parameters nil
10074 "Parameters of the active org-occur calls.
10075 This is a list, each call to org-occur pushes as cons cell,
10076 containing the regular expression and the callback, onto the list.
10077 The list can contain several entries if `org-occur' has been called
10078 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10079 will only contain one set of parameters. When the highlights are
10080 removed (for example with `C-c C-c', or with the next edit (depending
10081 on `org-remove-highlights-with-change'), this variable is emptied
10082 as well.")
10083 (make-variable-buffer-local 'org-occur-parameters)
10085 (defun org-occur (regexp &optional keep-previous callback)
10086 "Make a compact tree which shows all matches of REGEXP.
10087 The tree will show the lines where the regexp matches, and all higher
10088 headlines above the match. It will also show the heading after the match,
10089 to make sure editing the matching entry is easy.
10090 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10091 call to `org-occur' will be kept, to allow stacking of calls to this
10092 command.
10093 If CALLBACK is non-nil, it is a function which is called to confirm
10094 that the match should indeed be shown."
10095 (interactive "sRegexp: \nP")
10096 (unless keep-previous
10097 (org-remove-occur-highlights nil nil t))
10098 (push (cons regexp callback) org-occur-parameters)
10099 (let ((cnt 0))
10100 (save-excursion
10101 (goto-char (point-min))
10102 (if (or (not keep-previous) ; do not want to keep
10103 (not org-occur-highlights)) ; no previous matches
10104 ;; hide everything
10105 (org-overview))
10106 (while (re-search-forward regexp nil t)
10107 (when (or (not callback)
10108 (save-match-data (funcall callback)))
10109 (setq cnt (1+ cnt))
10110 (when org-highlight-sparse-tree-matches
10111 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10112 (org-show-context 'occur-tree))))
10113 (when org-remove-highlights-with-change
10114 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10115 nil 'local))
10116 (unless org-sparse-tree-open-archived-trees
10117 (org-hide-archived-subtrees (point-min) (point-max)))
10118 (run-hooks 'org-occur-hook)
10119 (if (interactive-p)
10120 (message "%d match(es) for regexp %s" cnt regexp))
10121 cnt))
10123 (defun org-show-context (&optional key)
10124 "Make sure point and context and visible.
10125 How much context is shown depends upon the variables
10126 `org-show-hierarchy-above', `org-show-following-heading'. and
10127 `org-show-siblings'."
10128 (let ((heading-p (org-on-heading-p t))
10129 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10130 (following-p (org-get-alist-option org-show-following-heading key))
10131 (entry-p (org-get-alist-option org-show-entry-below key))
10132 (siblings-p (org-get-alist-option org-show-siblings key)))
10133 (catch 'exit
10134 ;; Show heading or entry text
10135 (if (and heading-p (not entry-p))
10136 (org-flag-heading nil) ; only show the heading
10137 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10138 (org-show-hidden-entry))) ; show entire entry
10139 (when following-p
10140 ;; Show next sibling, or heading below text
10141 (save-excursion
10142 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10143 (org-flag-heading nil))))
10144 (when siblings-p (org-show-siblings))
10145 (when hierarchy-p
10146 ;; show all higher headings, possibly with siblings
10147 (save-excursion
10148 (while (and (condition-case nil
10149 (progn (org-up-heading-all 1) t)
10150 (error nil))
10151 (not (bobp)))
10152 (org-flag-heading nil)
10153 (when siblings-p (org-show-siblings))))))))
10155 (defun org-reveal (&optional siblings)
10156 "Show current entry, hierarchy above it, and the following headline.
10157 This can be used to show a consistent set of context around locations
10158 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10159 not t for the search context.
10161 With optional argument SIBLINGS, on each level of the hierarchy all
10162 siblings are shown. This repairs the tree structure to what it would
10163 look like when opened with hierarchical calls to `org-cycle'."
10164 (interactive "P")
10165 (let ((org-show-hierarchy-above t)
10166 (org-show-following-heading t)
10167 (org-show-siblings (if siblings t org-show-siblings)))
10168 (org-show-context nil)))
10170 (defun org-highlight-new-match (beg end)
10171 "Highlight from BEG to END and mark the highlight is an occur headline."
10172 (let ((ov (org-make-overlay beg end)))
10173 (org-overlay-put ov 'face 'secondary-selection)
10174 (push ov org-occur-highlights)))
10176 (defun org-remove-occur-highlights (&optional beg end noremove)
10177 "Remove the occur highlights from the buffer.
10178 BEG and END are ignored. If NOREMOVE is nil, remove this function
10179 from the `before-change-functions' in the current buffer."
10180 (interactive)
10181 (unless org-inhibit-highlight-removal
10182 (mapc 'org-delete-overlay org-occur-highlights)
10183 (setq org-occur-highlights nil)
10184 (setq org-occur-parameters nil)
10185 (unless noremove
10186 (remove-hook 'before-change-functions
10187 'org-remove-occur-highlights 'local))))
10189 ;;;; Priorities
10191 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10192 "Regular expression matching the priority indicator.")
10194 (defvar org-remove-priority-next-time nil)
10196 (defun org-priority-up ()
10197 "Increase the priority of the current item."
10198 (interactive)
10199 (org-priority 'up))
10201 (defun org-priority-down ()
10202 "Decrease the priority of the current item."
10203 (interactive)
10204 (org-priority 'down))
10206 (defun org-priority (&optional action)
10207 "Change the priority of an item by ARG.
10208 ACTION can be `set', `up', `down', or a character."
10209 (interactive)
10210 (unless org-enable-priority-commands
10211 (error "Priority commands are disabled"))
10212 (setq action (or action 'set))
10213 (let (current new news have remove)
10214 (save-excursion
10215 (org-back-to-heading t)
10216 (if (looking-at org-priority-regexp)
10217 (setq current (string-to-char (match-string 2))
10218 have t)
10219 (setq current org-default-priority))
10220 (cond
10221 ((or (eq action 'set)
10222 (if (featurep 'xemacs) (characterp action) (integerp action)))
10223 (if (not (eq action 'set))
10224 (setq new action)
10225 (message "Priority %c-%c, SPC to remove: "
10226 org-highest-priority org-lowest-priority)
10227 (setq new (read-char-exclusive)))
10228 (if (and (= (upcase org-highest-priority) org-highest-priority)
10229 (= (upcase org-lowest-priority) org-lowest-priority))
10230 (setq new (upcase new)))
10231 (cond ((equal new ?\ ) (setq remove t))
10232 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10233 (error "Priority must be between `%c' and `%c'"
10234 org-highest-priority org-lowest-priority))))
10235 ((eq action 'up)
10236 (if (and (not have) (eq last-command this-command))
10237 (setq new org-lowest-priority)
10238 (setq new (if (and org-priority-start-cycle-with-default (not have))
10239 org-default-priority (1- current)))))
10240 ((eq action 'down)
10241 (if (and (not have) (eq last-command this-command))
10242 (setq new org-highest-priority)
10243 (setq new (if (and org-priority-start-cycle-with-default (not have))
10244 org-default-priority (1+ current)))))
10245 (t (error "Invalid action")))
10246 (if (or (< (upcase new) org-highest-priority)
10247 (> (upcase new) org-lowest-priority))
10248 (setq remove t))
10249 (setq news (format "%c" new))
10250 (if have
10251 (if remove
10252 (replace-match "" t t nil 1)
10253 (replace-match news t t nil 2))
10254 (if remove
10255 (error "No priority cookie found in line")
10256 (let ((case-fold-search nil))
10257 (looking-at org-todo-line-regexp))
10258 (if (match-end 2)
10259 (progn
10260 (goto-char (match-end 2))
10261 (insert " [#" news "]"))
10262 (goto-char (match-beginning 3))
10263 (insert "[#" news "] ")))))
10264 (org-preserve-lc (org-set-tags nil 'align))
10265 (if remove
10266 (message "Priority removed")
10267 (message "Priority of current item set to %s" news))))
10270 (defun org-get-priority (s)
10271 "Find priority cookie and return priority."
10272 (save-match-data
10273 (if (not (string-match org-priority-regexp s))
10274 (* 1000 (- org-lowest-priority org-default-priority))
10275 (* 1000 (- org-lowest-priority
10276 (string-to-char (match-string 2 s)))))))
10278 ;;;; Tags
10280 (defvar org-agenda-archives-mode)
10281 (defvar org-map-continue-from nil
10282 "Position from where mapping should continue.
10283 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10285 (defvar org-scanner-tags nil
10286 "The current tag list while the tags scanner is running.")
10287 (defvar org-trust-scanner-tags nil
10288 "Should `org-get-tags-at' use the tags fro the scanner.
10289 This is for internal dynamical scoping only.
10290 When this is non-nil, the function `org-get-tags-at' will return the value
10291 of `org-scanner-tags' instead of building the list by itself. This
10292 can lead to large speed-ups when the tags scanner is used in a file with
10293 many entries, and when the list of tags is retrieved, for example to
10294 obtain a list of properties. Building the tags list for each entry in such
10295 a file becomes an N^2 operation - but with this variable set, it scales
10296 as N.")
10298 (defun org-scan-tags (action matcher &optional todo-only)
10299 "Scan headline tags with inheritance and produce output ACTION.
10301 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10302 or `agenda' to produce an entry list for an agenda view. It can also be
10303 a Lisp form or a function that should be called at each matched headline, in
10304 this case the return value is a list of all return values from these calls.
10306 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10307 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10308 only lines with a TODO keyword are included in the output."
10309 (require 'org-agenda)
10310 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10311 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10312 (org-re
10313 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10314 (props (list 'face 'default
10315 'done-face 'org-agenda-done
10316 'undone-face 'default
10317 'mouse-face 'highlight
10318 'org-not-done-regexp org-not-done-regexp
10319 'org-todo-regexp org-todo-regexp
10320 'keymap org-agenda-keymap
10321 'help-echo
10322 (format "mouse-2 or RET jump to org file %s"
10323 (abbreviate-file-name
10324 (or (buffer-file-name (buffer-base-buffer))
10325 (buffer-name (buffer-base-buffer)))))))
10326 (case-fold-search nil)
10327 (org-map-continue-from nil)
10328 lspos tags tags-list
10329 (tags-alist (list (cons 0 org-file-tags)))
10330 (llast 0) rtn rtn1 level category i txt
10331 todo marker entry priority)
10332 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10333 (setq action (list 'lambda nil action)))
10334 (save-excursion
10335 (goto-char (point-min))
10336 (when (eq action 'sparse-tree)
10337 (org-overview)
10338 (org-remove-occur-highlights))
10339 (while (re-search-forward re nil t)
10340 (catch :skip
10341 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10342 tags (if (match-end 4) (org-match-string-no-properties 4)))
10343 (goto-char (setq lspos (match-beginning 0)))
10344 (setq level (org-reduced-level (funcall outline-level))
10345 category (org-get-category))
10346 (setq i llast llast level)
10347 ;; remove tag lists from same and sublevels
10348 (while (>= i level)
10349 (when (setq entry (assoc i tags-alist))
10350 (setq tags-alist (delete entry tags-alist)))
10351 (setq i (1- i)))
10352 ;; add the next tags
10353 (when tags
10354 (setq tags (org-split-string tags ":")
10355 tags-alist
10356 (cons (cons level tags) tags-alist)))
10357 ;; compile tags for current headline
10358 (setq tags-list
10359 (if org-use-tag-inheritance
10360 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10361 tags)
10362 org-scanner-tags tags-list)
10363 (when org-use-tag-inheritance
10364 (setcdr (car tags-alist)
10365 (mapcar (lambda (x)
10366 (setq x (copy-sequence x))
10367 (org-add-prop-inherited x))
10368 (cdar tags-alist))))
10369 (when (and tags org-use-tag-inheritance
10370 (or (not (eq t org-use-tag-inheritance))
10371 org-tags-exclude-from-inheritance))
10372 ;; selective inheritance, remove uninherited ones
10373 (setcdr (car tags-alist)
10374 (org-remove-uniherited-tags (cdar tags-alist))))
10375 (when (and (or (not todo-only)
10376 (and (member todo org-not-done-keywords)
10377 (or (not org-agenda-tags-todo-honor-ignore-options)
10378 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10379 (let ((case-fold-search t)) (eval matcher))
10381 (not (member org-archive-tag tags-list))
10382 ;; we have an archive tag, should we use this anyway?
10383 (or (not org-agenda-skip-archived-trees)
10384 (and (eq action 'agenda) org-agenda-archives-mode))))
10385 (unless (eq action 'sparse-tree) (org-agenda-skip))
10387 ;; select this headline
10389 (cond
10390 ((eq action 'sparse-tree)
10391 (and org-highlight-sparse-tree-matches
10392 (org-get-heading) (match-end 0)
10393 (org-highlight-new-match
10394 (match-beginning 0) (match-beginning 1)))
10395 (org-show-context 'tags-tree))
10396 ((eq action 'agenda)
10397 (setq txt (org-format-agenda-item
10399 (concat
10400 (if (eq org-tags-match-list-sublevels 'indented)
10401 (make-string (1- level) ?.) "")
10402 (org-get-heading))
10403 category
10404 tags-list
10406 priority (org-get-priority txt))
10407 (goto-char lspos)
10408 (setq marker (org-agenda-new-marker))
10409 (org-add-props txt props
10410 'org-marker marker 'org-hd-marker marker 'org-category category
10411 'todo-state todo
10412 'priority priority 'type "tagsmatch")
10413 (push txt rtn))
10414 ((functionp action)
10415 (setq org-map-continue-from nil)
10416 (save-excursion
10417 (setq rtn1 (funcall action))
10418 (push rtn1 rtn)))
10419 (t (error "Invalid action")))
10421 ;; if we are to skip sublevels, jump to end of subtree
10422 (unless org-tags-match-list-sublevels
10423 (org-end-of-subtree t)
10424 (backward-char 1))))
10425 ;; Get the correct position from where to continue
10426 (if org-map-continue-from
10427 (goto-char org-map-continue-from)
10428 (and (= (point) lspos) (end-of-line 1)))))
10429 (when (and (eq action 'sparse-tree)
10430 (not org-sparse-tree-open-archived-trees))
10431 (org-hide-archived-subtrees (point-min) (point-max)))
10432 (nreverse rtn)))
10434 (defun org-remove-uniherited-tags (tags)
10435 "Remove all tags that are not inherited from the list TAGS."
10436 (cond
10437 ((eq org-use-tag-inheritance t)
10438 (if org-tags-exclude-from-inheritance
10439 (org-delete-all org-tags-exclude-from-inheritance tags)
10440 tags))
10441 ((not org-use-tag-inheritance) nil)
10442 ((stringp org-use-tag-inheritance)
10443 (delq nil (mapcar
10444 (lambda (x)
10445 (if (and (string-match org-use-tag-inheritance x)
10446 (not (member x org-tags-exclude-from-inheritance)))
10447 x nil))
10448 tags)))
10449 ((listp org-use-tag-inheritance)
10450 (delq nil (mapcar
10451 (lambda (x)
10452 (if (member x org-use-tag-inheritance) x nil))
10453 tags)))))
10455 (defvar todo-only) ;; dynamically scoped
10457 (defun org-match-sparse-tree (&optional todo-only match)
10458 "Create a sparse tree according to tags string MATCH.
10459 MATCH can contain positive and negative selection of tags, like
10460 \"+WORK+URGENT-WITHBOSS\".
10461 If optional argument TODO-ONLY is non-nil, only select lines that are
10462 also TODO lines."
10463 (interactive "P")
10464 (org-prepare-agenda-buffers (list (current-buffer)))
10465 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10467 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10469 (defvar org-cached-props nil)
10470 (defun org-cached-entry-get (pom property)
10471 (if (or (eq t org-use-property-inheritance)
10472 (and (stringp org-use-property-inheritance)
10473 (string-match org-use-property-inheritance property))
10474 (and (listp org-use-property-inheritance)
10475 (member property org-use-property-inheritance)))
10476 ;; Caching is not possible, check it directly
10477 (org-entry-get pom property 'inherit)
10478 ;; Get all properties, so that we can do complicated checks easily
10479 (cdr (assoc property (or org-cached-props
10480 (setq org-cached-props
10481 (org-entry-properties pom)))))))
10483 (defun org-global-tags-completion-table (&optional files)
10484 "Return the list of all tags in all agenda buffer/files."
10485 (save-excursion
10486 (org-uniquify
10487 (delq nil
10488 (apply 'append
10489 (mapcar
10490 (lambda (file)
10491 (set-buffer (find-file-noselect file))
10492 (append (org-get-buffer-tags)
10493 (mapcar (lambda (x) (if (stringp (car-safe x))
10494 (list (car-safe x)) nil))
10495 org-tag-alist)))
10496 (if (and files (car files))
10497 files
10498 (org-agenda-files))))))))
10500 (defun org-make-tags-matcher (match)
10501 "Create the TAGS//TODO matcher form for the selection string MATCH."
10502 ;; todo-only is scoped dynamically into this function, and the function
10503 ;; may change it if the matcher asks for it.
10504 (unless match
10505 ;; Get a new match request, with completion
10506 (let ((org-last-tags-completion-table
10507 (org-global-tags-completion-table)))
10508 (setq match (org-completing-read-no-ido
10509 "Match: " 'org-tags-completion-function nil nil nil
10510 'org-tags-history))))
10512 ;; Parse the string and create a lisp form
10513 (let ((match0 match)
10514 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10515 minus tag mm
10516 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10517 orterms term orlist re-p str-p level-p level-op time-p
10518 prop-p pn pv po cat-p gv rest)
10519 (if (string-match "/+" match)
10520 ;; match contains also a todo-matching request
10521 (progn
10522 (setq tagsmatch (substring match 0 (match-beginning 0))
10523 todomatch (substring match (match-end 0)))
10524 (if (string-match "^!" todomatch)
10525 (setq todo-only t todomatch (substring todomatch 1)))
10526 (if (string-match "^\\s-*$" todomatch)
10527 (setq todomatch nil)))
10528 ;; only matching tags
10529 (setq tagsmatch match todomatch nil))
10531 ;; Make the tags matcher
10532 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10533 (setq tagsmatcher t)
10534 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10535 (while (setq term (pop orterms))
10536 (while (and (equal (substring term -1) "\\") orterms)
10537 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10538 (while (string-match re term)
10539 (setq rest (substring term (match-end 0))
10540 minus (and (match-end 1)
10541 (equal (match-string 1 term) "-"))
10542 tag (match-string 2 term)
10543 re-p (equal (string-to-char tag) ?{)
10544 level-p (match-end 4)
10545 prop-p (match-end 5)
10546 mm (cond
10547 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10548 (level-p
10549 (setq level-op (org-op-to-function (match-string 3 term)))
10550 `(,level-op level ,(string-to-number
10551 (match-string 4 term))))
10552 (prop-p
10553 (setq pn (match-string 5 term)
10554 po (match-string 6 term)
10555 pv (match-string 7 term)
10556 cat-p (equal pn "CATEGORY")
10557 re-p (equal (string-to-char pv) ?{)
10558 str-p (equal (string-to-char pv) ?\")
10559 time-p (save-match-data
10560 (string-match "^\"[[<].*[]>]\"$" pv))
10561 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10562 (if time-p (setq pv (org-matcher-time pv)))
10563 (setq po (org-op-to-function po (if time-p 'time str-p)))
10564 (cond
10565 ((equal pn "CATEGORY")
10566 (setq gv '(get-text-property (point) 'org-category)))
10567 ((equal pn "TODO")
10568 (setq gv 'todo))
10570 (setq gv `(org-cached-entry-get nil ,pn))))
10571 (if re-p
10572 (if (eq po 'org<>)
10573 `(not (string-match ,pv (or ,gv "")))
10574 `(string-match ,pv (or ,gv "")))
10575 (if str-p
10576 `(,po (or ,gv "") ,pv)
10577 `(,po (string-to-number (or ,gv ""))
10578 ,(string-to-number pv) ))))
10579 (t `(member ,tag tags-list)))
10580 mm (if minus (list 'not mm) mm)
10581 term rest)
10582 (push mm tagsmatcher))
10583 (push (if (> (length tagsmatcher) 1)
10584 (cons 'and tagsmatcher)
10585 (car tagsmatcher))
10586 orlist)
10587 (setq tagsmatcher nil))
10588 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10589 (setq tagsmatcher
10590 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10591 ;; Make the todo matcher
10592 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10593 (setq todomatcher t)
10594 (setq orterms (org-split-string todomatch "|") orlist nil)
10595 (while (setq term (pop orterms))
10596 (while (string-match re term)
10597 (setq minus (and (match-end 1)
10598 (equal (match-string 1 term) "-"))
10599 kwd (match-string 2 term)
10600 re-p (equal (string-to-char kwd) ?{)
10601 term (substring term (match-end 0))
10602 mm (if re-p
10603 `(string-match ,(substring kwd 1 -1) todo)
10604 (list 'equal 'todo kwd))
10605 mm (if minus (list 'not mm) mm))
10606 (push mm todomatcher))
10607 (push (if (> (length todomatcher) 1)
10608 (cons 'and todomatcher)
10609 (car todomatcher))
10610 orlist)
10611 (setq todomatcher nil))
10612 (setq todomatcher (if (> (length orlist) 1)
10613 (cons 'or orlist) (car orlist))))
10615 ;; Return the string and lisp forms of the matcher
10616 (setq matcher (if todomatcher
10617 (list 'and tagsmatcher todomatcher)
10618 tagsmatcher))
10619 (cons match0 matcher)))
10621 (defun org-op-to-function (op &optional stringp)
10622 "Turn an operator into the appropriate function."
10623 (setq op
10624 (cond
10625 ((equal op "<" ) '(< string< org-time<))
10626 ((equal op ">" ) '(> org-string> org-time>))
10627 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10628 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10629 ((member op '("=" "==")) '(= string= org-time=))
10630 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10631 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10633 (defun org<> (a b) (not (= a b)))
10634 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10635 (defun org-string>= (a b) (not (string< a b)))
10636 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10637 (defun org-string<> (a b) (not (string= a b)))
10638 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10639 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10640 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10641 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10642 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10643 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10644 (defun org-2ft (s)
10645 "Convert S to a floating point time.
10646 If S is already a number, just return it. If it is a string, parse
10647 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10648 (cond
10649 ((numberp s) s)
10650 ((stringp s)
10651 (condition-case nil
10652 (float-time (apply 'encode-time (org-parse-time-string s)))
10653 (error 0.)))
10654 (t 0.)))
10656 (defun org-time-today ()
10657 "Time in seconds today at 0:00.
10658 Returns the float number of seconds since the beginning of the
10659 epoch to the beginning of today (00:00)."
10660 (float-time (apply 'encode-time
10661 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10663 (defun org-matcher-time (s)
10664 "Interpret a time comparison value."
10665 (save-match-data
10666 (cond
10667 ((string= s "<now>") (float-time))
10668 ((string= s "<today>") (org-time-today))
10669 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10670 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10671 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10672 (+ (org-time-today)
10673 (* (string-to-number (match-string 1 s))
10674 (cdr (assoc (match-string 2 s)
10675 '(("d" . 86400.0) ("w" . 604800.0)
10676 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10677 (t (org-2ft s)))))
10679 (defun org-match-any-p (re list)
10680 "Does re match any element of list?"
10681 (setq list (mapcar (lambda (x) (string-match re x)) list))
10682 (delq nil list))
10684 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10685 (defvar org-tags-overlay (org-make-overlay 1 1))
10686 (org-detach-overlay org-tags-overlay)
10688 (defun org-get-local-tags-at (&optional pos)
10689 "Get a list of tags defined in the current headline."
10690 (org-get-tags-at pos 'local))
10692 (defun org-get-local-tags ()
10693 "Get a list of tags defined in the current headline."
10694 (org-get-tags-at nil 'local))
10696 (defun org-get-tags-at (&optional pos local)
10697 "Get a list of all headline tags applicable at POS.
10698 POS defaults to point. If tags are inherited, the list contains
10699 the targets in the same sequence as the headlines appear, i.e.
10700 the tags of the current headline come last.
10701 When LOCAL is non-nil, only return tags from the current headline,
10702 ignore inherited ones."
10703 (interactive)
10704 (if (and org-trust-scanner-tags
10705 (or (not pos) (equal pos (point)))
10706 (not local))
10707 org-scanner-tags
10708 (let (tags ltags lastpos parent)
10709 (save-excursion
10710 (save-restriction
10711 (widen)
10712 (goto-char (or pos (point)))
10713 (save-match-data
10714 (catch 'done
10715 (condition-case nil
10716 (progn
10717 (org-back-to-heading t)
10718 (while (not (equal lastpos (point)))
10719 (setq lastpos (point))
10720 (when (looking-at
10721 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10722 (setq ltags (org-split-string
10723 (org-match-string-no-properties 1) ":"))
10724 (when parent
10725 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10726 (setq tags (append
10727 (if parent
10728 (org-remove-uniherited-tags ltags)
10729 ltags)
10730 tags)))
10731 (or org-use-tag-inheritance (throw 'done t))
10732 (if local (throw 'done t))
10733 (or (org-up-heading-safe) (error nil))
10734 (setq parent t)))
10735 (error nil)))))
10736 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10738 (defun org-add-prop-inherited (s)
10739 (add-text-properties 0 (length s) '(inherited t) s)
10742 (defun org-toggle-tag (tag &optional onoff)
10743 "Toggle the tag TAG for the current line.
10744 If ONOFF is `on' or `off', don't toggle but set to this state."
10745 (let (res current)
10746 (save-excursion
10747 (org-back-to-heading t)
10748 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10749 (point-at-eol) t)
10750 (progn
10751 (setq current (match-string 1))
10752 (replace-match ""))
10753 (setq current ""))
10754 (setq current (nreverse (org-split-string current ":")))
10755 (cond
10756 ((eq onoff 'on)
10757 (setq res t)
10758 (or (member tag current) (push tag current)))
10759 ((eq onoff 'off)
10760 (or (not (member tag current)) (setq current (delete tag current))))
10761 (t (if (member tag current)
10762 (setq current (delete tag current))
10763 (setq res t)
10764 (push tag current))))
10765 (end-of-line 1)
10766 (if current
10767 (progn
10768 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10769 (org-set-tags nil t))
10770 (delete-horizontal-space))
10771 (run-hooks 'org-after-tags-change-hook))
10772 res))
10774 (defun org-align-tags-here (to-col)
10775 ;; Assumes that this is a headline
10776 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10777 (beginning-of-line 1)
10778 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10779 (< pos (match-beginning 2)))
10780 (progn
10781 (setq tags-l (- (match-end 2) (match-beginning 2)))
10782 (goto-char (match-beginning 1))
10783 (insert " ")
10784 (delete-region (point) (1+ (match-beginning 2)))
10785 (setq ncol (max (1+ (current-column))
10786 (1+ col)
10787 (if (> to-col 0)
10788 to-col
10789 (- (abs to-col) tags-l))))
10790 (setq p (point))
10791 (insert (make-string (- ncol (current-column)) ?\ ))
10792 (setq ncol (current-column))
10793 (when indent-tabs-mode (tabify p (point-at-eol)))
10794 (org-move-to-column (min ncol col) t))
10795 (goto-char pos))))
10797 (defun org-set-tags-command (&optional arg just-align)
10798 "Call the set-tags command for the current entry."
10799 (interactive "P")
10800 (if (org-on-heading-p)
10801 (org-set-tags arg just-align)
10802 (save-excursion
10803 (org-back-to-heading t)
10804 (org-set-tags arg just-align))))
10806 (defun org-set-tags (&optional arg just-align)
10807 "Set the tags for the current headline.
10808 With prefix ARG, realign all tags in headings in the current buffer."
10809 (interactive "P")
10810 (let* ((re (concat "^" outline-regexp))
10811 (current (org-get-tags-string))
10812 (col (current-column))
10813 (org-setting-tags t)
10814 table current-tags inherited-tags ; computed below when needed
10815 tags p0 c0 c1 rpl)
10816 (if arg
10817 (save-excursion
10818 (goto-char (point-min))
10819 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10820 (while (re-search-forward re nil t)
10821 (org-set-tags nil t)
10822 (end-of-line 1)))
10823 (message "All tags realigned to column %d" org-tags-column))
10824 (if just-align
10825 (setq tags current)
10826 ;; Get a new set of tags from the user
10827 (save-excursion
10828 (setq table (append org-tag-persistent-alist
10829 (or org-tag-alist (org-get-buffer-tags)))
10830 org-last-tags-completion-table table
10831 current-tags (org-split-string current ":")
10832 inherited-tags (nreverse
10833 (nthcdr (length current-tags)
10834 (nreverse (org-get-tags-at))))
10835 tags
10836 (if (or (eq t org-use-fast-tag-selection)
10837 (and org-use-fast-tag-selection
10838 (delq nil (mapcar 'cdr table))))
10839 (org-fast-tag-selection
10840 current-tags inherited-tags table
10841 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10842 (let ((org-add-colon-after-tag-completion t))
10843 (org-trim
10844 (org-without-partial-completion
10845 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10846 nil nil current 'org-tags-history)))))))
10847 (while (string-match "[-+&]+" tags)
10848 ;; No boolean logic, just a list
10849 (setq tags (replace-match ":" t t tags))))
10851 (if org-tags-sort-function
10852 (setq tags (mapconcat 'identity
10853 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
10854 org-tags-sort-function) ":")))
10856 (if (string-match "\\`[\t ]*\\'" tags)
10857 (setq tags "")
10858 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10859 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10861 ;; Insert new tags at the correct column
10862 (beginning-of-line 1)
10863 (cond
10864 ((and (equal current "") (equal tags "")))
10865 ((re-search-forward
10866 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10867 (point-at-eol) t)
10868 (if (equal tags "")
10869 (setq rpl "")
10870 (goto-char (match-beginning 0))
10871 (setq c0 (current-column) p0 (point)
10872 c1 (max (1+ c0) (if (> org-tags-column 0)
10873 org-tags-column
10874 (- (- org-tags-column) (length tags))))
10875 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10876 (replace-match rpl t t)
10877 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10878 tags)
10879 (t (error "Tags alignment failed")))
10880 (org-move-to-column col)
10881 (unless just-align
10882 (run-hooks 'org-after-tags-change-hook)))))
10884 (defun org-change-tag-in-region (beg end tag off)
10885 "Add or remove TAG for each entry in the region.
10886 This works in the agenda, and also in an org-mode buffer."
10887 (interactive
10888 (list (region-beginning) (region-end)
10889 (let ((org-last-tags-completion-table
10890 (if (org-mode-p)
10891 (org-get-buffer-tags)
10892 (org-global-tags-completion-table))))
10893 (org-ido-completing-read
10894 "Tag: " 'org-tags-completion-function nil nil nil
10895 'org-tags-history))
10896 (progn
10897 (message "[s]et or [r]emove? ")
10898 (equal (read-char-exclusive) ?r))))
10899 (if (fboundp 'deactivate-mark) (deactivate-mark))
10900 (let ((agendap (equal major-mode 'org-agenda-mode))
10901 l1 l2 m buf pos newhead (cnt 0))
10902 (goto-char end)
10903 (setq l2 (1- (org-current-line)))
10904 (goto-char beg)
10905 (setq l1 (org-current-line))
10906 (loop for l from l1 to l2 do
10907 (goto-line l)
10908 (setq m (get-text-property (point) 'org-hd-marker))
10909 (when (or (and (org-mode-p) (org-on-heading-p))
10910 (and agendap m))
10911 (setq buf (if agendap (marker-buffer m) (current-buffer))
10912 pos (if agendap m (point)))
10913 (with-current-buffer buf
10914 (save-excursion
10915 (save-restriction
10916 (goto-char pos)
10917 (setq cnt (1+ cnt))
10918 (org-toggle-tag tag (if off 'off 'on))
10919 (setq newhead (org-get-heading)))))
10920 (and agendap (org-agenda-change-all-lines newhead m))))
10921 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10923 (defun org-tags-completion-function (string predicate &optional flag)
10924 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10925 (confirm (lambda (x) (stringp (car x)))))
10926 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10927 (setq s1 (match-string 1 string)
10928 s2 (match-string 2 string))
10929 (setq s1 "" s2 string))
10930 (cond
10931 ((eq flag nil)
10932 ;; try completion
10933 (setq rtn (try-completion s2 ctable confirm))
10934 (if (stringp rtn)
10935 (setq rtn
10936 (concat s1 s2 (substring rtn (length s2))
10937 (if (and org-add-colon-after-tag-completion
10938 (assoc rtn ctable))
10939 ":" ""))))
10940 rtn)
10941 ((eq flag t)
10942 ;; all-completions
10943 (all-completions s2 ctable confirm)
10945 ((eq flag 'lambda)
10946 ;; exact match?
10947 (assoc s2 ctable)))
10950 (defun org-fast-tag-insert (kwd tags face &optional end)
10951 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10952 (insert (format "%-12s" (concat kwd ":"))
10953 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10954 (or end "")))
10956 (defun org-fast-tag-show-exit (flag)
10957 (save-excursion
10958 (goto-line 3)
10959 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10960 (replace-match ""))
10961 (when flag
10962 (end-of-line 1)
10963 (org-move-to-column (- (window-width) 19) t)
10964 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10966 (defun org-set-current-tags-overlay (current prefix)
10967 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10968 (if (featurep 'xemacs)
10969 (org-overlay-display org-tags-overlay (concat prefix s)
10970 'secondary-selection)
10971 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10972 (org-overlay-display org-tags-overlay (concat prefix s)))))
10974 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10975 "Fast tag selection with single keys.
10976 CURRENT is the current list of tags in the headline, INHERITED is the
10977 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10978 possibly with grouping information. TODO-TABLE is a similar table with
10979 TODO keywords, should these have keys assigned to them.
10980 If the keys are nil, a-z are automatically assigned.
10981 Returns the new tags string, or nil to not change the current settings."
10982 (let* ((fulltable (append table todo-table))
10983 (maxlen (apply 'max (mapcar
10984 (lambda (x)
10985 (if (stringp (car x)) (string-width (car x)) 0))
10986 fulltable)))
10987 (buf (current-buffer))
10988 (expert (eq org-fast-tag-selection-single-key 'expert))
10989 (buffer-tags nil)
10990 (fwidth (+ maxlen 3 1 3))
10991 (ncol (/ (- (window-width) 4) fwidth))
10992 (i-face 'org-done)
10993 (c-face 'org-todo)
10994 tg cnt e c char c1 c2 ntable tbl rtn
10995 ov-start ov-end ov-prefix
10996 (exit-after-next org-fast-tag-selection-single-key)
10997 (done-keywords org-done-keywords)
10998 groups ingroup)
10999 (save-excursion
11000 (beginning-of-line 1)
11001 (if (looking-at
11002 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11003 (setq ov-start (match-beginning 1)
11004 ov-end (match-end 1)
11005 ov-prefix "")
11006 (setq ov-start (1- (point-at-eol))
11007 ov-end (1+ ov-start))
11008 (skip-chars-forward "^\n\r")
11009 (setq ov-prefix
11010 (concat
11011 (buffer-substring (1- (point)) (point))
11012 (if (> (current-column) org-tags-column)
11014 (make-string (- org-tags-column (current-column)) ?\ ))))))
11015 (org-move-overlay org-tags-overlay ov-start ov-end)
11016 (save-window-excursion
11017 (if expert
11018 (set-buffer (get-buffer-create " *Org tags*"))
11019 (delete-other-windows)
11020 (split-window-vertically)
11021 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11022 (erase-buffer)
11023 (org-set-local 'org-done-keywords done-keywords)
11024 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11025 (org-fast-tag-insert "Current" current c-face "\n\n")
11026 (org-fast-tag-show-exit exit-after-next)
11027 (org-set-current-tags-overlay current ov-prefix)
11028 (setq tbl fulltable char ?a cnt 0)
11029 (while (setq e (pop tbl))
11030 (cond
11031 ((equal e '(:startgroup))
11032 (push '() groups) (setq ingroup t)
11033 (when (not (= cnt 0))
11034 (setq cnt 0)
11035 (insert "\n"))
11036 (insert "{ "))
11037 ((equal e '(:endgroup))
11038 (setq ingroup nil cnt 0)
11039 (insert "}\n"))
11040 ((equal e '(:newline))
11041 (when (not (= cnt 0))
11042 (setq cnt 0)
11043 (insert "\n")
11044 (setq e (car tbl))
11045 (while (equal (car tbl) '(:newline))
11046 (insert "\n")
11047 (setq tbl (cdr tbl)))))
11049 (setq tg (car e) c2 nil)
11050 (if (cdr e)
11051 (setq c (cdr e))
11052 ;; automatically assign a character.
11053 (setq c1 (string-to-char
11054 (downcase (substring
11055 tg (if (= (string-to-char tg) ?@) 1 0)))))
11056 (if (or (rassoc c1 ntable) (rassoc c1 table))
11057 (while (or (rassoc char ntable) (rassoc char table))
11058 (setq char (1+ char)))
11059 (setq c2 c1))
11060 (setq c (or c2 char)))
11061 (if ingroup (push tg (car groups)))
11062 (setq tg (org-add-props tg nil 'face
11063 (cond
11064 ((not (assoc tg table))
11065 (org-get-todo-face tg))
11066 ((member tg current) c-face)
11067 ((member tg inherited) i-face)
11068 (t nil))))
11069 (if (and (= cnt 0) (not ingroup)) (insert " "))
11070 (insert "[" c "] " tg (make-string
11071 (- fwidth 4 (length tg)) ?\ ))
11072 (push (cons tg c) ntable)
11073 (when (= (setq cnt (1+ cnt)) ncol)
11074 (insert "\n")
11075 (if ingroup (insert " "))
11076 (setq cnt 0)))))
11077 (setq ntable (nreverse ntable))
11078 (insert "\n")
11079 (goto-char (point-min))
11080 (if (not expert) (org-fit-window-to-buffer))
11081 (setq rtn
11082 (catch 'exit
11083 (while t
11084 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11085 (if groups " [!] no groups" " [!]groups")
11086 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11087 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11088 (cond
11089 ((= c ?\r) (throw 'exit t))
11090 ((= c ?!)
11091 (setq groups (not groups))
11092 (goto-char (point-min))
11093 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11094 ((= c ?\C-c)
11095 (if (not expert)
11096 (org-fast-tag-show-exit
11097 (setq exit-after-next (not exit-after-next)))
11098 (setq expert nil)
11099 (delete-other-windows)
11100 (split-window-vertically)
11101 (org-switch-to-buffer-other-window " *Org tags*")
11102 (org-fit-window-to-buffer)))
11103 ((or (= c ?\C-g)
11104 (and (= c ?q) (not (rassoc c ntable))))
11105 (org-detach-overlay org-tags-overlay)
11106 (setq quit-flag t))
11107 ((= c ?\ )
11108 (setq current nil)
11109 (if exit-after-next (setq exit-after-next 'now)))
11110 ((= c ?\t)
11111 (condition-case nil
11112 (setq tg (org-ido-completing-read
11113 "Tag: "
11114 (or buffer-tags
11115 (with-current-buffer buf
11116 (org-get-buffer-tags)))))
11117 (quit (setq tg "")))
11118 (when (string-match "\\S-" tg)
11119 (add-to-list 'buffer-tags (list tg))
11120 (if (member tg current)
11121 (setq current (delete tg current))
11122 (push tg current)))
11123 (if exit-after-next (setq exit-after-next 'now)))
11124 ((setq e (rassoc c todo-table) tg (car e))
11125 (with-current-buffer buf
11126 (save-excursion (org-todo tg)))
11127 (if exit-after-next (setq exit-after-next 'now)))
11128 ((setq e (rassoc c ntable) tg (car e))
11129 (if (member tg current)
11130 (setq current (delete tg current))
11131 (loop for g in groups do
11132 (if (member tg g)
11133 (mapc (lambda (x)
11134 (setq current (delete x current)))
11135 g)))
11136 (push tg current))
11137 (if exit-after-next (setq exit-after-next 'now))))
11139 ;; Create a sorted list
11140 (setq current
11141 (sort current
11142 (lambda (a b)
11143 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11144 (if (eq exit-after-next 'now) (throw 'exit t))
11145 (goto-char (point-min))
11146 (beginning-of-line 2)
11147 (delete-region (point) (point-at-eol))
11148 (org-fast-tag-insert "Current" current c-face)
11149 (org-set-current-tags-overlay current ov-prefix)
11150 (while (re-search-forward
11151 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11152 (setq tg (match-string 1))
11153 (add-text-properties
11154 (match-beginning 1) (match-end 1)
11155 (list 'face
11156 (cond
11157 ((member tg current) c-face)
11158 ((member tg inherited) i-face)
11159 (t (get-text-property (match-beginning 1) 'face))))))
11160 (goto-char (point-min)))))
11161 (org-detach-overlay org-tags-overlay)
11162 (if rtn
11163 (mapconcat 'identity current ":")
11164 nil))))
11166 (defun org-get-tags-string ()
11167 "Get the TAGS string in the current headline."
11168 (unless (org-on-heading-p t)
11169 (error "Not on a heading"))
11170 (save-excursion
11171 (beginning-of-line 1)
11172 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11173 (org-match-string-no-properties 1)
11174 "")))
11176 (defun org-get-tags ()
11177 "Get the list of tags specified in the current headline."
11178 (org-split-string (org-get-tags-string) ":"))
11180 (defun org-get-buffer-tags ()
11181 "Get a table of all tags used in the buffer, for completion."
11182 (let (tags)
11183 (save-excursion
11184 (goto-char (point-min))
11185 (while (re-search-forward
11186 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11187 (when (equal (char-after (point-at-bol 0)) ?*)
11188 (mapc (lambda (x) (add-to-list 'tags x))
11189 (org-split-string (org-match-string-no-properties 1) ":")))))
11190 (mapcar 'list tags)))
11192 ;;;; The mapping API
11194 ;;;###autoload
11195 (defun org-map-entries (func &optional match scope &rest skip)
11196 "Call FUNC at each headline selected by MATCH in SCOPE.
11198 FUNC is a function or a lisp form. The function will be called without
11199 arguments, with the cursor positioned at the beginning of the headline.
11200 The return values of all calls to the function will be collected and
11201 returned as a list.
11203 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11204 does not need to preserve point. After evaluation, the cursor will be
11205 moved to the end of the line (presumably of the headline of the
11206 processed entry) and search continues from there. Under some
11207 circumstances, this may not produce the wanted results. For example,
11208 if you have removed (e.g. archived) the current (sub)tree it could
11209 mean that the next entry will be skipped entirely. In such cases, you
11210 can specify the position from where search should continue by making
11211 FUNC set the variable `org-map-continue-from' to the desired buffer
11212 position.
11214 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11215 Only headlines that are matched by this query will be considered during
11216 the iteration. When MATCH is nil or t, all headlines will be
11217 visited by the iteration.
11219 SCOPE determines the scope of this command. It can be any of:
11221 nil The current buffer, respecting the restriction if any
11222 tree The subtree started with the entry at point
11223 file The current buffer, without restriction
11224 file-with-archives
11225 The current buffer, and any archives associated with it
11226 agenda All agenda files
11227 agenda-with-archives
11228 All agenda files with any archive files associated with them
11229 \(file1 file2 ...)
11230 If this is a list, all files in the list will be scanned
11232 The remaining args are treated as settings for the skipping facilities of
11233 the scanner. The following items can be given here:
11235 archive skip trees with the archive tag.
11236 comment skip trees with the COMMENT keyword
11237 function or Emacs Lisp form:
11238 will be used as value for `org-agenda-skip-function', so whenever
11239 the the function returns t, FUNC will not be called for that
11240 entry and search will continue from the point where the
11241 function leaves it.
11243 If your function needs to retrieve the tags including inherited tags
11244 at the *current* entry, you can use the value of the variable
11245 `org-scanner-tags' which will be much faster than getting the value
11246 with `org-get-tags-at'. If your function gets properties with
11247 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11248 to t around the call to `org-entry-properties' to get the same speedup.
11249 Note that if your function moves around to retrieve tags and properties at
11250 a *different* entry, you cannot use these techniques."
11251 (let* ((org-agenda-archives-mode nil) ; just to make sure
11252 (org-agenda-skip-archived-trees (memq 'archive skip))
11253 (org-agenda-skip-comment-trees (memq 'comment skip))
11254 (org-agenda-skip-function
11255 (car (org-delete-all '(comment archive) skip)))
11256 (org-tags-match-list-sublevels t)
11257 matcher file res
11258 org-todo-keywords-for-agenda
11259 org-done-keywords-for-agenda
11260 org-todo-keyword-alist-for-agenda
11261 org-tag-alist-for-agenda)
11263 (cond
11264 ((eq match t) (setq matcher t))
11265 ((eq match nil) (setq matcher t))
11266 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11268 (save-excursion
11269 (save-restriction
11270 (when (eq scope 'tree)
11271 (org-back-to-heading t)
11272 (org-narrow-to-subtree)
11273 (setq scope nil))
11275 (if (not scope)
11276 (progn
11277 (org-prepare-agenda-buffers
11278 (list (buffer-file-name (current-buffer))))
11279 (setq res (org-scan-tags func matcher)))
11280 ;; Get the right scope
11281 (cond
11282 ((and scope (listp scope) (symbolp (car scope)))
11283 (setq scope (eval scope)))
11284 ((eq scope 'agenda)
11285 (setq scope (org-agenda-files t)))
11286 ((eq scope 'agenda-with-archives)
11287 (setq scope (org-agenda-files t))
11288 (setq scope (org-add-archive-files scope)))
11289 ((eq scope 'file)
11290 (setq scope (list (buffer-file-name))))
11291 ((eq scope 'file-with-archives)
11292 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11293 (org-prepare-agenda-buffers scope)
11294 (while (setq file (pop scope))
11295 (with-current-buffer (org-find-base-buffer-visiting file)
11296 (save-excursion
11297 (save-restriction
11298 (widen)
11299 (goto-char (point-min))
11300 (setq res (append res (org-scan-tags func matcher))))))))))
11301 res))
11303 ;;;; Properties
11305 ;;; Setting and retrieving properties
11307 (defconst org-special-properties
11308 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11309 "TIMESTAMP" "TIMESTAMP_IA")
11310 "The special properties valid in Org-mode.
11312 These are properties that are not defined in the property drawer,
11313 but in some other way.")
11315 (defconst org-default-properties
11316 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11317 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11318 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11319 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11320 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11321 "CLOCK_MODELINE_TOTAL")
11322 "Some properties that are used by Org-mode for various purposes.
11323 Being in this list makes sure that they are offered for completion.")
11325 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11326 "Regular expression matching the first line of a property drawer.")
11328 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11329 "Regular expression matching the first line of a property drawer.")
11331 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11332 "Regular expression matching the first line of a property drawer.")
11334 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11335 "Regular expression matching the first line of a property drawer.")
11337 (defconst org-property-drawer-re
11338 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11339 org-property-end-re "\\)\n?")
11340 "Matches an entire property drawer.")
11342 (defconst org-clock-drawer-re
11343 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11344 org-property-end-re "\\)\n?")
11345 "Matches an entire clock drawer.")
11347 (defun org-property-action ()
11348 "Do an action on properties."
11349 (interactive)
11350 (let (c)
11351 (org-at-property-p)
11352 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11353 (setq c (read-char-exclusive))
11354 (cond
11355 ((equal c ?s)
11356 (call-interactively 'org-set-property))
11357 ((equal c ?d)
11358 (call-interactively 'org-delete-property))
11359 ((equal c ?D)
11360 (call-interactively 'org-delete-property-globally))
11361 ((equal c ?c)
11362 (call-interactively 'org-compute-property-at-point))
11363 (t (error "No such property action %c" c)))))
11365 (defun org-at-property-p ()
11366 "Is the cursor in a property line?"
11367 ;; FIXME: Does not check if we are actually in the drawer.
11368 ;; FIXME: also returns true on any drawers.....
11369 ;; This is used by C-c C-c for property action.
11370 (save-excursion
11371 (beginning-of-line 1)
11372 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11374 (defun org-get-property-block (&optional beg end force)
11375 "Return the (beg . end) range of the body of the property drawer.
11376 BEG and END can be beginning and end of subtree, if not given
11377 they will be found.
11378 If the drawer does not exist and FORCE is non-nil, create the drawer."
11379 (catch 'exit
11380 (save-excursion
11381 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11382 (end (or end (progn (outline-next-heading) (point)))))
11383 (goto-char beg)
11384 (if (re-search-forward org-property-start-re end t)
11385 (setq beg (1+ (match-end 0)))
11386 (if force
11387 (save-excursion
11388 (org-insert-property-drawer)
11389 (setq end (progn (outline-next-heading) (point))))
11390 (throw 'exit nil))
11391 (goto-char beg)
11392 (if (re-search-forward org-property-start-re end t)
11393 (setq beg (1+ (match-end 0)))))
11394 (if (re-search-forward org-property-end-re end t)
11395 (setq end (match-beginning 0))
11396 (or force (throw 'exit nil))
11397 (goto-char beg)
11398 (setq end beg)
11399 (org-indent-line-function)
11400 (insert ":END:\n"))
11401 (cons beg end)))))
11403 (defun org-entry-properties (&optional pom which)
11404 "Get all properties of the entry at point-or-marker POM.
11405 This includes the TODO keyword, the tags, time strings for deadline,
11406 scheduled, and clocking, and any additional properties defined in the
11407 entry. The return value is an alist, keys may occur multiple times
11408 if the property key was used several times.
11409 POM may also be nil, in which case the current entry is used.
11410 If WHICH is nil or `all', get all properties. If WHICH is
11411 `special' or `standard', only get that subclass."
11412 (setq which (or which 'all))
11413 (org-with-point-at pom
11414 (let ((clockstr (substring org-clock-string 0 -1))
11415 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11416 beg end range props sum-props key value string clocksum)
11417 (save-excursion
11418 (when (condition-case nil
11419 (and (org-mode-p) (org-back-to-heading t))
11420 (error nil))
11421 (setq beg (point))
11422 (setq sum-props (get-text-property (point) 'org-summaries))
11423 (setq clocksum (get-text-property (point) :org-clock-minutes))
11424 (outline-next-heading)
11425 (setq end (point))
11426 (when (memq which '(all special))
11427 ;; Get the special properties, like TODO and tags
11428 (goto-char beg)
11429 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11430 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11431 (when (looking-at org-priority-regexp)
11432 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11433 (when (and (setq value (org-get-tags-string))
11434 (string-match "\\S-" value))
11435 (push (cons "TAGS" value) props))
11436 (when (setq value (org-get-tags-at))
11437 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11438 props))
11439 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11440 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11441 string (if (equal key clockstr)
11442 (org-no-properties
11443 (org-trim
11444 (buffer-substring
11445 (match-beginning 3) (goto-char (point-at-eol)))))
11446 (substring (org-match-string-no-properties 3) 1 -1)))
11447 (unless key
11448 (if (= (char-after (match-beginning 3)) ?\[)
11449 (setq key "TIMESTAMP_IA")
11450 (setq key "TIMESTAMP")))
11451 (when (or (equal key clockstr) (not (assoc key props)))
11452 (push (cons key string) props)))
11456 (when (memq which '(all standard))
11457 ;; Get the standard properties, like :PROP: ...
11458 (setq range (org-get-property-block beg end))
11459 (when range
11460 (goto-char (car range))
11461 (while (re-search-forward
11462 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11463 (cdr range) t)
11464 (setq key (org-match-string-no-properties 1)
11465 value (org-trim (or (org-match-string-no-properties 2) "")))
11466 (unless (member key excluded)
11467 (push (cons key (or value "")) props)))))
11468 (if clocksum
11469 (push (cons "CLOCKSUM"
11470 (org-columns-number-to-string (/ (float clocksum) 60.)
11471 'add_times))
11472 props))
11473 (unless (assoc "CATEGORY" props)
11474 (setq value (or (org-get-category)
11475 (progn (org-refresh-category-properties)
11476 (org-get-category))))
11477 (push (cons "CATEGORY" value) props))
11478 (append sum-props (nreverse props)))))))
11480 (defun org-entry-get (pom property &optional inherit)
11481 "Get value of PROPERTY for entry at point-or-marker POM.
11482 If INHERIT is non-nil and the entry does not have the property,
11483 then also check higher levels of the hierarchy.
11484 If INHERIT is the symbol `selective', use inheritance only if the setting
11485 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11486 If the property is present but empty, the return value is the empty string.
11487 If the property is not present at all, nil is returned."
11488 (org-with-point-at pom
11489 (if (and inherit (if (eq inherit 'selective)
11490 (org-property-inherit-p property)
11492 (org-entry-get-with-inheritance property)
11493 (if (member property org-special-properties)
11494 ;; We need a special property. Use brute force, get all properties.
11495 (cdr (assoc property (org-entry-properties nil 'special)))
11496 (let ((range (org-get-property-block)))
11497 (if (and range
11498 (goto-char (car range))
11499 (re-search-forward
11500 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11501 (cdr range) t))
11502 ;; Found the property, return it.
11503 (if (match-end 1)
11504 (org-match-string-no-properties 1)
11505 "")))))))
11507 (defun org-property-or-variable-value (var &optional inherit)
11508 "Check if there is a property fixing the value of VAR.
11509 If yes, return this value. If not, return the current value of the variable."
11510 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11511 (if (and prop (stringp prop) (string-match "\\S-" prop))
11512 (read prop)
11513 (symbol-value var))))
11515 (defun org-entry-delete (pom property)
11516 "Delete the property PROPERTY from entry at point-or-marker POM."
11517 (org-with-point-at pom
11518 (if (member property org-special-properties)
11519 nil ; cannot delete these properties.
11520 (let ((range (org-get-property-block)))
11521 (if (and range
11522 (goto-char (car range))
11523 (re-search-forward
11524 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11525 (cdr range) t))
11526 (progn
11527 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11529 nil)))))
11531 ;; Multi-values properties are properties that contain multiple values
11532 ;; These values are assumed to be single words, separated by whitespace.
11533 (defun org-entry-add-to-multivalued-property (pom property value)
11534 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11535 (let* ((old (org-entry-get pom property))
11536 (values (and old (org-split-string old "[ \t]"))))
11537 (setq value (org-entry-protect-space value))
11538 (unless (member value values)
11539 (setq values (cons value values))
11540 (org-entry-put pom property
11541 (mapconcat 'identity values " ")))))
11543 (defun org-entry-remove-from-multivalued-property (pom property value)
11544 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11545 (let* ((old (org-entry-get pom property))
11546 (values (and old (org-split-string old "[ \t]"))))
11547 (setq value (org-entry-protect-space value))
11548 (when (member value values)
11549 (setq values (delete value values))
11550 (org-entry-put pom property
11551 (mapconcat 'identity values " ")))))
11553 (defun org-entry-member-in-multivalued-property (pom property value)
11554 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11555 (let* ((old (org-entry-get pom property))
11556 (values (and old (org-split-string old "[ \t]"))))
11557 (setq value (org-entry-protect-space value))
11558 (member value values)))
11560 (defun org-entry-get-multivalued-property (pom property)
11561 "Return a list of values in a multivalued property."
11562 (let* ((value (org-entry-get pom property))
11563 (values (and value (org-split-string value "[ \t]"))))
11564 (mapcar 'org-entry-restore-space values)))
11566 (defun org-entry-put-multivalued-property (pom property &rest values)
11567 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11568 VALUES should be a list of strings. Spaces will be protected."
11569 (org-entry-put pom property
11570 (mapconcat 'org-entry-protect-space values " "))
11571 (let* ((value (org-entry-get pom property))
11572 (values (and value (org-split-string value "[ \t]"))))
11573 (mapcar 'org-entry-restore-space values)))
11575 (defun org-entry-protect-space (s)
11576 "Protect spaces and newline in string S."
11577 (while (string-match " " s)
11578 (setq s (replace-match "%20" t t s)))
11579 (while (string-match "\n" s)
11580 (setq s (replace-match "%0A" t t s)))
11583 (defun org-entry-restore-space (s)
11584 "Restore spaces and newline in string S."
11585 (while (string-match "%20" s)
11586 (setq s (replace-match " " t t s)))
11587 (while (string-match "%0A" s)
11588 (setq s (replace-match "\n" t t s)))
11591 (defvar org-entry-property-inherited-from (make-marker)
11592 "Marker pointing to the entry from where a property was inherited.
11593 Each call to `org-entry-get-with-inheritance' will set this marker to the
11594 location of the entry where the inheritance search matched. If there was
11595 no match, the marker will point nowhere.
11596 Note that also `org-entry-get' calls this function, if the INHERIT flag
11597 is set.")
11599 (defun org-entry-get-with-inheritance (property)
11600 "Get entry property, and search higher levels if not present."
11601 (move-marker org-entry-property-inherited-from nil)
11602 (let (tmp)
11603 (save-excursion
11604 (save-restriction
11605 (widen)
11606 (catch 'ex
11607 (while t
11608 (when (setq tmp (org-entry-get nil property))
11609 (org-back-to-heading t)
11610 (move-marker org-entry-property-inherited-from (point))
11611 (throw 'ex tmp))
11612 (or (org-up-heading-safe) (throw 'ex nil)))))
11613 (or tmp
11614 (cdr (assoc property org-file-properties))
11615 (cdr (assoc property org-global-properties))
11616 (cdr (assoc property org-global-properties-fixed))))))
11618 (defun org-entry-put (pom property value)
11619 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11620 (org-with-point-at pom
11621 (org-back-to-heading t)
11622 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11623 range)
11624 (cond
11625 ((equal property "TODO")
11626 (when (and (stringp value) (string-match "\\S-" value)
11627 (not (member value org-todo-keywords-1)))
11628 (error "\"%s\" is not a valid TODO state" value))
11629 (if (or (not value)
11630 (not (string-match "\\S-" value)))
11631 (setq value 'none))
11632 (org-todo value)
11633 (org-set-tags nil 'align))
11634 ((equal property "PRIORITY")
11635 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11636 (string-to-char value) ?\ ))
11637 (org-set-tags nil 'align))
11638 ((equal property "SCHEDULED")
11639 (if (re-search-forward org-scheduled-time-regexp end t)
11640 (cond
11641 ((eq value 'earlier) (org-timestamp-change -1 'day))
11642 ((eq value 'later) (org-timestamp-change 1 'day))
11643 (t (call-interactively 'org-schedule)))
11644 (call-interactively 'org-schedule)))
11645 ((equal property "DEADLINE")
11646 (if (re-search-forward org-deadline-time-regexp end t)
11647 (cond
11648 ((eq value 'earlier) (org-timestamp-change -1 'day))
11649 ((eq value 'later) (org-timestamp-change 1 'day))
11650 (t (call-interactively 'org-deadline)))
11651 (call-interactively 'org-deadline)))
11652 ((member property org-special-properties)
11653 (error "The %s property can not yet be set with `org-entry-put'"
11654 property))
11655 (t ; a non-special property
11656 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11657 (setq range (org-get-property-block beg end 'force))
11658 (goto-char (car range))
11659 (if (re-search-forward
11660 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11661 (progn
11662 (delete-region (match-beginning 1) (match-end 1))
11663 (goto-char (match-beginning 1)))
11664 (goto-char (cdr range))
11665 (insert "\n")
11666 (backward-char 1)
11667 (org-indent-line-function)
11668 (insert ":" property ":"))
11669 (and value (insert " " value))
11670 (org-indent-line-function)))))))
11672 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11673 "Get all property keys in the current buffer.
11674 With INCLUDE-SPECIALS, also list the special properties that reflect things
11675 like tags and TODO state.
11676 With INCLUDE-DEFAULTS, also include properties that has special meaning
11677 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11678 With INCLUDE-COLUMNS, also include property names given in COLUMN
11679 formats in the current buffer."
11680 (let (rtn range cfmt s p)
11681 (save-excursion
11682 (save-restriction
11683 (widen)
11684 (goto-char (point-min))
11685 (while (re-search-forward org-property-start-re nil t)
11686 (setq range (org-get-property-block))
11687 (goto-char (car range))
11688 (while (re-search-forward
11689 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11690 (cdr range) t)
11691 (add-to-list 'rtn (org-match-string-no-properties 1)))
11692 (outline-next-heading))))
11694 (when include-specials
11695 (setq rtn (append org-special-properties rtn)))
11697 (when include-defaults
11698 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
11699 (add-to-list 'rtn org-effort-property))
11701 (when include-columns
11702 (save-excursion
11703 (save-restriction
11704 (widen)
11705 (goto-char (point-min))
11706 (while (re-search-forward
11707 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11708 nil t)
11709 (setq cfmt (match-string 2) s 0)
11710 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11711 cfmt s)
11712 (setq s (match-end 0)
11713 p (match-string 1 cfmt))
11714 (unless (or (equal p "ITEM")
11715 (member p org-special-properties))
11716 (add-to-list 'rtn (match-string 1 cfmt))))))))
11718 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11720 (defun org-property-values (key)
11721 "Return a list of all values of property KEY."
11722 (save-excursion
11723 (save-restriction
11724 (widen)
11725 (goto-char (point-min))
11726 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11727 values)
11728 (while (re-search-forward re nil t)
11729 (add-to-list 'values (org-trim (match-string 1))))
11730 (delete "" values)))))
11732 (defun org-insert-property-drawer ()
11733 "Insert a property drawer into the current entry."
11734 (interactive)
11735 (org-back-to-heading t)
11736 (looking-at outline-regexp)
11737 (let ((indent (if org-adapt-indentation
11738 (- (match-end 0)(match-beginning 0))
11740 (beg (point))
11741 (re (concat "^[ \t]*" org-keyword-time-regexp))
11742 end hiddenp)
11743 (outline-next-heading)
11744 (setq end (point))
11745 (goto-char beg)
11746 (while (re-search-forward re end t))
11747 (setq hiddenp (org-invisible-p))
11748 (end-of-line 1)
11749 (and (equal (char-after) ?\n) (forward-char 1))
11750 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11751 (if (member (match-string 1) '("CLOCK:" ":END:"))
11752 ;; just skip this line
11753 (beginning-of-line 2)
11754 ;; Drawer start, find the end
11755 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11756 (beginning-of-line 1)))
11757 (org-skip-over-state-notes)
11758 (skip-chars-backward " \t\n\r")
11759 (if (eq (char-before) ?*) (forward-char 1))
11760 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11761 (beginning-of-line 0)
11762 (org-indent-to-column indent)
11763 (beginning-of-line 2)
11764 (org-indent-to-column indent)
11765 (beginning-of-line 0)
11766 (if hiddenp
11767 (save-excursion
11768 (org-back-to-heading t)
11769 (hide-entry))
11770 (org-flag-drawer t))))
11772 (defun org-set-property (property value)
11773 "In the current entry, set PROPERTY to VALUE.
11774 When called interactively, this will prompt for a property name, offering
11775 completion on existing and default properties. And then it will prompt
11776 for a value, offering completion either on allowed values (via an inherited
11777 xxx_ALL property) or on existing values in other instances of this property
11778 in the current file."
11779 (interactive
11780 (let* ((completion-ignore-case t)
11781 (keys (org-buffer-property-keys nil t t))
11782 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11783 (prop (if (member prop0 keys)
11784 prop0
11785 (or (cdr (assoc (downcase prop0)
11786 (mapcar (lambda (x) (cons (downcase x) x))
11787 keys)))
11788 prop0)))
11789 (cur (org-entry-get nil prop))
11790 (allowed (org-property-get-allowed-values nil prop 'table))
11791 (existing (mapcar 'list (org-property-values prop)))
11792 (val (if allowed
11793 (org-completing-read "Value: " allowed nil 'req-match)
11794 (let (org-completion-use-ido)
11795 (org-completing-read
11796 (concat "Value" (if (and cur (string-match "\\S-" cur))
11797 (concat "[" cur "]") "")
11798 ": ")
11799 existing nil nil "" nil cur)))))
11800 (list prop (if (equal val "") cur val))))
11801 (unless (equal (org-entry-get nil property) value)
11802 (org-entry-put nil property value)))
11804 (defun org-delete-property (property)
11805 "In the current entry, delete PROPERTY."
11806 (interactive
11807 (let* ((completion-ignore-case t)
11808 (prop (org-ido-completing-read
11809 "Property: " (org-entry-properties nil 'standard))))
11810 (list prop)))
11811 (message "Property %s %s" property
11812 (if (org-entry-delete nil property)
11813 "deleted"
11814 "was not present in the entry")))
11816 (defun org-delete-property-globally (property)
11817 "Remove PROPERTY globally, from all entries."
11818 (interactive
11819 (let* ((completion-ignore-case t)
11820 (prop (org-ido-completing-read
11821 "Globally remove property: "
11822 (mapcar 'list (org-buffer-property-keys)))))
11823 (list prop)))
11824 (save-excursion
11825 (save-restriction
11826 (widen)
11827 (goto-char (point-min))
11828 (let ((cnt 0))
11829 (while (re-search-forward
11830 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11831 nil t)
11832 (setq cnt (1+ cnt))
11833 (replace-match ""))
11834 (message "Property \"%s\" removed from %d entries" property cnt)))))
11836 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11838 (defun org-compute-property-at-point ()
11839 "Compute the property at point.
11840 This looks for an enclosing column format, extracts the operator and
11841 then applies it to the property in the column format's scope."
11842 (interactive)
11843 (unless (org-at-property-p)
11844 (error "Not at a property"))
11845 (let ((prop (org-match-string-no-properties 2)))
11846 (org-columns-get-format-and-top-level)
11847 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11848 (error "No operator defined for property %s" prop))
11849 (org-columns-compute prop)))
11851 (defun org-property-get-allowed-values (pom property &optional table)
11852 "Get allowed values for the property PROPERTY.
11853 When TABLE is non-nil, return an alist that can directly be used for
11854 completion."
11855 (let (vals)
11856 (cond
11857 ((equal property "TODO")
11858 (setq vals (org-with-point-at pom
11859 (append org-todo-keywords-1 '("")))))
11860 ((equal property "PRIORITY")
11861 (let ((n org-lowest-priority))
11862 (while (>= n org-highest-priority)
11863 (push (char-to-string n) vals)
11864 (setq n (1- n)))))
11865 ((member property org-special-properties))
11867 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11869 (when (and vals (string-match "\\S-" vals))
11870 (setq vals (car (read-from-string (concat "(" vals ")"))))
11871 (setq vals (mapcar (lambda (x)
11872 (cond ((stringp x) x)
11873 ((numberp x) (number-to-string x))
11874 ((symbolp x) (symbol-name x))
11875 (t "???")))
11876 vals)))))
11877 (if table (mapcar 'list vals) vals)))
11879 (defun org-property-previous-allowed-value (&optional previous)
11880 "Switch to the next allowed value for this property."
11881 (interactive)
11882 (org-property-next-allowed-value t))
11884 (defun org-property-next-allowed-value (&optional previous)
11885 "Switch to the next allowed value for this property."
11886 (interactive)
11887 (unless (org-at-property-p)
11888 (error "Not at a property"))
11889 (let* ((key (match-string 2))
11890 (value (match-string 3))
11891 (allowed (or (org-property-get-allowed-values (point) key)
11892 (and (member value '("[ ]" "[-]" "[X]"))
11893 '("[ ]" "[X]"))))
11894 nval)
11895 (unless allowed
11896 (error "Allowed values for this property have not been defined"))
11897 (if previous (setq allowed (reverse allowed)))
11898 (if (member value allowed)
11899 (setq nval (car (cdr (member value allowed)))))
11900 (setq nval (or nval (car allowed)))
11901 (if (equal nval value)
11902 (error "Only one allowed value for this property"))
11903 (org-at-property-p)
11904 (replace-match (concat " :" key ": " nval) t t)
11905 (org-indent-line-function)
11906 (beginning-of-line 1)
11907 (skip-chars-forward " \t")))
11909 (defun org-find-entry-with-id (ident)
11910 "Locate the entry that contains the ID property with exact value IDENT.
11911 IDENT can be a string, a symbol or a number, this function will search for
11912 the string representation of it.
11913 Return the position where this entry starts, or nil if there is no such entry."
11914 (interactive "sID: ")
11915 (let ((id (cond
11916 ((stringp ident) ident)
11917 ((symbol-name ident) (symbol-name ident))
11918 ((numberp ident) (number-to-string ident))
11919 (t (error "IDENT %s must be a string, symbol or number" ident))))
11920 (case-fold-search nil))
11921 (save-excursion
11922 (save-restriction
11923 (widen)
11924 (goto-char (point-min))
11925 (when (re-search-forward
11926 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11927 nil t)
11928 (org-back-to-heading t)
11929 (point))))))
11931 ;;;; Timestamps
11933 (defvar org-last-changed-timestamp nil)
11934 (defvar org-last-inserted-timestamp nil
11935 "The last time stamp inserted with `org-insert-time-stamp'.")
11936 (defvar org-time-was-given) ; dynamically scoped parameter
11937 (defvar org-end-time-was-given) ; dynamically scoped parameter
11938 (defvar org-ts-what) ; dynamically scoped parameter
11940 (defun org-time-stamp (arg &optional inactive)
11941 "Prompt for a date/time and insert a time stamp.
11942 If the user specifies a time like HH:MM, or if this command is called
11943 with a prefix argument, the time stamp will contain date and time.
11944 Otherwise, only the date will be included. All parts of a date not
11945 specified by the user will be filled in from the current date/time.
11946 So if you press just return without typing anything, the time stamp
11947 will represent the current date/time. If there is already a timestamp
11948 at the cursor, it will be modified."
11949 (interactive "P")
11950 (let* ((ts nil)
11951 (default-time
11952 ;; Default time is either today, or, when entering a range,
11953 ;; the range start.
11954 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11955 (save-excursion
11956 (re-search-backward
11957 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11958 (- (point) 20) t)))
11959 (apply 'encode-time (org-parse-time-string (match-string 1)))
11960 (current-time)))
11961 (default-input (and ts (org-get-compact-tod ts)))
11962 org-time-was-given org-end-time-was-given time)
11963 (cond
11964 ((and (org-at-timestamp-p t)
11965 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11966 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11967 (insert "--")
11968 (setq time (let ((this-command this-command))
11969 (org-read-date arg 'totime nil nil
11970 default-time default-input)))
11971 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11972 ((org-at-timestamp-p t)
11973 (setq time (let ((this-command this-command))
11974 (org-read-date arg 'totime nil nil default-time default-input)))
11975 (when (org-at-timestamp-p t) ; just to get the match data
11976 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11977 (replace-match "")
11978 (setq org-last-changed-timestamp
11979 (org-insert-time-stamp
11980 time (or org-time-was-given arg)
11981 inactive nil nil (list org-end-time-was-given))))
11982 (message "Timestamp updated"))
11984 (setq time (let ((this-command this-command))
11985 (org-read-date arg 'totime nil nil default-time default-input)))
11986 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11987 nil nil (list org-end-time-was-given))))))
11989 ;; FIXME: can we use this for something else, like computing time differences?
11990 (defun org-get-compact-tod (s)
11991 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11992 (let* ((t1 (match-string 1 s))
11993 (h1 (string-to-number (match-string 2 s)))
11994 (m1 (string-to-number (match-string 3 s)))
11995 (t2 (and (match-end 4) (match-string 5 s)))
11996 (h2 (and t2 (string-to-number (match-string 6 s))))
11997 (m2 (and t2 (string-to-number (match-string 7 s))))
11998 dh dm)
11999 (if (not t2)
12001 (setq dh (- h2 h1) dm (- m2 m1))
12002 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12003 (concat t1 "+" (number-to-string dh)
12004 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12006 (defun org-time-stamp-inactive (&optional arg)
12007 "Insert an inactive time stamp.
12008 An inactive time stamp is enclosed in square brackets instead of angle
12009 brackets. It is inactive in the sense that it does not trigger agenda entries,
12010 does not link to the calendar and cannot be changed with the S-cursor keys.
12011 So these are more for recording a certain time/date."
12012 (interactive "P")
12013 (org-time-stamp arg 'inactive))
12015 (defvar org-date-ovl (org-make-overlay 1 1))
12016 (org-overlay-put org-date-ovl 'face 'org-warning)
12017 (org-detach-overlay org-date-ovl)
12019 (defvar org-ans1) ; dynamically scoped parameter
12020 (defvar org-ans2) ; dynamically scoped parameter
12022 (defvar org-plain-time-of-day-regexp) ; defined below
12024 (defvar org-overriding-default-time nil) ; dynamically scoped
12025 (defvar org-read-date-overlay nil)
12026 (defvar org-dcst nil) ; dynamically scoped
12027 (defvar org-read-date-history nil)
12028 (defvar org-read-date-final-answer nil)
12030 (defun org-read-date (&optional with-time to-time from-string prompt
12031 default-time default-input)
12032 "Read a date, possibly a time, and make things smooth for the user.
12033 The prompt will suggest to enter an ISO date, but you can also enter anything
12034 which will at least partially be understood by `parse-time-string'.
12035 Unrecognized parts of the date will default to the current day, month, year,
12036 hour and minute. If this command is called to replace a timestamp at point,
12037 of to enter the second timestamp of a range, the default time is taken from the
12038 existing stamp. For example,
12039 3-2-5 --> 2003-02-05
12040 feb 15 --> currentyear-02-15
12041 sep 12 9 --> 2009-09-12
12042 12:45 --> today 12:45
12043 22 sept 0:34 --> currentyear-09-22 0:34
12044 12 --> currentyear-currentmonth-12
12045 Fri --> nearest Friday (today or later)
12046 etc.
12048 Furthermore you can specify a relative date by giving, as the *first* thing
12049 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12050 change in days weeks, months, years.
12051 With a single plus or minus, the date is relative to today. With a double
12052 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12053 +4d --> four days from today
12054 +4 --> same as above
12055 +2w --> two weeks from today
12056 ++5 --> five days from default date
12058 The function understands only English month and weekday abbreviations,
12059 but this can be configured with the variables `parse-time-months' and
12060 `parse-time-weekdays'.
12062 While prompting, a calendar is popped up - you can also select the
12063 date with the mouse (button 1). The calendar shows a period of three
12064 months. To scroll it to other months, use the keys `>' and `<'.
12065 If you don't like the calendar, turn it off with
12066 \(setq org-read-date-popup-calendar nil)
12068 With optional argument TO-TIME, the date will immediately be converted
12069 to an internal time.
12070 With an optional argument WITH-TIME, the prompt will suggest to also
12071 insert a time. Note that when WITH-TIME is not set, you can still
12072 enter a time, and this function will inform the calling routine about
12073 this change. The calling routine may then choose to change the format
12074 used to insert the time stamp into the buffer to include the time.
12075 With optional argument FROM-STRING, read from this string instead from
12076 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12077 the time/date that is used for everything that is not specified by the
12078 user."
12079 (require 'parse-time)
12080 (let* ((org-time-stamp-rounding-minutes
12081 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12082 (org-dcst org-display-custom-times)
12083 (ct (org-current-time))
12084 (def (or org-overriding-default-time default-time ct))
12085 (defdecode (decode-time def))
12086 (dummy (progn
12087 (when (< (nth 2 defdecode) org-extend-today-until)
12088 (setcar (nthcdr 2 defdecode) -1)
12089 (setcar (nthcdr 1 defdecode) 59)
12090 (setq def (apply 'encode-time defdecode)
12091 defdecode (decode-time def)))))
12092 (calendar-move-hook nil)
12093 (calendar-view-diary-initially-flag nil)
12094 (view-diary-entries-initially nil)
12095 (calendar-view-holidays-initially-flag nil)
12096 (view-calendar-holidays-initially nil)
12097 (timestr (format-time-string
12098 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12099 (prompt (concat (if prompt (concat prompt " ") "")
12100 (format "Date+time [%s]: " timestr)))
12101 ans (org-ans0 "") org-ans1 org-ans2 final)
12103 (cond
12104 (from-string (setq ans from-string))
12105 (org-read-date-popup-calendar
12106 (save-excursion
12107 (save-window-excursion
12108 (calendar)
12109 (calendar-forward-day (- (time-to-days def)
12110 (calendar-absolute-from-gregorian
12111 (calendar-current-date))))
12112 (org-eval-in-calendar nil t)
12113 (let* ((old-map (current-local-map))
12114 (map (copy-keymap calendar-mode-map))
12115 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12116 (org-defkey map (kbd "RET") 'org-calendar-select)
12117 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12118 'org-calendar-select-mouse)
12119 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12120 'org-calendar-select-mouse)
12121 (org-defkey minibuffer-local-map [(meta shift left)]
12122 (lambda () (interactive)
12123 (org-eval-in-calendar '(calendar-backward-month 1))))
12124 (org-defkey minibuffer-local-map [(meta shift right)]
12125 (lambda () (interactive)
12126 (org-eval-in-calendar '(calendar-forward-month 1))))
12127 (org-defkey minibuffer-local-map [(meta shift up)]
12128 (lambda () (interactive)
12129 (org-eval-in-calendar '(calendar-backward-year 1))))
12130 (org-defkey minibuffer-local-map [(meta shift down)]
12131 (lambda () (interactive)
12132 (org-eval-in-calendar '(calendar-forward-year 1))))
12133 (org-defkey minibuffer-local-map [?\e (shift left)]
12134 (lambda () (interactive)
12135 (org-eval-in-calendar '(calendar-backward-month 1))))
12136 (org-defkey minibuffer-local-map [?\e (shift right)]
12137 (lambda () (interactive)
12138 (org-eval-in-calendar '(calendar-forward-month 1))))
12139 (org-defkey minibuffer-local-map [?\e (shift up)]
12140 (lambda () (interactive)
12141 (org-eval-in-calendar '(calendar-backward-year 1))))
12142 (org-defkey minibuffer-local-map [?\e (shift down)]
12143 (lambda () (interactive)
12144 (org-eval-in-calendar '(calendar-forward-year 1))))
12145 (org-defkey minibuffer-local-map [(shift up)]
12146 (lambda () (interactive)
12147 (org-eval-in-calendar '(calendar-backward-week 1))))
12148 (org-defkey minibuffer-local-map [(shift down)]
12149 (lambda () (interactive)
12150 (org-eval-in-calendar '(calendar-forward-week 1))))
12151 (org-defkey minibuffer-local-map [(shift left)]
12152 (lambda () (interactive)
12153 (org-eval-in-calendar '(calendar-backward-day 1))))
12154 (org-defkey minibuffer-local-map [(shift right)]
12155 (lambda () (interactive)
12156 (org-eval-in-calendar '(calendar-forward-day 1))))
12157 (org-defkey minibuffer-local-map ">"
12158 (lambda () (interactive)
12159 (org-eval-in-calendar '(scroll-calendar-left 1))))
12160 (org-defkey minibuffer-local-map "<"
12161 (lambda () (interactive)
12162 (org-eval-in-calendar '(scroll-calendar-right 1))))
12163 (run-hooks 'org-read-date-minibuffer-setup-hook)
12164 (unwind-protect
12165 (progn
12166 (use-local-map map)
12167 (add-hook 'post-command-hook 'org-read-date-display)
12168 (setq org-ans0 (read-string prompt default-input
12169 'org-read-date-history nil))
12170 ;; org-ans0: from prompt
12171 ;; org-ans1: from mouse click
12172 ;; org-ans2: from calendar motion
12173 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12174 (remove-hook 'post-command-hook 'org-read-date-display)
12175 (use-local-map old-map)
12176 (when org-read-date-overlay
12177 (org-delete-overlay org-read-date-overlay)
12178 (setq org-read-date-overlay nil)))))))
12180 (t ; Naked prompt only
12181 (unwind-protect
12182 (setq ans (read-string prompt default-input
12183 'org-read-date-history timestr))
12184 (when org-read-date-overlay
12185 (org-delete-overlay org-read-date-overlay)
12186 (setq org-read-date-overlay nil)))))
12188 (setq final (org-read-date-analyze ans def defdecode))
12189 (setq org-read-date-final-answer ans)
12191 (if to-time
12192 (apply 'encode-time final)
12193 (if (and (boundp 'org-time-was-given) org-time-was-given)
12194 (format "%04d-%02d-%02d %02d:%02d"
12195 (nth 5 final) (nth 4 final) (nth 3 final)
12196 (nth 2 final) (nth 1 final))
12197 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12198 (defvar def)
12199 (defvar defdecode)
12200 (defvar with-time)
12201 (defun org-read-date-display ()
12202 "Display the current date prompt interpretation in the minibuffer."
12203 (when org-read-date-display-live
12204 (when org-read-date-overlay
12205 (org-delete-overlay org-read-date-overlay))
12206 (let ((p (point)))
12207 (end-of-line 1)
12208 (while (not (equal (buffer-substring
12209 (max (point-min) (- (point) 4)) (point))
12210 " "))
12211 (insert " "))
12212 (goto-char p))
12213 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12214 " " (or org-ans1 org-ans2)))
12215 (org-end-time-was-given nil)
12216 (f (org-read-date-analyze ans def defdecode))
12217 (fmts (if org-dcst
12218 org-time-stamp-custom-formats
12219 org-time-stamp-formats))
12220 (fmt (if (or with-time
12221 (and (boundp 'org-time-was-given) org-time-was-given))
12222 (cdr fmts)
12223 (car fmts)))
12224 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12225 (when (and org-end-time-was-given
12226 (string-match org-plain-time-of-day-regexp txt))
12227 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12228 org-end-time-was-given
12229 (substring txt (match-end 0)))))
12230 (setq org-read-date-overlay
12231 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12232 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12234 (defun org-read-date-analyze (ans def defdecode)
12235 "Analyse the combined answer of the date prompt."
12236 ;; FIXME: cleanup and comment
12237 (let (delta deltan deltaw deltadef year month day
12238 hour minute second wday pm h2 m2 tl wday1
12239 iso-year iso-weekday iso-week iso-year iso-date)
12241 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12242 (setq ans "+0"))
12244 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12245 (setq ans (replace-match "" t t ans)
12246 deltan (car delta)
12247 deltaw (nth 1 delta)
12248 deltadef (nth 2 delta)))
12250 ;; Check if there is an iso week date in there
12251 ;; If yes, sore the info and postpone interpreting it until the rest
12252 ;; of the parsing is done
12253 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12254 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12255 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12256 iso-week (string-to-number (match-string 2 ans)))
12257 (setq ans (replace-match "" t t ans)))
12259 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12260 (when (string-match
12261 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12262 (setq year (if (match-end 2)
12263 (string-to-number (match-string 2 ans))
12264 (string-to-number (format-time-string "%Y")))
12265 month (string-to-number (match-string 3 ans))
12266 day (string-to-number (match-string 4 ans)))
12267 (if (< year 100) (setq year (+ 2000 year)))
12268 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12269 t nil ans)))
12270 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12271 ;; If there is a time with am/pm, and *no* time without it, we convert
12272 ;; so that matching will be successful.
12273 (loop for i from 1 to 2 do ; twice, for end time as well
12274 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12275 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12276 (setq hour (string-to-number (match-string 1 ans))
12277 minute (if (match-end 3)
12278 (string-to-number (match-string 3 ans))
12280 pm (equal ?p
12281 (string-to-char (downcase (match-string 4 ans)))))
12282 (if (and (= hour 12) (not pm))
12283 (setq hour 0)
12284 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12285 (setq ans (replace-match (format "%02d:%02d" hour minute)
12286 t t ans))))
12288 ;; Check if a time range is given as a duration
12289 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12290 (setq hour (string-to-number (match-string 1 ans))
12291 h2 (+ hour (string-to-number (match-string 3 ans)))
12292 minute (string-to-number (match-string 2 ans))
12293 m2 (+ minute (if (match-end 5) (string-to-number
12294 (match-string 5 ans))0)))
12295 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12296 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12297 t t ans)))
12299 ;; Check if there is a time range
12300 (when (boundp 'org-end-time-was-given)
12301 (setq org-time-was-given nil)
12302 (when (and (string-match org-plain-time-of-day-regexp ans)
12303 (match-end 8))
12304 (setq org-end-time-was-given (match-string 8 ans))
12305 (setq ans (concat (substring ans 0 (match-beginning 7))
12306 (substring ans (match-end 7))))))
12308 (setq tl (parse-time-string ans)
12309 day (or (nth 3 tl) (nth 3 defdecode))
12310 month (or (nth 4 tl)
12311 (if (and org-read-date-prefer-future
12312 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12313 (1+ (nth 4 defdecode))
12314 (nth 4 defdecode)))
12315 year (or (nth 5 tl)
12316 (if (and org-read-date-prefer-future
12317 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12318 (1+ (nth 5 defdecode))
12319 (nth 5 defdecode)))
12320 hour (or (nth 2 tl) (nth 2 defdecode))
12321 minute (or (nth 1 tl) (nth 1 defdecode))
12322 second (or (nth 0 tl) 0)
12323 wday (nth 6 tl))
12325 ;; Special date definitions below
12326 (cond
12327 (iso-week
12328 ;; There was an iso week
12329 (setq year (or iso-year year)
12330 day (or iso-weekday wday 1)
12331 wday nil ; to make sure that the trigger below does not match
12332 iso-date (calendar-gregorian-from-absolute
12333 (calendar-absolute-from-iso
12334 (list iso-week day year))))
12335 ; FIXME: Should we also push ISO weeks into the future?
12336 ; (when (and org-read-date-prefer-future
12337 ; (not iso-year)
12338 ; (< (calendar-absolute-from-gregorian iso-date)
12339 ; (time-to-days (current-time))))
12340 ; (setq year (1+ year)
12341 ; iso-date (calendar-gregorian-from-absolute
12342 ; (calendar-absolute-from-iso
12343 ; (list iso-week day year)))))
12344 (setq month (car iso-date)
12345 year (nth 2 iso-date)
12346 day (nth 1 iso-date)))
12347 (deltan
12348 (unless deltadef
12349 (let ((now (decode-time (current-time))))
12350 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12351 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12352 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12353 ((equal deltaw "m") (setq month (+ month deltan)))
12354 ((equal deltaw "y") (setq year (+ year deltan)))))
12355 ((and wday (not (nth 3 tl)))
12356 ;; Weekday was given, but no day, so pick that day in the week
12357 ;; on or after the derived date.
12358 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12359 (unless (equal wday wday1)
12360 (setq day (+ day (% (- wday wday1 -7) 7))))))
12361 (if (and (boundp 'org-time-was-given)
12362 (nth 2 tl))
12363 (setq org-time-was-given t))
12364 (if (< year 100) (setq year (+ 2000 year)))
12365 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12366 (list second minute hour day month year)))
12368 (defvar parse-time-weekdays)
12370 (defun org-read-date-get-relative (s today default)
12371 "Check string S for special relative date string.
12372 TODAY and DEFAULT are internal times, for today and for a default.
12373 Return shift list (N what def-flag)
12374 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12375 N is the number of WHATs to shift.
12376 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12377 the DEFAULT date rather than TODAY."
12378 (when (and
12379 (string-match
12380 (concat
12381 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12382 "\\([0-9]+\\)?"
12383 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12384 "\\([ \t]\\|$\\)") s)
12385 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12386 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12387 (string-to-char (substring (match-string 1 s) -1))
12388 ?+))
12389 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12390 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12391 (what (if (match-end 3) (match-string 3 s) "d"))
12392 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12393 (date (if rel default today))
12394 (wday (nth 6 (decode-time date)))
12395 delta)
12396 (if wday1
12397 (progn
12398 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12399 (if (= dir ?-) (setq delta (- delta 7)))
12400 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12401 (list delta "d" rel))
12402 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12404 (defun org-eval-in-calendar (form &optional keepdate)
12405 "Eval FORM in the calendar window and return to current window.
12406 Also, store the cursor date in variable org-ans2."
12407 (let ((sw (selected-window)))
12408 (select-window (get-buffer-window "*Calendar*"))
12409 (eval form)
12410 (when (and (not keepdate) (calendar-cursor-to-date))
12411 (let* ((date (calendar-cursor-to-date))
12412 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12413 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12414 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12415 (select-window sw)))
12417 (defun org-calendar-select ()
12418 "Return to `org-read-date' with the date currently selected.
12419 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12420 (interactive)
12421 (when (calendar-cursor-to-date)
12422 (let* ((date (calendar-cursor-to-date))
12423 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12424 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12425 (if (active-minibuffer-window) (exit-minibuffer))))
12427 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12428 "Insert a date stamp for the date given by the internal TIME.
12429 WITH-HM means, use the stamp format that includes the time of the day.
12430 INACTIVE means use square brackets instead of angular ones, so that the
12431 stamp will not contribute to the agenda.
12432 PRE and POST are optional strings to be inserted before and after the
12433 stamp.
12434 The command returns the inserted time stamp."
12435 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12436 stamp)
12437 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12438 (insert-before-markers (or pre ""))
12439 (insert-before-markers (setq stamp (format-time-string fmt time)))
12440 (when (listp extra)
12441 (setq extra (car extra))
12442 (if (and (stringp extra)
12443 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12444 (setq extra (format "-%02d:%02d"
12445 (string-to-number (match-string 1 extra))
12446 (string-to-number (match-string 2 extra))))
12447 (setq extra nil)))
12448 (when extra
12449 (backward-char 1)
12450 (insert-before-markers extra)
12451 (forward-char 1))
12452 (insert-before-markers (or post ""))
12453 (setq org-last-inserted-timestamp stamp)))
12455 (defun org-toggle-time-stamp-overlays ()
12456 "Toggle the use of custom time stamp formats."
12457 (interactive)
12458 (setq org-display-custom-times (not org-display-custom-times))
12459 (unless org-display-custom-times
12460 (let ((p (point-min)) (bmp (buffer-modified-p)))
12461 (while (setq p (next-single-property-change p 'display))
12462 (if (and (get-text-property p 'display)
12463 (eq (get-text-property p 'face) 'org-date))
12464 (remove-text-properties
12465 p (setq p (next-single-property-change p 'display))
12466 '(display t))))
12467 (set-buffer-modified-p bmp)))
12468 (if (featurep 'xemacs)
12469 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12470 (org-restart-font-lock)
12471 (setq org-table-may-need-update t)
12472 (if org-display-custom-times
12473 (message "Time stamps are overlayed with custom format")
12474 (message "Time stamp overlays removed")))
12476 (defun org-display-custom-time (beg end)
12477 "Overlay modified time stamp format over timestamp between BEG and END."
12478 (let* ((ts (buffer-substring beg end))
12479 t1 w1 with-hm tf time str w2 (off 0))
12480 (save-match-data
12481 (setq t1 (org-parse-time-string ts t))
12482 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12483 (setq off (- (match-end 0) (match-beginning 0)))))
12484 (setq end (- end off))
12485 (setq w1 (- end beg)
12486 with-hm (and (nth 1 t1) (nth 2 t1))
12487 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12488 time (org-fix-decoded-time t1)
12489 str (org-add-props
12490 (format-time-string
12491 (substring tf 1 -1) (apply 'encode-time time))
12492 nil 'mouse-face 'highlight)
12493 w2 (length str))
12494 (if (not (= w2 w1))
12495 (add-text-properties (1+ beg) (+ 2 beg)
12496 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12497 (if (featurep 'xemacs)
12498 (progn
12499 (put-text-property beg end 'invisible t)
12500 (put-text-property beg end 'end-glyph (make-glyph str)))
12501 (put-text-property beg end 'display str))))
12503 (defun org-translate-time (string)
12504 "Translate all timestamps in STRING to custom format.
12505 But do this only if the variable `org-display-custom-times' is set."
12506 (when org-display-custom-times
12507 (save-match-data
12508 (let* ((start 0)
12509 (re org-ts-regexp-both)
12510 t1 with-hm inactive tf time str beg end)
12511 (while (setq start (string-match re string start))
12512 (setq beg (match-beginning 0)
12513 end (match-end 0)
12514 t1 (save-match-data
12515 (org-parse-time-string (substring string beg end) t))
12516 with-hm (and (nth 1 t1) (nth 2 t1))
12517 inactive (equal (substring string beg (1+ beg)) "[")
12518 tf (funcall (if with-hm 'cdr 'car)
12519 org-time-stamp-custom-formats)
12520 time (org-fix-decoded-time t1)
12521 str (format-time-string
12522 (concat
12523 (if inactive "[" "<") (substring tf 1 -1)
12524 (if inactive "]" ">"))
12525 (apply 'encode-time time))
12526 string (replace-match str t t string)
12527 start (+ start (length str)))))))
12528 string)
12530 (defun org-fix-decoded-time (time)
12531 "Set 0 instead of nil for the first 6 elements of time.
12532 Don't touch the rest."
12533 (let ((n 0))
12534 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12536 (defun org-days-to-time (timestamp-string)
12537 "Difference between TIMESTAMP-STRING and now in days."
12538 (- (time-to-days (org-time-string-to-time timestamp-string))
12539 (time-to-days (current-time))))
12541 (defun org-deadline-close (timestamp-string &optional ndays)
12542 "Is the time in TIMESTAMP-STRING close to the current date?"
12543 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12544 (and (< (org-days-to-time timestamp-string) ndays)
12545 (not (org-entry-is-done-p))))
12547 (defun org-get-wdays (ts)
12548 "Get the deadline lead time appropriate for timestring TS."
12549 (cond
12550 ((<= org-deadline-warning-days 0)
12551 ;; 0 or negative, enforce this value no matter what
12552 (- org-deadline-warning-days))
12553 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12554 ;; lead time is specified.
12555 (floor (* (string-to-number (match-string 1 ts))
12556 (cdr (assoc (match-string 2 ts)
12557 '(("d" . 1) ("w" . 7)
12558 ("m" . 30.4) ("y" . 365.25)))))))
12559 ;; go for the default.
12560 (t org-deadline-warning-days)))
12562 (defun org-calendar-select-mouse (ev)
12563 "Return to `org-read-date' with the date currently selected.
12564 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12565 (interactive "e")
12566 (mouse-set-point ev)
12567 (when (calendar-cursor-to-date)
12568 (let* ((date (calendar-cursor-to-date))
12569 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12570 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12571 (if (active-minibuffer-window) (exit-minibuffer))))
12573 (defun org-check-deadlines (ndays)
12574 "Check if there are any deadlines due or past due.
12575 A deadline is considered due if it happens within `org-deadline-warning-days'
12576 days from today's date. If the deadline appears in an entry marked DONE,
12577 it is not shown. The prefix arg NDAYS can be used to test that many
12578 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12579 (interactive "P")
12580 (let* ((org-warn-days
12581 (cond
12582 ((equal ndays '(4)) 100000)
12583 (ndays (prefix-numeric-value ndays))
12584 (t (abs org-deadline-warning-days))))
12585 (case-fold-search nil)
12586 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12587 (callback
12588 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12590 (message "%d deadlines past-due or due within %d days"
12591 (org-occur regexp nil callback)
12592 org-warn-days)))
12594 (defun org-check-before-date (date)
12595 "Check if there are deadlines or scheduled entries before DATE."
12596 (interactive (list (org-read-date)))
12597 (let ((case-fold-search nil)
12598 (regexp (concat "\\<\\(" org-deadline-string
12599 "\\|" org-scheduled-string
12600 "\\) *<\\([^>]+\\)>"))
12601 (callback
12602 (lambda () (time-less-p
12603 (org-time-string-to-time (match-string 2))
12604 (org-time-string-to-time date)))))
12605 (message "%d entries before %s"
12606 (org-occur regexp nil callback) date)))
12608 (defun org-check-after-date (date)
12609 "Check if there are deadlines or scheduled entries after DATE."
12610 (interactive (list (org-read-date)))
12611 (let ((case-fold-search nil)
12612 (regexp (concat "\\<\\(" org-deadline-string
12613 "\\|" org-scheduled-string
12614 "\\) *<\\([^>]+\\)>"))
12615 (callback
12616 (lambda () (not
12617 (time-less-p
12618 (org-time-string-to-time (match-string 2))
12619 (org-time-string-to-time date))))))
12620 (message "%d entries after %s"
12621 (org-occur regexp nil callback) date)))
12623 (defun org-evaluate-time-range (&optional to-buffer)
12624 "Evaluate a time range by computing the difference between start and end.
12625 Normally the result is just printed in the echo area, but with prefix arg
12626 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12627 If the time range is actually in a table, the result is inserted into the
12628 next column.
12629 For time difference computation, a year is assumed to be exactly 365
12630 days in order to avoid rounding problems."
12631 (interactive "P")
12633 (org-clock-update-time-maybe)
12634 (save-excursion
12635 (unless (org-at-date-range-p t)
12636 (goto-char (point-at-bol))
12637 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12638 (if (not (org-at-date-range-p t))
12639 (error "Not at a time-stamp range, and none found in current line")))
12640 (let* ((ts1 (match-string 1))
12641 (ts2 (match-string 2))
12642 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12643 (match-end (match-end 0))
12644 (time1 (org-time-string-to-time ts1))
12645 (time2 (org-time-string-to-time ts2))
12646 (t1 (time-to-seconds time1))
12647 (t2 (time-to-seconds time2))
12648 (diff (abs (- t2 t1)))
12649 (negative (< (- t2 t1) 0))
12650 ;; (ys (floor (* 365 24 60 60)))
12651 (ds (* 24 60 60))
12652 (hs (* 60 60))
12653 (fy "%dy %dd %02d:%02d")
12654 (fy1 "%dy %dd")
12655 (fd "%dd %02d:%02d")
12656 (fd1 "%dd")
12657 (fh "%02d:%02d")
12658 y d h m align)
12659 (if havetime
12660 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12662 d (floor (/ diff ds)) diff (mod diff ds)
12663 h (floor (/ diff hs)) diff (mod diff hs)
12664 m (floor (/ diff 60)))
12665 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12667 d (floor (+ (/ diff ds) 0.5))
12668 h 0 m 0))
12669 (if (not to-buffer)
12670 (message "%s" (org-make-tdiff-string y d h m))
12671 (if (org-at-table-p)
12672 (progn
12673 (goto-char match-end)
12674 (setq align t)
12675 (and (looking-at " *|") (goto-char (match-end 0))))
12676 (goto-char match-end))
12677 (if (looking-at
12678 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12679 (replace-match ""))
12680 (if negative (insert " -"))
12681 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12682 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12683 (insert " " (format fh h m))))
12684 (if align (org-table-align))
12685 (message "Time difference inserted")))))
12687 (defun org-make-tdiff-string (y d h m)
12688 (let ((fmt "")
12689 (l nil))
12690 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12691 l (push y l)))
12692 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12693 l (push d l)))
12694 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12695 l (push h l)))
12696 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12697 l (push m l)))
12698 (apply 'format fmt (nreverse l))))
12700 (defun org-time-string-to-time (s)
12701 (apply 'encode-time (org-parse-time-string s)))
12702 (defun org-time-string-to-seconds (s)
12703 (time-to-seconds (org-time-string-to-time s)))
12705 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12706 "Convert a time stamp to an absolute day number.
12707 If there is a specifyer for a cyclic time stamp, get the closest date to
12708 DAYNR.
12709 PREFER and SHOW-ALL are passed through to `org-closest-date'.
12710 the variable date is bound by the calendar when this is called."
12711 (cond
12712 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12713 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12714 daynr
12715 (+ daynr 1000)))
12716 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12717 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12718 (time-to-days (current-time))) (match-string 0 s)
12719 prefer show-all))
12720 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12722 (defun org-days-to-iso-week (days)
12723 "Return the iso week number."
12724 (require 'cal-iso)
12725 (car (calendar-iso-from-absolute days)))
12727 (defun org-small-year-to-year (year)
12728 "Convert 2-digit years into 4-digit years.
12729 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12730 The year 2000 cannot be abbreviated. Any year larger than 99
12731 is returned unchanged."
12732 (if (< year 38)
12733 (setq year (+ 2000 year))
12734 (if (< year 100)
12735 (setq year (+ 1900 year))))
12736 year)
12738 (defun org-time-from-absolute (d)
12739 "Return the time corresponding to date D.
12740 D may be an absolute day number, or a calendar-type list (month day year)."
12741 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12742 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12744 (defun org-calendar-holiday ()
12745 "List of holidays, for Diary display in Org-mode."
12746 (require 'holidays)
12747 (let ((hl (funcall
12748 (if (fboundp 'calendar-check-holidays)
12749 'calendar-check-holidays 'check-calendar-holidays) date)))
12750 (if hl (mapconcat 'identity hl "; "))))
12752 (defun org-diary-sexp-entry (sexp entry date)
12753 "Process a SEXP diary ENTRY for DATE."
12754 (require 'diary-lib)
12755 (let ((result (if calendar-debug-sexp
12756 (let ((stack-trace-on-error t))
12757 (eval (car (read-from-string sexp))))
12758 (condition-case nil
12759 (eval (car (read-from-string sexp)))
12760 (error
12761 (beep)
12762 (message "Bad sexp at line %d in %s: %s"
12763 (org-current-line)
12764 (buffer-file-name) sexp)
12765 (sleep-for 2))))))
12766 (cond ((stringp result) result)
12767 ((and (consp result)
12768 (stringp (cdr result))) (cdr result))
12769 (result entry)
12770 (t nil))))
12772 (defun org-diary-to-ical-string (frombuf)
12773 "Get iCalendar entries from diary entries in buffer FROMBUF.
12774 This uses the icalendar.el library."
12775 (let* ((tmpdir (if (featurep 'xemacs)
12776 (temp-directory)
12777 temporary-file-directory))
12778 (tmpfile (make-temp-name
12779 (expand-file-name "orgics" tmpdir)))
12780 buf rtn b e)
12781 (save-excursion
12782 (set-buffer frombuf)
12783 (icalendar-export-region (point-min) (point-max) tmpfile)
12784 (setq buf (find-buffer-visiting tmpfile))
12785 (set-buffer buf)
12786 (goto-char (point-min))
12787 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12788 (setq b (match-beginning 0)))
12789 (goto-char (point-max))
12790 (if (re-search-backward "^END:VEVENT" nil t)
12791 (setq e (match-end 0)))
12792 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12793 (kill-buffer buf)
12794 (delete-file tmpfile)
12795 rtn))
12797 (defun org-closest-date (start current change prefer show-all)
12798 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12799 When PREFER is `past' return a date that is either CURRENT or past.
12800 When PREFER is `future', return a date that is either CURRENT or future.
12801 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12802 ;; Make the proper lists from the dates
12803 (catch 'exit
12804 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12805 dn dw sday cday n1 n2 n0
12806 d m y y1 y2 date1 date2 nmonths nm ny m2)
12808 (setq start (org-date-to-gregorian start)
12809 current (org-date-to-gregorian
12810 (if show-all
12811 current
12812 (time-to-days (current-time))))
12813 sday (calendar-absolute-from-gregorian start)
12814 cday (calendar-absolute-from-gregorian current))
12816 (if (<= cday sday) (throw 'exit sday))
12818 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12819 (setq dn (string-to-number (match-string 1 change))
12820 dw (cdr (assoc (match-string 2 change) a1)))
12821 (error "Invalid change specifyer: %s" change))
12822 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12823 (cond
12824 ((eq dw 'day)
12825 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12826 n2 (+ n1 dn)))
12827 ((eq dw 'year)
12828 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12829 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12830 (setq date1 (list m d y1)
12831 n1 (calendar-absolute-from-gregorian date1)
12832 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12833 n2 (calendar-absolute-from-gregorian date2)))
12834 ((eq dw 'month)
12835 ;; approx number of month between the two dates
12836 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12837 ;; How often does dn fit in there?
12838 (setq d (nth 1 start) m (car start) y (nth 2 start)
12839 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12840 m (+ m nm)
12841 ny (floor (/ m 12))
12842 y (+ y ny)
12843 m (- m (* ny 12)))
12844 (while (> m 12) (setq m (- m 12) y (1+ y)))
12845 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12846 (setq m2 (+ m dn) y2 y)
12847 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12848 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12849 (while (<= n2 cday)
12850 (setq n1 n2 m m2 y y2)
12851 (setq m2 (+ m dn) y2 y)
12852 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12853 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12854 ;; Make sure n1 is the earlier date
12855 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12856 (if show-all
12857 (cond
12858 ((eq prefer 'past) n1)
12859 ((eq prefer 'future) (if (= cday n1) n1 n2))
12860 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12861 (cond
12862 ((eq prefer 'past) n1)
12863 ((eq prefer 'future) (if (= cday n1) n1 n2))
12864 (t (if (= cday n1) n1 n2)))))))
12866 (defun org-date-to-gregorian (date)
12867 "Turn any specification of DATE into a gregorian date for the calendar."
12868 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12869 ((and (listp date) (= (length date) 3)) date)
12870 ((stringp date)
12871 (setq date (org-parse-time-string date))
12872 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12873 ((listp date)
12874 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12876 (defun org-parse-time-string (s &optional nodefault)
12877 "Parse the standard Org-mode time string.
12878 This should be a lot faster than the normal `parse-time-string'.
12879 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12880 hour and minute fields will be nil if not given."
12881 (if (string-match org-ts-regexp0 s)
12882 (list 0
12883 (if (or (match-beginning 8) (not nodefault))
12884 (string-to-number (or (match-string 8 s) "0")))
12885 (if (or (match-beginning 7) (not nodefault))
12886 (string-to-number (or (match-string 7 s) "0")))
12887 (string-to-number (match-string 4 s))
12888 (string-to-number (match-string 3 s))
12889 (string-to-number (match-string 2 s))
12890 nil nil nil)
12891 (make-list 9 0)))
12893 (defun org-timestamp-up (&optional arg)
12894 "Increase the date item at the cursor by one.
12895 If the cursor is on the year, change the year. If it is on the month or
12896 the day, change that.
12897 With prefix ARG, change by that many units."
12898 (interactive "p")
12899 (org-timestamp-change (prefix-numeric-value arg)))
12901 (defun org-timestamp-down (&optional arg)
12902 "Decrease the date item at the cursor by one.
12903 If the cursor is on the year, change the year. If it is on the month or
12904 the day, change that.
12905 With prefix ARG, change by that many units."
12906 (interactive "p")
12907 (org-timestamp-change (- (prefix-numeric-value arg))))
12909 (defun org-timestamp-up-day (&optional arg)
12910 "Increase the date in the time stamp by one day.
12911 With prefix ARG, change that many days."
12912 (interactive "p")
12913 (if (and (not (org-at-timestamp-p t))
12914 (org-on-heading-p))
12915 (org-todo 'up)
12916 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12918 (defun org-timestamp-down-day (&optional arg)
12919 "Decrease the date in the time stamp by one day.
12920 With prefix ARG, change that many days."
12921 (interactive "p")
12922 (if (and (not (org-at-timestamp-p t))
12923 (org-on-heading-p))
12924 (org-todo 'down)
12925 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12927 (defun org-at-timestamp-p (&optional inactive-ok)
12928 "Determine if the cursor is in or at a timestamp."
12929 (interactive)
12930 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12931 (pos (point))
12932 (ans (or (looking-at tsr)
12933 (save-excursion
12934 (skip-chars-backward "^[<\n\r\t")
12935 (if (> (point) (point-min)) (backward-char 1))
12936 (and (looking-at tsr)
12937 (> (- (match-end 0) pos) -1))))))
12938 (and ans
12939 (boundp 'org-ts-what)
12940 (setq org-ts-what
12941 (cond
12942 ((= pos (match-beginning 0)) 'bracket)
12943 ((= pos (1- (match-end 0))) 'bracket)
12944 ((org-pos-in-match-range pos 2) 'year)
12945 ((org-pos-in-match-range pos 3) 'month)
12946 ((org-pos-in-match-range pos 7) 'hour)
12947 ((org-pos-in-match-range pos 8) 'minute)
12948 ((or (org-pos-in-match-range pos 4)
12949 (org-pos-in-match-range pos 5)) 'day)
12950 ((and (> pos (or (match-end 8) (match-end 5)))
12951 (< pos (match-end 0)))
12952 (- pos (or (match-end 8) (match-end 5))))
12953 (t 'day))))
12954 ans))
12956 (defun org-toggle-timestamp-type ()
12957 "Toggle the type (<active> or [inactive]) of a time stamp."
12958 (interactive)
12959 (when (org-at-timestamp-p t)
12960 (let ((beg (match-beginning 0)) (end (match-end 0))
12961 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12962 (save-excursion
12963 (goto-char beg)
12964 (while (re-search-forward "[][<>]" end t)
12965 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12966 t t)))
12967 (message "Timestamp is now %sactive"
12968 (if (equal (char-after beg) ?<) "" "in")))))
12970 (defun org-timestamp-change (n &optional what)
12971 "Change the date in the time stamp at point.
12972 The date will be changed by N times WHAT. WHAT can be `day', `month',
12973 `year', `minute', `second'. If WHAT is not given, the cursor position
12974 in the timestamp determines what will be changed."
12975 (let ((pos (point))
12976 with-hm inactive
12977 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12978 org-ts-what
12979 extra rem
12980 ts time time0)
12981 (if (not (org-at-timestamp-p t))
12982 (error "Not at a timestamp"))
12983 (if (and (not what) (eq org-ts-what 'bracket))
12984 (org-toggle-timestamp-type)
12985 (if (and (not what) (not (eq org-ts-what 'day))
12986 org-display-custom-times
12987 (get-text-property (point) 'display)
12988 (not (get-text-property (1- (point)) 'display)))
12989 (setq org-ts-what 'day))
12990 (setq org-ts-what (or what org-ts-what)
12991 inactive (= (char-after (match-beginning 0)) ?\[)
12992 ts (match-string 0))
12993 (replace-match "")
12994 (if (string-match
12995 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12997 (setq extra (match-string 1 ts)))
12998 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12999 (setq with-hm t))
13000 (setq time0 (org-parse-time-string ts))
13001 (when (and (eq org-ts-what 'minute)
13002 (eq current-prefix-arg nil))
13003 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13004 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13005 (setcar (cdr time0) (+ (nth 1 time0)
13006 (if (> n 0) (- rem) (- dm rem))))))
13007 (setq time
13008 (encode-time (or (car time0) 0)
13009 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13010 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13011 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13012 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13013 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13014 (nthcdr 6 time0)))
13015 (when (and (member org-ts-what '(hour minute))
13016 extra
13017 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13018 (setq extra (org-modify-ts-extra
13019 extra
13020 (if (eq org-ts-what 'hour) 2 5)
13021 n dm)))
13022 (when (integerp org-ts-what)
13023 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13024 (if (eq what 'calendar)
13025 (let ((cal-date (org-get-date-from-calendar)))
13026 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13027 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13028 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13029 (setcar time0 (or (car time0) 0))
13030 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13031 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13032 (setq time (apply 'encode-time time0))))
13033 (setq org-last-changed-timestamp
13034 (org-insert-time-stamp time with-hm inactive nil nil extra))
13035 (org-clock-update-time-maybe)
13036 (goto-char pos)
13037 ;; Try to recenter the calendar window, if any
13038 (if (and org-calendar-follow-timestamp-change
13039 (get-buffer-window "*Calendar*" t)
13040 (memq org-ts-what '(day month year)))
13041 (org-recenter-calendar (time-to-days time))))))
13043 (defun org-modify-ts-extra (s pos n dm)
13044 "Change the different parts of the lead-time and repeat fields in timestamp."
13045 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13046 ng h m new rem)
13047 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13048 (cond
13049 ((or (org-pos-in-match-range pos 2)
13050 (org-pos-in-match-range pos 3))
13051 (setq m (string-to-number (match-string 3 s))
13052 h (string-to-number (match-string 2 s)))
13053 (if (org-pos-in-match-range pos 2)
13054 (setq h (+ h n))
13055 (setq n (* dm (org-no-warnings (signum n))))
13056 (when (not (= 0 (setq rem (% m dm))))
13057 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13058 (setq m (+ m n)))
13059 (if (< m 0) (setq m (+ m 60) h (1- h)))
13060 (if (> m 59) (setq m (- m 60) h (1+ h)))
13061 (setq h (min 24 (max 0 h)))
13062 (setq ng 1 new (format "-%02d:%02d" h m)))
13063 ((org-pos-in-match-range pos 6)
13064 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13065 ((org-pos-in-match-range pos 5)
13066 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13068 ((org-pos-in-match-range pos 9)
13069 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13070 ((org-pos-in-match-range pos 8)
13071 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13073 (when ng
13074 (setq s (concat
13075 (substring s 0 (match-beginning ng))
13077 (substring s (match-end ng))))))
13080 (defun org-recenter-calendar (date)
13081 "If the calendar is visible, recenter it to DATE."
13082 (let* ((win (selected-window))
13083 (cwin (get-buffer-window "*Calendar*" t))
13084 (calendar-move-hook nil))
13085 (when cwin
13086 (select-window cwin)
13087 (calendar-goto-date (if (listp date) date
13088 (calendar-gregorian-from-absolute date)))
13089 (select-window win))))
13091 (defun org-goto-calendar (&optional arg)
13092 "Go to the Emacs calendar at the current date.
13093 If there is a time stamp in the current line, go to that date.
13094 A prefix ARG can be used to force the current date."
13095 (interactive "P")
13096 (let ((tsr org-ts-regexp) diff
13097 (calendar-move-hook nil)
13098 (calendar-view-holidays-initially-flag nil)
13099 (view-calendar-holidays-initially nil)
13100 (calendar-view-diary-initially-flag nil)
13101 (view-diary-entries-initially nil))
13102 (if (or (org-at-timestamp-p)
13103 (save-excursion
13104 (beginning-of-line 1)
13105 (looking-at (concat ".*" tsr))))
13106 (let ((d1 (time-to-days (current-time)))
13107 (d2 (time-to-days
13108 (org-time-string-to-time (match-string 1)))))
13109 (setq diff (- d2 d1))))
13110 (calendar)
13111 (calendar-goto-today)
13112 (if (and diff (not arg)) (calendar-forward-day diff))))
13114 (defun org-get-date-from-calendar ()
13115 "Return a list (month day year) of date at point in calendar."
13116 (with-current-buffer "*Calendar*"
13117 (save-match-data
13118 (calendar-cursor-to-date))))
13120 (defun org-date-from-calendar ()
13121 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13122 If there is already a time stamp at the cursor position, update it."
13123 (interactive)
13124 (if (org-at-timestamp-p t)
13125 (org-timestamp-change 0 'calendar)
13126 (let ((cal-date (org-get-date-from-calendar)))
13127 (org-insert-time-stamp
13128 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13130 (defun org-minutes-to-hh:mm-string (m)
13131 "Compute H:MM from a number of minutes."
13132 (let ((h (/ m 60)))
13133 (setq m (- m (* 60 h)))
13134 (format org-time-clocksum-format h m)))
13136 (defun org-hh:mm-string-to-minutes (s)
13137 "Convert a string H:MM to a number of minutes.
13138 If the string is just a number, interprete it as minutes.
13139 In fact, the first hh:mm or number in the string will be taken,
13140 there can be extra stuff in the string.
13141 If no number is found, the return value is 0."
13142 (cond
13143 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13144 (+ (* (string-to-number (match-string 1 s)) 60)
13145 (string-to-number (match-string 2 s))))
13146 ((string-match "\\([0-9]+\\)" s)
13147 (string-to-number (match-string 1 s)))
13148 (t 0)))
13150 ;;;; Files
13152 (defun org-save-all-org-buffers ()
13153 "Save all Org-mode buffers without user confirmation."
13154 (interactive)
13155 (message "Saving all Org-mode buffers...")
13156 (save-some-buffers t 'org-mode-p)
13157 (when (featurep 'org-id) (org-id-locations-save))
13158 (message "Saving all Org-mode buffers... done"))
13160 (defun org-revert-all-org-buffers ()
13161 "Revert all Org-mode buffers.
13162 Prompt for confirmation when there are unsaved changes.
13163 Be sure you know what you are doing before letting this function
13164 overwrite your changes.
13166 This function is useful in a setup where one tracks org files
13167 with a version control system, to revert on one machine after pulling
13168 changes from another. I believe the procedure must be like this:
13170 1. M-x org-save-all-org-buffers
13171 2. Pull changes from the other machine, resolve conflicts
13172 3. M-x org-revert-all-org-buffers"
13173 (interactive)
13174 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13175 (error "Abort"))
13176 (save-excursion
13177 (save-window-excursion
13178 (mapc
13179 (lambda (b)
13180 (when (and (with-current-buffer b (org-mode-p))
13181 (with-current-buffer b buffer-file-name))
13182 (switch-to-buffer b)
13183 (revert-buffer t 'no-confirm)))
13184 (buffer-list))
13185 (when (and (featurep 'org-id) org-id-track-globally)
13186 (org-id-locations-load)))))
13188 ;;;; Agenda files
13190 ;;;###autoload
13191 (defun org-iswitchb (&optional arg)
13192 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13193 With a prefix argument, restrict available to files.
13194 With two prefix arguments, restrict available buffers to agenda files.
13196 Due to some yet unresolved reason, the global function
13197 `iswitchb-mode' needs to be active for this function to work."
13198 (interactive "P")
13199 (require 'iswitchb)
13200 (let ((enabled iswitchb-mode) blist)
13201 (or enabled (iswitchb-mode 1))
13202 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13203 ((equal arg '(16)) (org-buffer-list 'agenda))
13204 (t (org-buffer-list))))
13205 (unwind-protect
13206 (let ((iswitchb-make-buflist-hook
13207 (lambda ()
13208 (setq iswitchb-temp-buflist
13209 (mapcar 'buffer-name blist)))))
13210 (switch-to-buffer
13211 (iswitchb-read-buffer
13212 "Switch-to: " nil t))
13213 (or enabled (iswitchb-mode -1))))))
13215 ;;;###autoload
13216 (defun org-ido-switchb (&optional arg)
13217 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
13218 With a prefix argument, restrict available to files.
13219 With two prefix arguments, restrict available buffers to agenda files."
13220 (interactive "P")
13221 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13222 ((equal arg '(16)) (org-buffer-list 'agenda))
13223 (t (org-buffer-list)))))
13224 (switch-to-buffer
13225 (org-ido-completing-read "Org buffer: "
13226 (mapcar 'list (mapcar 'buffer-name blist))
13227 nil t))))
13229 (defun org-buffer-list (&optional predicate exclude-tmp)
13230 "Return a list of Org buffers.
13231 PREDICATE can be `export', `files' or `agenda'.
13233 export restrict the list to Export buffers.
13234 files restrict the list to buffers visiting Org files.
13235 agenda restrict the list to buffers visiting agenda files.
13237 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13238 (let* ((bfn nil)
13239 (agenda-files (and (eq predicate 'agenda)
13240 (mapcar 'file-truename (org-agenda-files t))))
13241 (filter
13242 (cond
13243 ((eq predicate 'files)
13244 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13245 ((eq predicate 'export)
13246 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13247 ((eq predicate 'agenda)
13248 (lambda (b)
13249 (with-current-buffer b
13250 (and (eq major-mode 'org-mode)
13251 (setq bfn (buffer-file-name b))
13252 (member (file-truename bfn) agenda-files)))))
13253 (t (lambda (b) (with-current-buffer b
13254 (or (eq major-mode 'org-mode)
13255 (string-match "\*Org .*Export"
13256 (buffer-name b)))))))))
13257 (delq nil
13258 (mapcar
13259 (lambda(b)
13260 (if (and (funcall filter b)
13261 (or (not exclude-tmp)
13262 (not (string-match "tmp" (buffer-name b)))))
13264 nil))
13265 (buffer-list)))))
13267 (defun org-agenda-files (&optional unrestricted archives)
13268 "Get the list of agenda files.
13269 Optional UNRESTRICTED means return the full list even if a restriction
13270 is currently in place.
13271 When ARCHIVES is t, include all archive files hat are really being
13272 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13273 `org-agenda-archives-mode' is t."
13274 (let ((files
13275 (cond
13276 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13277 ((stringp org-agenda-files) (org-read-agenda-file-list))
13278 ((listp org-agenda-files) org-agenda-files)
13279 (t (error "Invalid value of `org-agenda-files'")))))
13280 (setq files (apply 'append
13281 (mapcar (lambda (f)
13282 (if (file-directory-p f)
13283 (directory-files
13284 f t org-agenda-file-regexp)
13285 (list f)))
13286 files)))
13287 (when org-agenda-skip-unavailable-files
13288 (setq files (delq nil
13289 (mapcar (function
13290 (lambda (file)
13291 (and (file-readable-p file) file)))
13292 files))))
13293 (when (or (eq archives t)
13294 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13295 (setq files (org-add-archive-files files)))
13296 files))
13298 (defun org-edit-agenda-file-list ()
13299 "Edit the list of agenda files.
13300 Depending on setup, this either uses customize to edit the variable
13301 `org-agenda-files', or it visits the file that is holding the list. In the
13302 latter case, the buffer is set up in a way that saving it automatically kills
13303 the buffer and restores the previous window configuration."
13304 (interactive)
13305 (if (stringp org-agenda-files)
13306 (let ((cw (current-window-configuration)))
13307 (find-file org-agenda-files)
13308 (org-set-local 'org-window-configuration cw)
13309 (org-add-hook 'after-save-hook
13310 (lambda ()
13311 (set-window-configuration
13312 (prog1 org-window-configuration
13313 (kill-buffer (current-buffer))))
13314 (org-install-agenda-files-menu)
13315 (message "New agenda file list installed"))
13316 nil 'local)
13317 (message "%s" (substitute-command-keys
13318 "Edit list and finish with \\[save-buffer]")))
13319 (customize-variable 'org-agenda-files)))
13321 (defun org-store-new-agenda-file-list (list)
13322 "Set new value for the agenda file list and save it correctly."
13323 (if (stringp org-agenda-files)
13324 (let ((f org-agenda-files) b)
13325 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13326 (with-temp-file f
13327 (insert (mapconcat 'identity list "\n") "\n")))
13328 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13329 (setq org-agenda-files list)
13330 (customize-save-variable 'org-agenda-files org-agenda-files))))
13332 (defun org-read-agenda-file-list ()
13333 "Read the list of agenda files from a file."
13334 (when (file-directory-p org-agenda-files)
13335 (error "`org-agenda-files' cannot be a single directory"))
13336 (when (stringp org-agenda-files)
13337 (with-temp-buffer
13338 (insert-file-contents org-agenda-files)
13339 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13342 ;;;###autoload
13343 (defun org-cycle-agenda-files ()
13344 "Cycle through the files in `org-agenda-files'.
13345 If the current buffer visits an agenda file, find the next one in the list.
13346 If the current buffer does not, find the first agenda file."
13347 (interactive)
13348 (let* ((fs (org-agenda-files t))
13349 (files (append fs (list (car fs))))
13350 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13351 file)
13352 (unless files (error "No agenda files"))
13353 (catch 'exit
13354 (while (setq file (pop files))
13355 (if (equal (file-truename file) tcf)
13356 (when (car files)
13357 (find-file (car files))
13358 (throw 'exit t))))
13359 (find-file (car fs)))
13360 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13362 (defun org-agenda-file-to-front (&optional to-end)
13363 "Move/add the current file to the top of the agenda file list.
13364 If the file is not present in the list, it is added to the front. If it is
13365 present, it is moved there. With optional argument TO-END, add/move to the
13366 end of the list."
13367 (interactive "P")
13368 (let ((org-agenda-skip-unavailable-files nil)
13369 (file-alist (mapcar (lambda (x)
13370 (cons (file-truename x) x))
13371 (org-agenda-files t)))
13372 (ctf (file-truename buffer-file-name))
13373 x had)
13374 (setq x (assoc ctf file-alist) had x)
13376 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13377 (if to-end
13378 (setq file-alist (append (delq x file-alist) (list x)))
13379 (setq file-alist (cons x (delq x file-alist))))
13380 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13381 (org-install-agenda-files-menu)
13382 (message "File %s to %s of agenda file list"
13383 (if had "moved" "added") (if to-end "end" "front"))))
13385 (defun org-remove-file (&optional file)
13386 "Remove current file from the list of files in variable `org-agenda-files'.
13387 These are the files which are being checked for agenda entries.
13388 Optional argument FILE means, use this file instead of the current."
13389 (interactive)
13390 (let* ((org-agenda-skip-unavailable-files nil)
13391 (file (or file buffer-file-name))
13392 (true-file (file-truename file))
13393 (afile (abbreviate-file-name file))
13394 (files (delq nil (mapcar
13395 (lambda (x)
13396 (if (equal true-file
13397 (file-truename x))
13398 nil x))
13399 (org-agenda-files t)))))
13400 (if (not (= (length files) (length (org-agenda-files t))))
13401 (progn
13402 (org-store-new-agenda-file-list files)
13403 (org-install-agenda-files-menu)
13404 (message "Removed file: %s" afile))
13405 (message "File was not in list: %s (not removed)" afile))))
13407 (defun org-file-menu-entry (file)
13408 (vector file (list 'find-file file) t))
13410 (defun org-check-agenda-file (file)
13411 "Make sure FILE exists. If not, ask user what to do."
13412 (when (not (file-exists-p file))
13413 (message "non-existent file %s. [R]emove from list or [A]bort?"
13414 (abbreviate-file-name file))
13415 (let ((r (downcase (read-char-exclusive))))
13416 (cond
13417 ((equal r ?r)
13418 (org-remove-file file)
13419 (throw 'nextfile t))
13420 (t (error "Abort"))))))
13422 (defun org-get-agenda-file-buffer (file)
13423 "Get a buffer visiting FILE. If the buffer needs to be created, add
13424 it to the list of buffers which might be released later."
13425 (let ((buf (org-find-base-buffer-visiting file)))
13426 (if buf
13427 buf ; just return it
13428 ;; Make a new buffer and remember it
13429 (setq buf (find-file-noselect file))
13430 (if buf (push buf org-agenda-new-buffers))
13431 buf)))
13433 (defun org-release-buffers (blist)
13434 "Release all buffers in list, asking the user for confirmation when needed.
13435 When a buffer is unmodified, it is just killed. When modified, it is saved
13436 \(if the user agrees) and then killed."
13437 (let (buf file)
13438 (while (setq buf (pop blist))
13439 (setq file (buffer-file-name buf))
13440 (when (and (buffer-modified-p buf)
13441 file
13442 (y-or-n-p (format "Save file %s? " file)))
13443 (with-current-buffer buf (save-buffer)))
13444 (kill-buffer buf))))
13446 (defun org-prepare-agenda-buffers (files)
13447 "Create buffers for all agenda files, protect archived trees and comments."
13448 (interactive)
13449 (let ((pa '(:org-archived t))
13450 (pc '(:org-comment t))
13451 (pall '(:org-archived t :org-comment t))
13452 (inhibit-read-only t)
13453 (rea (concat ":" org-archive-tag ":"))
13454 bmp file re)
13455 (save-excursion
13456 (save-restriction
13457 (while (setq file (pop files))
13458 (catch 'nextfile
13459 (if (bufferp file)
13460 (set-buffer file)
13461 (org-check-agenda-file file)
13462 (set-buffer (org-get-agenda-file-buffer file)))
13463 (widen)
13464 (setq bmp (buffer-modified-p))
13465 (org-refresh-category-properties)
13466 (setq org-todo-keywords-for-agenda
13467 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13468 (setq org-done-keywords-for-agenda
13469 (append org-done-keywords-for-agenda org-done-keywords))
13470 (setq org-todo-keyword-alist-for-agenda
13471 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13472 (setq org-tag-alist-for-agenda
13473 (append org-tag-alist-for-agenda org-tag-alist))
13475 (save-excursion
13476 (remove-text-properties (point-min) (point-max) pall)
13477 (when org-agenda-skip-archived-trees
13478 (goto-char (point-min))
13479 (while (re-search-forward rea nil t)
13480 (if (org-on-heading-p t)
13481 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13482 (goto-char (point-min))
13483 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13484 (while (re-search-forward re nil t)
13485 (add-text-properties
13486 (match-beginning 0) (org-end-of-subtree t) pc)))
13487 (set-buffer-modified-p bmp)))))
13488 (setq org-todo-keyword-alist-for-agenda
13489 (org-uniquify org-todo-keyword-alist-for-agenda)
13490 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13492 ;;;; Embedded LaTeX
13494 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13495 "Keymap for the minor `org-cdlatex-mode'.")
13497 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13498 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13499 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13500 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13501 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13503 (defvar org-cdlatex-texmathp-advice-is-done nil
13504 "Flag remembering if we have applied the advice to texmathp already.")
13506 (define-minor-mode org-cdlatex-mode
13507 "Toggle the minor `org-cdlatex-mode'.
13508 This mode supports entering LaTeX environment and math in LaTeX fragments
13509 in Org-mode.
13510 \\{org-cdlatex-mode-map}"
13511 nil " OCDL" nil
13512 (when org-cdlatex-mode (require 'cdlatex))
13513 (unless org-cdlatex-texmathp-advice-is-done
13514 (setq org-cdlatex-texmathp-advice-is-done t)
13515 (defadvice texmathp (around org-math-always-on activate)
13516 "Always return t in org-mode buffers.
13517 This is because we want to insert math symbols without dollars even outside
13518 the LaTeX math segments. If Orgmode thinks that point is actually inside
13519 an embedded LaTeX fragment, let texmathp do its job.
13520 \\[org-cdlatex-mode-map]"
13521 (interactive)
13522 (let (p)
13523 (cond
13524 ((not (org-mode-p)) ad-do-it)
13525 ((eq this-command 'cdlatex-math-symbol)
13526 (setq ad-return-value t
13527 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13529 (let ((p (org-inside-LaTeX-fragment-p)))
13530 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13531 (setq ad-return-value t
13532 texmathp-why '("Org-mode embedded math" . 0))
13533 (if p ad-do-it)))))))))
13535 (defun turn-on-org-cdlatex ()
13536 "Unconditionally turn on `org-cdlatex-mode'."
13537 (org-cdlatex-mode 1))
13539 (defun org-inside-LaTeX-fragment-p ()
13540 "Test if point is inside a LaTeX fragment.
13541 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13542 sequence appearing also before point.
13543 Even though the matchers for math are configurable, this function assumes
13544 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13545 delimiters are skipped when they have been removed by customization.
13546 The return value is nil, or a cons cell with the delimiter and
13547 and the position of this delimiter.
13549 This function does a reasonably good job, but can locally be fooled by
13550 for example currency specifications. For example it will assume being in
13551 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13552 fragments that are properly closed, but during editing, we have to live
13553 with the uncertainty caused by missing closing delimiters. This function
13554 looks only before point, not after."
13555 (catch 'exit
13556 (let ((pos (point))
13557 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13558 (lim (progn
13559 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13560 (point)))
13561 dd-on str (start 0) m re)
13562 (goto-char pos)
13563 (when dodollar
13564 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13565 re (nth 1 (assoc "$" org-latex-regexps)))
13566 (while (string-match re str start)
13567 (cond
13568 ((= (match-end 0) (length str))
13569 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13570 ((= (match-end 0) (- (length str) 5))
13571 (throw 'exit nil))
13572 (t (setq start (match-end 0))))))
13573 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13574 (goto-char pos)
13575 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13576 (and (match-beginning 2) (throw 'exit nil))
13577 ;; count $$
13578 (while (re-search-backward "\\$\\$" lim t)
13579 (setq dd-on (not dd-on)))
13580 (goto-char pos)
13581 (if dd-on (cons "$$" m))))))
13584 (defun org-try-cdlatex-tab ()
13585 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13586 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13587 - inside a LaTeX fragment, or
13588 - after the first word in a line, where an abbreviation expansion could
13589 insert a LaTeX environment."
13590 (when org-cdlatex-mode
13591 (cond
13592 ((save-excursion
13593 (skip-chars-backward "a-zA-Z0-9*")
13594 (skip-chars-backward " \t")
13595 (bolp))
13596 (cdlatex-tab) t)
13597 ((org-inside-LaTeX-fragment-p)
13598 (cdlatex-tab) t)
13599 (t nil))))
13601 (defun org-cdlatex-underscore-caret (&optional arg)
13602 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13603 Revert to the normal definition outside of these fragments."
13604 (interactive "P")
13605 (if (org-inside-LaTeX-fragment-p)
13606 (call-interactively 'cdlatex-sub-superscript)
13607 (let (org-cdlatex-mode)
13608 (call-interactively (key-binding (vector last-input-event))))))
13610 (defun org-cdlatex-math-modify (&optional arg)
13611 "Execute `cdlatex-math-modify' in LaTeX fragments.
13612 Revert to the normal definition outside of these fragments."
13613 (interactive "P")
13614 (if (org-inside-LaTeX-fragment-p)
13615 (call-interactively 'cdlatex-math-modify)
13616 (let (org-cdlatex-mode)
13617 (call-interactively (key-binding (vector last-input-event))))))
13619 (defvar org-latex-fragment-image-overlays nil
13620 "List of overlays carrying the images of latex fragments.")
13621 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13623 (defun org-remove-latex-fragment-image-overlays ()
13624 "Remove all overlays with LaTeX fragment images in current buffer."
13625 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13626 (setq org-latex-fragment-image-overlays nil))
13628 (defun org-preview-latex-fragment (&optional subtree)
13629 "Preview the LaTeX fragment at point, or all locally or globally.
13630 If the cursor is in a LaTeX fragment, create the image and overlay
13631 it over the source code. If there is no fragment at point, display
13632 all fragments in the current text, from one headline to the next. With
13633 prefix SUBTREE, display all fragments in the current subtree. With a
13634 double prefix `C-u C-u', or when the cursor is before the first headline,
13635 display all fragments in the buffer.
13636 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13637 (interactive "P")
13638 (org-remove-latex-fragment-image-overlays)
13639 (save-excursion
13640 (save-restriction
13641 (let (beg end at msg)
13642 (cond
13643 ((or (equal subtree '(16))
13644 (not (save-excursion
13645 (re-search-backward (concat "^" outline-regexp) nil t))))
13646 (setq beg (point-min) end (point-max)
13647 msg "Creating images for buffer...%s"))
13648 ((equal subtree '(4))
13649 (org-back-to-heading)
13650 (setq beg (point) end (org-end-of-subtree t)
13651 msg "Creating images for subtree...%s"))
13653 (if (setq at (org-inside-LaTeX-fragment-p))
13654 (goto-char (max (point-min) (- (cdr at) 2)))
13655 (org-back-to-heading))
13656 (setq beg (point) end (progn (outline-next-heading) (point))
13657 msg (if at "Creating image...%s"
13658 "Creating images for entry...%s"))))
13659 (message msg "")
13660 (narrow-to-region beg end)
13661 (goto-char beg)
13662 (org-format-latex
13663 (concat "ltxpng/" (file-name-sans-extension
13664 (file-name-nondirectory
13665 buffer-file-name)))
13666 default-directory 'overlays msg at 'forbuffer)
13667 (message msg "done. Use `C-c C-c' to remove images.")))))
13669 (defvar org-latex-regexps
13670 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13671 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13672 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13673 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13674 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13675 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13676 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13677 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13678 "Regular expressions for matching embedded LaTeX.")
13680 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13681 "Replace LaTeX fragments with links to an image, and produce images."
13682 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13683 (let* ((prefixnodir (file-name-nondirectory prefix))
13684 (absprefix (expand-file-name prefix dir))
13685 (todir (file-name-directory absprefix))
13686 (opt org-format-latex-options)
13687 (matchers (plist-get opt :matchers))
13688 (re-list org-latex-regexps)
13689 (cnt 0) txt link beg end re e checkdir
13690 executables-checked
13691 m n block linkfile movefile ov)
13692 ;; Check if there are old images files with this prefix, and remove them
13693 (when (file-directory-p todir)
13694 (mapc 'delete-file
13695 (directory-files
13696 todir 'full
13697 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13698 ;; Check the different regular expressions
13699 (while (setq e (pop re-list))
13700 (setq m (car e) re (nth 1 e) n (nth 2 e)
13701 block (if (nth 3 e) "\n\n" ""))
13702 (when (member m matchers)
13703 (goto-char (point-min))
13704 (while (re-search-forward re nil t)
13705 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13706 (not (get-text-property (match-beginning n)
13707 'org-protected)))
13708 (setq txt (match-string n)
13709 beg (match-beginning n) end (match-end n)
13710 cnt (1+ cnt)
13711 linkfile (format "%s_%04d.png" prefix cnt)
13712 movefile (format "%s_%04d.png" absprefix cnt)
13713 link (concat block "[[file:" linkfile "]]" block))
13714 (if msg (message msg cnt))
13715 (goto-char beg)
13716 (unless checkdir ; make sure the directory exists
13717 (setq checkdir t)
13718 (or (file-directory-p todir) (make-directory todir)))
13720 (unless executables-checked
13721 (org-check-external-command
13722 "latex" "needed to convert LaTeX fragments to images")
13723 (org-check-external-command
13724 "dvipng" "needed to convert LaTeX fragments to images")
13725 (setq executables-checked t))
13727 (org-create-formula-image
13728 txt movefile opt forbuffer)
13729 (if overlays
13730 (progn
13731 (setq ov (org-make-overlay beg end))
13732 (if (featurep 'xemacs)
13733 (progn
13734 (org-overlay-put ov 'invisible t)
13735 (org-overlay-put
13736 ov 'end-glyph
13737 (make-glyph (vector 'png :file movefile))))
13738 (org-overlay-put
13739 ov 'display
13740 (list 'image :type 'png :file movefile :ascent 'center)))
13741 (push ov org-latex-fragment-image-overlays)
13742 (goto-char end))
13743 (delete-region beg end)
13744 (insert link))))))))
13746 ;; This function borrows from Ganesh Swami's latex2png.el
13747 (defun org-create-formula-image (string tofile options buffer)
13748 (let* ((tmpdir (if (featurep 'xemacs)
13749 (temp-directory)
13750 temporary-file-directory))
13751 (texfilebase (make-temp-name
13752 (expand-file-name "orgtex" tmpdir)))
13753 (texfile (concat texfilebase ".tex"))
13754 (dvifile (concat texfilebase ".dvi"))
13755 (pngfile (concat texfilebase ".png"))
13756 (fnh (if (featurep 'xemacs)
13757 (font-height (get-face-font 'default))
13758 (face-attribute 'default :height nil)))
13759 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13760 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13761 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13762 "Black"))
13763 (bg (or (plist-get options (if buffer :background :html-background))
13764 "Transparent")))
13765 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13766 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13767 (with-temp-file texfile
13768 (insert org-format-latex-header
13769 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13770 (let ((dir default-directory))
13771 (condition-case nil
13772 (progn
13773 (cd tmpdir)
13774 (call-process "latex" nil nil nil texfile))
13775 (error nil))
13776 (cd dir))
13777 (if (not (file-exists-p dvifile))
13778 (progn (message "Failed to create dvi file from %s" texfile) nil)
13779 (condition-case nil
13780 (call-process "dvipng" nil nil nil
13781 "-E" "-fg" fg "-bg" bg
13782 "-D" dpi
13783 ;;"-x" scale "-y" scale
13784 "-T" "tight"
13785 "-o" pngfile
13786 dvifile)
13787 (error nil))
13788 (if (not (file-exists-p pngfile))
13789 (progn (message "Failed to create png file from %s" texfile) nil)
13790 ;; Use the requested file name and clean up
13791 (copy-file pngfile tofile 'replace)
13792 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13793 (delete-file (concat texfilebase e)))
13794 pngfile))))
13796 (defun org-dvipng-color (attr)
13797 "Return an rgb color specification for dvipng."
13798 (apply 'format "rgb %s %s %s"
13799 (mapcar 'org-normalize-color
13800 (color-values (face-attribute 'default attr nil)))))
13802 (defun org-normalize-color (value)
13803 "Return string to be used as color value for an RGB component."
13804 (format "%g" (/ value 65535.0)))
13806 ;;;; Key bindings
13808 ;; Make `C-c C-x' a prefix key
13809 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13811 ;; TAB key with modifiers
13812 (org-defkey org-mode-map "\C-i" 'org-cycle)
13813 (org-defkey org-mode-map [(tab)] 'org-cycle)
13814 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13815 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13816 (org-defkey org-mode-map "\M-\t" 'org-complete)
13817 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13818 ;; The following line is necessary under Suse GNU/Linux
13819 (unless (featurep 'xemacs)
13820 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13821 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13822 (define-key org-mode-map [backtab] 'org-shifttab)
13824 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13825 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13826 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13828 ;; Cursor keys with modifiers
13829 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13830 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13831 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13832 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13834 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13835 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13836 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13837 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13839 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13840 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13841 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13842 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13844 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13845 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13847 ;;; Extra keys for tty access.
13848 ;; We only set them when really needed because otherwise the
13849 ;; menus don't show the simple keys
13851 (when (or org-use-extra-keys
13852 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13853 (not window-system))
13854 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13855 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13856 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13857 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13858 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13859 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13860 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13861 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13862 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13863 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13864 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13865 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13866 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13867 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13868 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13869 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13870 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13871 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13872 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13873 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13874 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13875 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
13876 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
13877 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
13878 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
13879 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
13880 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
13881 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
13883 ;; All the other keys
13885 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13886 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13887 (if (boundp 'narrow-map)
13888 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13889 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13890 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13891 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13892 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13893 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13894 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13895 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13896 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13897 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13898 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13899 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13900 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13901 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13902 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13903 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13904 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13905 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13906 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13907 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13908 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13909 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13910 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13911 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13912 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13913 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13914 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13915 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13916 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13917 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13918 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13919 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13920 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13921 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13922 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13923 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13924 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13925 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13926 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13927 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13928 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13929 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13930 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13931 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13932 (org-defkey org-mode-map "\C-c^" 'org-sort)
13933 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13934 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13935 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13936 (org-defkey org-mode-map "\C-m" 'org-return)
13937 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13938 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13939 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13940 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13941 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13942 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13943 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13944 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13945 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13946 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13947 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13948 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13949 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13950 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13951 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13952 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13953 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13955 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13956 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13957 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13958 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13960 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13961 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13962 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13963 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13964 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13965 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13966 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13967 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13968 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13969 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13970 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13971 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13972 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13974 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13975 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13976 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13977 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13979 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13981 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
13983 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
13984 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
13986 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
13989 (when (featurep 'xemacs)
13990 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13993 (defvar org-self-insert-command-undo-counter 0)
13995 (defvar org-table-auto-blank-field) ; defined in org-table.el
13996 (defun org-self-insert-command (N)
13997 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13998 If the cursor is in a table looking at whitespace, the whitespace is
13999 overwritten, and the table is not marked as requiring realignment."
14000 (interactive "p")
14001 (if (and
14002 (org-table-p)
14003 (progn
14004 ;; check if we blank the field, and if that triggers align
14005 (and (featurep 'org-table) org-table-auto-blank-field
14006 (member last-command
14007 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14008 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14009 ;; got extra space, this field does not determine column width
14010 (let (org-table-may-need-update) (org-table-blank-field))
14011 ;; no extra space, this field may determine column width
14012 (org-table-blank-field)))
14014 (eq N 1)
14015 (looking-at "[^|\n]* |"))
14016 (let (org-table-may-need-update)
14017 (goto-char (1- (match-end 0)))
14018 (delete-backward-char 1)
14019 (goto-char (match-beginning 0))
14020 (self-insert-command N))
14021 (setq org-table-may-need-update t)
14022 (self-insert-command N)
14023 (org-fix-tags-on-the-fly)
14024 (if org-self-insert-cluster-for-undo
14025 (if (not (eq last-command 'org-self-insert-command))
14026 (setq org-self-insert-command-undo-counter 1)
14027 (if (>= org-self-insert-command-undo-counter 20)
14028 (setq org-self-insert-command-undo-counter 1)
14029 (and (> org-self-insert-command-undo-counter 0)
14030 buffer-undo-list
14031 (not (cadr buffer-undo-list)) ; remove nil entry
14032 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14033 (setq org-self-insert-command-undo-counter
14034 (1+ org-self-insert-command-undo-counter)))))))
14036 (defun org-fix-tags-on-the-fly ()
14037 (when (and (equal (char-after (point-at-bol)) ?*)
14038 (org-on-heading-p))
14039 (org-align-tags-here org-tags-column)))
14041 (defun org-delete-backward-char (N)
14042 "Like `delete-backward-char', insert whitespace at field end in tables.
14043 When deleting backwards, in tables this function will insert whitespace in
14044 front of the next \"|\" separator, to keep the table aligned. The table will
14045 still be marked for re-alignment if the field did fill the entire column,
14046 because, in this case the deletion might narrow the column."
14047 (interactive "p")
14048 (if (and (org-table-p)
14049 (eq N 1)
14050 (string-match "|" (buffer-substring (point-at-bol) (point)))
14051 (looking-at ".*?|"))
14052 (let ((pos (point))
14053 (noalign (looking-at "[^|\n\r]* |"))
14054 (c org-table-may-need-update))
14055 (backward-delete-char N)
14056 (skip-chars-forward "^|")
14057 (insert " ")
14058 (goto-char (1- pos))
14059 ;; noalign: if there were two spaces at the end, this field
14060 ;; does not determine the width of the column.
14061 (if noalign (setq org-table-may-need-update c)))
14062 (backward-delete-char N)
14063 (org-fix-tags-on-the-fly)))
14065 (defun org-delete-char (N)
14066 "Like `delete-char', but insert whitespace at field end in tables.
14067 When deleting characters, in tables this function will insert whitespace in
14068 front of the next \"|\" separator, to keep the table aligned. The table will
14069 still be marked for re-alignment if the field did fill the entire column,
14070 because, in this case the deletion might narrow the column."
14071 (interactive "p")
14072 (if (and (org-table-p)
14073 (not (bolp))
14074 (not (= (char-after) ?|))
14075 (eq N 1))
14076 (if (looking-at ".*?|")
14077 (let ((pos (point))
14078 (noalign (looking-at "[^|\n\r]* |"))
14079 (c org-table-may-need-update))
14080 (replace-match (concat
14081 (substring (match-string 0) 1 -1)
14082 " |"))
14083 (goto-char pos)
14084 ;; noalign: if there were two spaces at the end, this field
14085 ;; does not determine the width of the column.
14086 (if noalign (setq org-table-may-need-update c)))
14087 (delete-char N))
14088 (delete-char N)
14089 (org-fix-tags-on-the-fly)))
14091 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14092 (put 'org-self-insert-command 'delete-selection t)
14093 (put 'orgtbl-self-insert-command 'delete-selection t)
14094 (put 'org-delete-char 'delete-selection 'supersede)
14095 (put 'org-delete-backward-char 'delete-selection 'supersede)
14096 (put 'org-yank 'delete-selection 'yank)
14098 ;; Make `flyspell-mode' delay after some commands
14099 (put 'org-self-insert-command 'flyspell-delayed t)
14100 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14101 (put 'org-delete-char 'flyspell-delayed t)
14102 (put 'org-delete-backward-char 'flyspell-delayed t)
14104 ;; Make pabbrev-mode expand after org-mode commands
14105 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14106 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14108 ;; How to do this: Measure non-white length of current string
14109 ;; If equal to column width, we should realign.
14111 (defun org-remap (map &rest commands)
14112 "In MAP, remap the functions given in COMMANDS.
14113 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14114 (let (new old)
14115 (while commands
14116 (setq old (pop commands) new (pop commands))
14117 (if (fboundp 'command-remapping)
14118 (org-defkey map (vector 'remap old) new)
14119 (substitute-key-definition old new map global-map)))))
14121 (when (eq org-enable-table-editor 'optimized)
14122 ;; If the user wants maximum table support, we need to hijack
14123 ;; some standard editing functions
14124 (org-remap org-mode-map
14125 'self-insert-command 'org-self-insert-command
14126 'delete-char 'org-delete-char
14127 'delete-backward-char 'org-delete-backward-char)
14128 (org-defkey org-mode-map "|" 'org-force-self-insert))
14130 (defvar org-ctrl-c-ctrl-c-hook nil
14131 "Hook for functions attaching themselves to `C-c C-c'.
14132 This can be used to add additional functionality to the C-c C-c key which
14133 executes context-dependent commands.
14134 Each function will be called with no arguments. The function must check
14135 if the context is appropriate for it to act. If yes, it should do its
14136 thing and then return a non-nil value. If the context is wrong,
14137 just do nothing and return nil.")
14139 (defvar org-tab-first-hook nil
14140 "Hook for functions to attach themselves to TAB.
14141 See `org-ctrl-c-ctrl-c-hook' for more information.
14142 This hook runs as the first action when TAB is pressed, even before
14143 `org-cycle' messes around with the `outline-regexp' to cater for
14144 inline tasks and plain list item folding.
14145 If any function in this hook returns t, not other actions like table
14146 field motion visibility cycling will be done.")
14148 (defvar org-tab-after-check-for-table-hook nil
14149 "Hook for functions to attach themselves to TAB.
14150 See `org-ctrl-c-ctrl-c-hook' for more information.
14151 This hook runs after it has been established that the cursor is not in a
14152 table, but before checking if the cursor is in a headline or if global cycling
14153 should be done.
14154 If any function in this hook returns t, not other actions like visibility
14155 cycling will be done.")
14157 (defvar org-tab-after-check-for-cycling-hook nil
14158 "Hook for functions to attach themselves to TAB.
14159 See `org-ctrl-c-ctrl-c-hook' for more information.
14160 This hook runs after it has been established that not table field motion and
14161 not visibility should be done because of current context. This is probably
14162 the place where a package like yasnippets can hook in.")
14164 (defvar org-metaleft-hook nil
14165 "Hook for functions attaching themselves to `M-left'.
14166 See `org-ctrl-c-ctrl-c-hook' for more information.")
14167 (defvar org-metaright-hook nil
14168 "Hook for functions attaching themselves to `M-right'.
14169 See `org-ctrl-c-ctrl-c-hook' for more information.")
14170 (defvar org-metaup-hook nil
14171 "Hook for functions attaching themselves to `M-up'.
14172 See `org-ctrl-c-ctrl-c-hook' for more information.")
14173 (defvar org-metadown-hook nil
14174 "Hook for functions attaching themselves to `M-down'.
14175 See `org-ctrl-c-ctrl-c-hook' for more information.")
14176 (defvar org-shiftmetaleft-hook nil
14177 "Hook for functions attaching themselves to `M-S-left'.
14178 See `org-ctrl-c-ctrl-c-hook' for more information.")
14179 (defvar org-shiftmetaright-hook nil
14180 "Hook for functions attaching themselves to `M-S-right'.
14181 See `org-ctrl-c-ctrl-c-hook' for more information.")
14182 (defvar org-shiftmetaup-hook nil
14183 "Hook for functions attaching themselves to `M-S-up'.
14184 See `org-ctrl-c-ctrl-c-hook' for more information.")
14185 (defvar org-shiftmetadown-hook nil
14186 "Hook for functions attaching themselves to `M-S-down'.
14187 See `org-ctrl-c-ctrl-c-hook' for more information.")
14188 (defvar org-metareturn-hook nil
14189 "Hook for functions attaching themselves to `M-RET'.
14190 See `org-ctrl-c-ctrl-c-hook' for more information.")
14192 (defun org-modifier-cursor-error ()
14193 "Throw an error, a modified cursor command was applied in wrong context."
14194 (error "This command is active in special context like tables, headlines or items"))
14196 (defun org-shiftselect-error ()
14197 "Throw an error because Shift-Cursor command was applied in wrong context."
14198 (if (and (boundp 'shift-select-mode) shift-select-mode)
14199 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14200 (error "This command works only in special context like headlines or timestamps.")))
14202 (defun org-call-for-shift-select (cmd)
14203 (let ((this-command-keys-shift-translated t))
14204 (call-interactively cmd)))
14206 (defun org-shifttab (&optional arg)
14207 "Global visibility cycling or move to previous table field.
14208 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14209 on context.
14210 See the individual commands for more information."
14211 (interactive "P")
14212 (cond
14213 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14214 ((integerp arg)
14215 (message "Content view to level: %d" arg)
14216 (org-content (prefix-numeric-value arg))
14217 (setq org-cycle-global-status 'overview))
14218 (t (call-interactively 'org-global-cycle))))
14220 (defun org-shiftmetaleft ()
14221 "Promote subtree or delete table column.
14222 Calls `org-promote-subtree', `org-outdent-item',
14223 or `org-table-delete-column', depending on context.
14224 See the individual commands for more information."
14225 (interactive)
14226 (cond
14227 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14228 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14229 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14230 ((org-at-item-p) (call-interactively 'org-outdent-item))
14231 (t (org-modifier-cursor-error))))
14233 (defun org-shiftmetaright ()
14234 "Demote subtree or insert table column.
14235 Calls `org-demote-subtree', `org-indent-item',
14236 or `org-table-insert-column', depending on context.
14237 See the individual commands for more information."
14238 (interactive)
14239 (cond
14240 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14241 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14242 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14243 ((org-at-item-p) (call-interactively 'org-indent-item))
14244 (t (org-modifier-cursor-error))))
14246 (defun org-shiftmetaup (&optional arg)
14247 "Move subtree up or kill table row.
14248 Calls `org-move-subtree-up' or `org-table-kill-row' or
14249 `org-move-item-up' depending on context. See the individual commands
14250 for more information."
14251 (interactive "P")
14252 (cond
14253 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14254 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14255 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14256 ((org-at-item-p) (call-interactively 'org-move-item-up))
14257 (t (org-modifier-cursor-error))))
14259 (defun org-shiftmetadown (&optional arg)
14260 "Move subtree down or insert table row.
14261 Calls `org-move-subtree-down' or `org-table-insert-row' or
14262 `org-move-item-down', depending on context. See the individual
14263 commands for more information."
14264 (interactive "P")
14265 (cond
14266 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14267 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14268 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14269 ((org-at-item-p) (call-interactively 'org-move-item-down))
14270 (t (org-modifier-cursor-error))))
14272 (defun org-metaleft (&optional arg)
14273 "Promote heading or move table column to left.
14274 Calls `org-do-promote' or `org-table-move-column', depending on context.
14275 With no specific context, calls the Emacs default `backward-word'.
14276 See the individual commands for more information."
14277 (interactive "P")
14278 (cond
14279 ((run-hook-with-args-until-success 'org-metaleft-hook))
14280 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14281 ((or (org-on-heading-p)
14282 (and (org-region-active-p)
14283 (save-excursion
14284 (goto-char (region-beginning))
14285 (org-on-heading-p))))
14286 (call-interactively 'org-do-promote))
14287 ((or (org-at-item-p)
14288 (and (org-region-active-p)
14289 (save-excursion
14290 (goto-char (region-beginning))
14291 (org-at-item-p))))
14292 (call-interactively 'org-outdent-item))
14293 (t (call-interactively 'backward-word))))
14295 (defun org-metaright (&optional arg)
14296 "Demote subtree or move table column to right.
14297 Calls `org-do-demote' or `org-table-move-column', depending on context.
14298 With no specific context, calls the Emacs default `forward-word'.
14299 See the individual commands for more information."
14300 (interactive "P")
14301 (cond
14302 ((run-hook-with-args-until-success 'org-metaright-hook))
14303 ((org-at-table-p) (call-interactively 'org-table-move-column))
14304 ((or (org-on-heading-p)
14305 (and (org-region-active-p)
14306 (save-excursion
14307 (goto-char (region-beginning))
14308 (org-on-heading-p))))
14309 (call-interactively 'org-do-demote))
14310 ((or (org-at-item-p)
14311 (and (org-region-active-p)
14312 (save-excursion
14313 (goto-char (region-beginning))
14314 (org-at-item-p))))
14315 (call-interactively 'org-indent-item))
14316 (t (call-interactively 'forward-word))))
14318 (defun org-metaup (&optional arg)
14319 "Move subtree up or move table row up.
14320 Calls `org-move-subtree-up' or `org-table-move-row' or
14321 `org-move-item-up', depending on context. See the individual commands
14322 for more information."
14323 (interactive "P")
14324 (cond
14325 ((run-hook-with-args-until-success 'org-metaup-hook))
14326 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14327 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14328 ((org-at-item-p) (call-interactively 'org-move-item-up))
14329 (t (transpose-lines 1) (beginning-of-line -1))))
14331 (defun org-metadown (&optional arg)
14332 "Move subtree down or move table row down.
14333 Calls `org-move-subtree-down' or `org-table-move-row' or
14334 `org-move-item-down', depending on context. See the individual
14335 commands for more information."
14336 (interactive "P")
14337 (cond
14338 ((run-hook-with-args-until-success 'org-metadown-hook))
14339 ((org-at-table-p) (call-interactively 'org-table-move-row))
14340 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14341 ((org-at-item-p) (call-interactively 'org-move-item-down))
14342 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14344 (defun org-shiftup (&optional arg)
14345 "Increase item in timestamp or increase priority of current headline.
14346 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14347 depending on context. See the individual commands for more information."
14348 (interactive "P")
14349 (cond
14350 ((and org-support-shift-select (org-region-active-p))
14351 (org-call-for-shift-select 'previous-line))
14352 ((org-at-timestamp-p t)
14353 (call-interactively (if org-edit-timestamp-down-means-later
14354 'org-timestamp-down 'org-timestamp-up)))
14355 ((and (not (eq org-support-shift-select 'always))
14356 org-enable-priority-commands
14357 (org-on-heading-p))
14358 (call-interactively 'org-priority-up))
14359 ((and (not org-support-shift-select) (org-at-item-p))
14360 (call-interactively 'org-previous-item))
14361 ((org-clocktable-try-shift 'up arg))
14362 (org-support-shift-select
14363 (org-call-for-shift-select 'previous-line))
14364 (t (org-shiftselect-error))))
14366 (defun org-shiftdown (&optional arg)
14367 "Decrease item in timestamp or decrease priority of current headline.
14368 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14369 depending on context. See the individual commands for more information."
14370 (interactive "P")
14371 (cond
14372 ((and org-support-shift-select (org-region-active-p))
14373 (org-call-for-shift-select 'next-line))
14374 ((org-at-timestamp-p t)
14375 (call-interactively (if org-edit-timestamp-down-means-later
14376 'org-timestamp-up 'org-timestamp-down)))
14377 ((and (not (eq org-support-shift-select 'always))
14378 org-enable-priority-commands
14379 (org-on-heading-p))
14380 (call-interactively 'org-priority-down))
14381 ((and (not org-support-shift-select) (org-at-item-p))
14382 (call-interactively 'org-next-item))
14383 ((org-clocktable-try-shift 'down arg))
14384 (org-support-shift-select
14385 (org-call-for-shift-select 'next-line))
14386 (t (org-shiftselect-error))))
14388 (defun org-shiftright (&optional arg)
14389 "Cycle the thing at point or in the current line, depending on context.
14390 Depending on context, this does one of the following:
14392 - switch a timestamp at point one day into the future
14393 - on a headline, switch to the next TODO keyword.
14394 - on an item, switch entire list to the next bullet type
14395 - on a property line, switch to the next allowed value
14396 - on a clocktable definition line, move time block into the future"
14397 (interactive "P")
14398 (cond
14399 ((and org-support-shift-select (org-region-active-p))
14400 (org-call-for-shift-select 'forward-char))
14401 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14402 ((and (not (eq org-support-shift-select 'always))
14403 (org-on-heading-p))
14404 (let ((org-inhibit-logging
14405 (not org-treat-S-cursor-todo-selection-as-state-change))
14406 (org-inhibit-blocking
14407 (not org-treat-S-cursor-todo-selection-as-state-change)))
14408 (org-call-with-arg 'org-todo 'right)))
14409 ((or (and org-support-shift-select
14410 (not (eq org-support-shift-select 'always))
14411 (org-at-item-bullet-p))
14412 (and (not org-support-shift-select) (org-at-item-p)))
14413 (org-call-with-arg 'org-cycle-list-bullet nil))
14414 ((and (not (eq org-support-shift-select 'always))
14415 (org-at-property-p))
14416 (call-interactively 'org-property-next-allowed-value))
14417 ((org-clocktable-try-shift 'right arg))
14418 (org-support-shift-select
14419 (org-call-for-shift-select 'forward-char))
14420 (t (org-shiftselect-error))))
14422 (defun org-shiftleft (&optional arg)
14423 "Cycle the thing at point or in the current line, depending on context.
14424 Depending on context, this does one of the following:
14426 - switch a timestamp at point one day into the past
14427 - on a headline, switch to the previous TODO keyword.
14428 - on an item, switch entire list to the previous bullet type
14429 - on a property line, switch to the previous allowed value
14430 - on a clocktable definition line, move time block into the past"
14431 (interactive "P")
14432 (cond
14433 ((and org-support-shift-select (org-region-active-p))
14434 (org-call-for-shift-select 'backward-char))
14435 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14436 ((and (not (eq org-support-shift-select 'always))
14437 (org-on-heading-p))
14438 (let ((org-inhibit-logging
14439 (not org-treat-S-cursor-todo-selection-as-state-change))
14440 (org-inhibit-blocking
14441 (not org-treat-S-cursor-todo-selection-as-state-change)))
14442 (org-call-with-arg 'org-todo 'left)))
14443 ((or (and org-support-shift-select
14444 (not (eq org-support-shift-select 'always))
14445 (org-at-item-bullet-p))
14446 (and (not org-support-shift-select) (org-at-item-p)))
14447 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14448 ((and (not (eq org-support-shift-select 'always))
14449 (org-at-property-p))
14450 (call-interactively 'org-property-previous-allowed-value))
14451 ((org-clocktable-try-shift 'left arg))
14452 (org-support-shift-select
14453 (org-call-for-shift-select 'backward-char))
14454 (t (org-shiftselect-error))))
14456 (defun org-shiftcontrolright ()
14457 "Switch to next TODO set."
14458 (interactive)
14459 (cond
14460 ((and org-support-shift-select (org-region-active-p))
14461 (org-call-for-shift-select 'forward-word))
14462 ((and (not (eq org-support-shift-select 'always))
14463 (org-on-heading-p))
14464 (org-call-with-arg 'org-todo 'nextset))
14465 (org-support-shift-select
14466 (org-call-for-shift-select 'forward-word))
14467 (t (org-shiftselect-error))))
14469 (defun org-shiftcontrolleft ()
14470 "Switch to previous TODO set."
14471 (interactive)
14472 (cond
14473 ((and org-support-shift-select (org-region-active-p))
14474 (org-call-for-shift-select 'backward-word))
14475 ((and (not (eq org-support-shift-select 'always))
14476 (org-on-heading-p))
14477 (org-call-with-arg 'org-todo 'previousset))
14478 (org-support-shift-select
14479 (org-call-for-shift-select 'backward-word))
14480 (t (org-shiftselect-error))))
14482 (defun org-ctrl-c-ret ()
14483 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14484 (interactive)
14485 (cond
14486 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14487 (t (call-interactively 'org-insert-heading))))
14489 (defun org-copy-special ()
14490 "Copy region in table or copy current subtree.
14491 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14492 See the individual commands for more information."
14493 (interactive)
14494 (call-interactively
14495 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14497 (defun org-cut-special ()
14498 "Cut region in table or cut current subtree.
14499 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14500 See the individual commands for more information."
14501 (interactive)
14502 (call-interactively
14503 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14505 (defun org-paste-special (arg)
14506 "Paste rectangular region into table, or past subtree relative to level.
14507 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14508 See the individual commands for more information."
14509 (interactive "P")
14510 (if (org-at-table-p)
14511 (org-table-paste-rectangle)
14512 (org-paste-subtree arg)))
14514 (defun org-edit-special ()
14515 "Call a special editor for the stuff at point.
14516 When at a table, call the formula editor with `org-table-edit-formulas'.
14517 When at the first line of an src example, call `org-edit-src-code'.
14518 When in an #+include line, visit the include file. Otherwise call
14519 `ffap' to visit the file at point."
14520 (interactive)
14521 (cond
14522 ((org-at-table-p)
14523 (call-interactively 'org-table-edit-formulas))
14524 ((save-excursion
14525 (beginning-of-line 1)
14526 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14527 (find-file (org-trim (match-string 1))))
14528 ((org-edit-src-code))
14529 ((org-edit-fixed-width-region))
14530 (t (call-interactively 'ffap))))
14533 (defun org-ctrl-c-ctrl-c (&optional arg)
14534 "Set tags in headline, or update according to changed information at point.
14536 This command does many different things, depending on context:
14538 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14539 this is what we do.
14541 - If the cursor is in a headline, prompt for tags and insert them
14542 into the current line, aligned to `org-tags-column'. When called
14543 with prefix arg, realign all tags in the current buffer.
14545 - If the cursor is in one of the special #+KEYWORD lines, this
14546 triggers scanning the buffer for these lines and updating the
14547 information.
14549 - If the cursor is inside a table, realign the table. This command
14550 works even if the automatic table editor has been turned off.
14552 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14553 the entire table.
14555 - If the cursor is at a footnote reference or definition, jump to
14556 the corresponding definition or references, respectively.
14558 - If the cursor is a the beginning of a dynamic block, update it.
14560 - If the cursor is inside a table created by the table.el package,
14561 activate that table.
14563 - If the current buffer is a remember buffer, close note and file
14564 it. A prefix argument of 1 files to the default location
14565 without further interaction. A prefix argument of 2 files to
14566 the currently clocking task.
14568 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14569 links in this buffer.
14571 - If the cursor is on a numbered item in a plain list, renumber the
14572 ordered list.
14574 - If the cursor is on a checkbox, toggle it."
14575 (interactive "P")
14576 (let ((org-enable-table-editor t))
14577 (cond
14578 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14579 org-occur-highlights
14580 org-latex-fragment-image-overlays)
14581 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14582 (org-remove-occur-highlights)
14583 (org-remove-latex-fragment-image-overlays)
14584 (message "Temporary highlights/overlays removed from current buffer"))
14585 ((and (local-variable-p 'org-finish-function (current-buffer))
14586 (fboundp org-finish-function))
14587 (funcall org-finish-function))
14588 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14589 ((org-at-property-p)
14590 (call-interactively 'org-property-action))
14591 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14592 ((org-on-heading-p) (call-interactively 'org-set-tags))
14593 ((org-at-table.el-p)
14594 (require 'table)
14595 (beginning-of-line 1)
14596 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14597 (call-interactively 'table-recognize-table))
14598 ((org-at-table-p)
14599 (org-table-maybe-eval-formula)
14600 (if arg
14601 (call-interactively 'org-table-recalculate)
14602 (org-table-maybe-recalculate-line))
14603 (call-interactively 'org-table-align))
14604 ((or (org-footnote-at-reference-p)
14605 (org-footnote-at-definition-p))
14606 (call-interactively 'org-footnote-action))
14607 ((org-at-item-checkbox-p)
14608 (call-interactively 'org-toggle-checkbox))
14609 ((org-at-item-p)
14610 (if arg
14611 (call-interactively 'org-toggle-checkbox)
14612 (call-interactively 'org-maybe-renumber-ordered-list)))
14613 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14614 ;; Dynamic block
14615 (beginning-of-line 1)
14616 (save-excursion (org-update-dblock)))
14617 ((save-excursion
14618 (beginning-of-line 1)
14619 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
14620 (cond
14621 ((equal (match-string 1) "TBLFM")
14622 ;; Recalculate the table before this line
14623 (save-excursion
14624 (beginning-of-line 1)
14625 (skip-chars-backward " \r\n\t")
14626 (if (org-at-table-p)
14627 (org-call-with-arg 'org-table-recalculate t))))
14629 ; (org-set-regexps-and-options)
14630 ; (org-restart-font-lock)
14631 (let ((org-inhibit-startup t)) (org-mode-restart))
14632 (message "Local setup has been refreshed"))))
14633 ((org-clock-update-time-maybe))
14634 (t (error "C-c C-c can do nothing useful at this location.")))))
14636 (defun org-mode-restart ()
14637 "Restart Org-mode, to scan again for special lines.
14638 Also updates the keyword regular expressions."
14639 (interactive)
14640 (org-mode)
14641 (message "Org-mode restarted"))
14643 (defun org-kill-note-or-show-branches ()
14644 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14645 (interactive)
14646 (if (not org-finish-function)
14647 (call-interactively 'show-branches)
14648 (let ((org-note-abort t))
14649 (funcall org-finish-function))))
14651 (defun org-return (&optional indent)
14652 "Goto next table row or insert a newline.
14653 Calls `org-table-next-row' or `newline', depending on context.
14654 See the individual commands for more information."
14655 (interactive)
14656 (cond
14657 ((bobp) (if indent (newline-and-indent) (newline)))
14658 ((org-at-table-p)
14659 (org-table-justify-field-maybe)
14660 (call-interactively 'org-table-next-row))
14661 ((and org-return-follows-link
14662 (eq (get-text-property (point) 'face) 'org-link))
14663 (call-interactively 'org-open-at-point))
14664 ((and (org-at-heading-p)
14665 (looking-at
14666 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14667 (org-show-entry)
14668 (end-of-line 1)
14669 (newline))
14670 (t (if indent (newline-and-indent) (newline)))))
14672 (defun org-return-indent ()
14673 "Goto next table row or insert a newline and indent.
14674 Calls `org-table-next-row' or `newline-and-indent', depending on
14675 context. See the individual commands for more information."
14676 (interactive)
14677 (org-return t))
14679 (defun org-ctrl-c-star ()
14680 "Compute table, or change heading status of lines.
14681 Calls `org-table-recalculate' or `org-toggle-heading',
14682 depending on context."
14683 (interactive)
14684 (cond
14685 ((org-at-table-p)
14686 (call-interactively 'org-table-recalculate))
14688 ;; Convert all lines in region to list items
14689 (call-interactively 'org-toggle-heading))))
14691 (defun org-ctrl-c-minus ()
14692 "Insert separator line in table or modify bullet status of line.
14693 Also turns a plain line or a region of lines into list items.
14694 Calls `org-table-insert-hline', `org-toggle-item', or
14695 `org-cycle-list-bullet', depending on context."
14696 (interactive)
14697 (cond
14698 ((org-at-table-p)
14699 (call-interactively 'org-table-insert-hline))
14700 ((org-region-active-p)
14701 (call-interactively 'org-toggle-item))
14702 ((org-in-item-p)
14703 (call-interactively 'org-cycle-list-bullet))
14705 (call-interactively 'org-toggle-item))))
14707 (defun org-toggle-item ()
14708 "Convert headings or normal lines to items, items to normal lines.
14709 If there is no active region, only the current line is considered.
14711 If the first line in the region is a headline, convert all headlines to items.
14713 If the first line in the region is an item, convert all items to normal lines.
14715 If the first line is normal text, add an item bullet to each line."
14716 (interactive)
14717 (let (l2 l beg end)
14718 (if (org-region-active-p)
14719 (setq beg (region-beginning) end (region-end))
14720 (setq beg (point-at-bol)
14721 end (min (1+ (point-at-eol)) (point-max))))
14722 (save-excursion
14723 (goto-char end)
14724 (setq l2 (org-current-line))
14725 (goto-char beg)
14726 (beginning-of-line 1)
14727 (setq l (1- (org-current-line)))
14728 (if (org-at-item-p)
14729 ;; We already have items, de-itemize
14730 (while (< (setq l (1+ l)) l2)
14731 (when (org-at-item-p)
14732 (goto-char (match-beginning 2))
14733 (delete-region (match-beginning 2) (match-end 2))
14734 (and (looking-at "[ \t]+") (replace-match "")))
14735 (beginning-of-line 2))
14736 (if (org-on-heading-p)
14737 ;; Headings, convert to items
14738 (while (< (setq l (1+ l)) l2)
14739 (if (looking-at org-outline-regexp)
14740 (replace-match "- " t t))
14741 (beginning-of-line 2))
14742 ;; normal lines, turn them into items
14743 (while (< (setq l (1+ l)) l2)
14744 (unless (org-at-item-p)
14745 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14746 (replace-match "\\1- \\2")))
14747 (beginning-of-line 2)))))))
14749 (defun org-toggle-heading (&optional nstars)
14750 "Convert headings to normal text, or items or text to headings.
14751 If there is no active region, only the current line is considered.
14753 If the first line is a heading, remove the stars from all headlines
14754 in the region.
14756 If the first line is a plain list item, turn all plain list items into
14757 headings.
14759 If the first line is a normal line, turn each and every line in the region
14760 into a heading.
14762 When converting a line into a heading, the number of stars is chosen
14763 such that the lines become children of the current entry. However, when
14764 a prefix argument is given, its value determines the number of stars to add."
14765 (interactive "P")
14766 (let (l2 l itemp beg end)
14767 (if (org-region-active-p)
14768 (setq beg (region-beginning) end (region-end))
14769 (setq beg (point-at-bol)
14770 end (min (1+ (point-at-eol)) (point-max))))
14771 (save-excursion
14772 (goto-char end)
14773 (setq l2 (org-current-line))
14774 (goto-char beg)
14775 (beginning-of-line 1)
14776 (setq l (1- (org-current-line)))
14777 (if (org-on-heading-p)
14778 ;; We already have headlines, de-star them
14779 (while (< (setq l (1+ l)) l2)
14780 (when (org-on-heading-p t)
14781 (and (looking-at outline-regexp) (replace-match "")))
14782 (beginning-of-line 2))
14783 (setq itemp (org-at-item-p))
14784 (let* ((stars
14785 (if nstars
14786 (make-string (prefix-numeric-value current-prefix-arg)
14788 (save-excursion
14789 (re-search-backward org-complex-heading-regexp nil t)
14790 (or (match-string 1) ""))))
14791 (add-stars (cond (nstars "")
14792 ((equal stars "") "*")
14793 (org-odd-levels-only "**")
14794 (t "*")))
14795 (rpl (concat stars add-stars " ")))
14796 (while (< (setq l (1+ l)) l2)
14797 (if itemp
14798 (and (org-at-item-p) (replace-match rpl t t))
14799 (unless (org-on-heading-p)
14800 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14801 (replace-match (concat rpl (match-string 2))))))
14802 (beginning-of-line 2)))))))
14804 (defun org-meta-return (&optional arg)
14805 "Insert a new heading or wrap a region in a table.
14806 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14807 See the individual commands for more information."
14808 (interactive "P")
14809 (cond
14810 ((run-hook-with-args-until-success 'org-metareturn-hook))
14811 ((org-at-table-p)
14812 (call-interactively 'org-table-wrap-region))
14813 (t (call-interactively 'org-insert-heading))))
14815 ;;; Menu entries
14817 ;; Define the Org-mode menus
14818 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14819 '("Tbl"
14820 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14821 ["Next Field" org-cycle (org-at-table-p)]
14822 ["Previous Field" org-shifttab (org-at-table-p)]
14823 ["Next Row" org-return (org-at-table-p)]
14824 "--"
14825 ["Blank Field" org-table-blank-field (org-at-table-p)]
14826 ["Edit Field" org-table-edit-field (org-at-table-p)]
14827 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14828 "--"
14829 ("Column"
14830 ["Move Column Left" org-metaleft (org-at-table-p)]
14831 ["Move Column Right" org-metaright (org-at-table-p)]
14832 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14833 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14834 ("Row"
14835 ["Move Row Up" org-metaup (org-at-table-p)]
14836 ["Move Row Down" org-metadown (org-at-table-p)]
14837 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14838 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14839 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14840 "--"
14841 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14842 ("Rectangle"
14843 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14844 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14845 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14846 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14847 "--"
14848 ("Calculate"
14849 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14850 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14851 ["Edit Formulas" org-edit-special (org-at-table-p)]
14852 "--"
14853 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14854 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14855 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14856 "--"
14857 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14858 "--"
14859 ["Sum Column/Rectangle" org-table-sum
14860 (or (org-at-table-p) (org-region-active-p))]
14861 ["Which Column?" org-table-current-column (org-at-table-p)])
14862 ["Debug Formulas"
14863 org-table-toggle-formula-debugger
14864 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14865 ["Show Col/Row Numbers"
14866 org-table-toggle-coordinate-overlays
14867 :style toggle
14868 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14869 "--"
14870 ["Create" org-table-create (and (not (org-at-table-p))
14871 org-enable-table-editor)]
14872 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14873 ["Import from File" org-table-import (not (org-at-table-p))]
14874 ["Export to File" org-table-export (org-at-table-p)]
14875 "--"
14876 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14878 (easy-menu-define org-org-menu org-mode-map "Org menu"
14879 '("Org"
14880 ("Show/Hide"
14881 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14882 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14883 ["Sparse Tree..." org-sparse-tree t]
14884 ["Reveal Context" org-reveal t]
14885 ["Show All" show-all t]
14886 "--"
14887 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14888 "--"
14889 ["New Heading" org-insert-heading t]
14890 ("Navigate Headings"
14891 ["Up" outline-up-heading t]
14892 ["Next" outline-next-visible-heading t]
14893 ["Previous" outline-previous-visible-heading t]
14894 ["Next Same Level" outline-forward-same-level t]
14895 ["Previous Same Level" outline-backward-same-level t]
14896 "--"
14897 ["Jump" org-goto t])
14898 ("Edit Structure"
14899 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14900 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14901 "--"
14902 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14903 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14904 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14905 "--"
14906 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14907 "--"
14908 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14909 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14910 ["Demote Heading" org-metaright (not (org-at-table-p))]
14911 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14912 "--"
14913 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14914 "--"
14915 ["Convert to odd levels" org-convert-to-odd-levels t]
14916 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14917 ("Editing"
14918 ["Emphasis..." org-emphasize t]
14919 ["Edit Source Example" org-edit-special t]
14920 "--"
14921 ["Footnote new/jump" org-footnote-action t]
14922 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14923 ("Archive"
14924 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14925 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14926 ; :active t :keys "C-u C-c C-x C-a"]
14927 ["Sparse trees open ARCHIVE trees"
14928 (setq org-sparse-tree-open-archived-trees
14929 (not org-sparse-tree-open-archived-trees))
14930 :style toggle :selected org-sparse-tree-open-archived-trees]
14931 ["Cycling opens ARCHIVE trees"
14932 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14933 :style toggle :selected org-cycle-open-archived-trees]
14934 "--"
14935 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14936 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14937 ; ["Check and Move Children" (org-archive-subtree '(4))
14938 ; :active t :keys "C-u C-c C-x C-s"]
14940 "--"
14941 ("Hyperlinks"
14942 ["Store Link (Global)" org-store-link t]
14943 ["Insert Link" org-insert-link t]
14944 ["Follow Link" org-open-at-point t]
14945 "--"
14946 ["Next link" org-next-link t]
14947 ["Previous link" org-previous-link t]
14948 "--"
14949 ["Descriptive Links"
14950 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14951 :style radio
14952 :selected (member '(org-link) buffer-invisibility-spec)]
14953 ["Literal Links"
14954 (progn
14955 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14956 :style radio
14957 :selected (not (member '(org-link) buffer-invisibility-spec))])
14958 "--"
14959 ("TODO Lists"
14960 ["TODO/DONE/-" org-todo t]
14961 ("Select keyword"
14962 ["Next keyword" org-shiftright (org-on-heading-p)]
14963 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14964 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14965 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14966 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14967 ["Show TODO Tree" org-show-todo-tree t]
14968 ["Global TODO list" org-todo-list t]
14969 "--"
14970 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14971 :selected org-enforce-todo-dependencies :style toggle :active t]
14972 "Settings for tree at point"
14973 ["Do Children sequentially" org-toggle-ordered-property :style radio
14974 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14975 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14976 ["Do Children parallel" org-toggle-ordered-property :style radio
14977 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14978 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14979 "--"
14980 ["Set Priority" org-priority t]
14981 ["Priority Up" org-shiftup t]
14982 ["Priority Down" org-shiftdown t]
14983 "--"
14984 ["Get news from all feeds" org-feed-update-all t]
14985 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
14986 ["Customize feeds" (customize-variable 'org-feed-alist) t])
14987 ("TAGS and Properties"
14988 ["Set Tags" org-set-tags-command t]
14989 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14990 "--"
14991 ["Set property" org-set-property t]
14992 ["Column view of properties" org-columns t]
14993 ["Insert Column View DBlock" org-insert-columns-dblock t])
14994 ("Dates and Scheduling"
14995 ["Timestamp" org-time-stamp t]
14996 ["Timestamp (inactive)" org-time-stamp-inactive t]
14997 ("Change Date"
14998 ["1 Day Later" org-shiftright t]
14999 ["1 Day Earlier" org-shiftleft t]
15000 ["1 ... Later" org-shiftup t]
15001 ["1 ... Earlier" org-shiftdown t])
15002 ["Compute Time Range" org-evaluate-time-range t]
15003 ["Schedule Item" org-schedule t]
15004 ["Deadline" org-deadline t]
15005 "--"
15006 ["Custom time format" org-toggle-time-stamp-overlays
15007 :style radio :selected org-display-custom-times]
15008 "--"
15009 ["Goto Calendar" org-goto-calendar t]
15010 ["Date from Calendar" org-date-from-calendar t]
15011 "--"
15012 ["Start/Restart Timer" org-timer-start t]
15013 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15014 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15015 ["Insert Timer String" org-timer t]
15016 ["Insert Timer Item" org-timer-item t])
15017 ("Logging work"
15018 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15019 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15020 ["Clock out" org-clock-out t]
15021 ["Clock cancel" org-clock-cancel t]
15022 "--"
15023 ["Mark as default task" org-clock-mark-default-task t]
15024 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15025 ["Goto running clock" org-clock-goto t]
15026 "--"
15027 ["Display times" org-clock-display t]
15028 ["Create clock table" org-clock-report t]
15029 "--"
15030 ["Record DONE time"
15031 (progn (setq org-log-done (not org-log-done))
15032 (message "Switching to %s will %s record a timestamp"
15033 (car org-done-keywords)
15034 (if org-log-done "automatically" "not")))
15035 :style toggle :selected org-log-done])
15036 "--"
15037 ["Agenda Command..." org-agenda t]
15038 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15039 ("File List for Agenda")
15040 ("Special views current file"
15041 ["TODO Tree" org-show-todo-tree t]
15042 ["Check Deadlines" org-check-deadlines t]
15043 ["Timeline" org-timeline t]
15044 ["Tags/Property tree" org-match-sparse-tree t])
15045 "--"
15046 ["Export/Publish..." org-export t]
15047 ("LaTeX"
15048 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15049 :selected org-cdlatex-mode]
15050 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15051 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15052 ["Modify math symbol" org-cdlatex-math-modify
15053 (org-inside-LaTeX-fragment-p)]
15054 ["Insert citation" org-reftex-citation t]
15055 "--"
15056 ["Export LaTeX fragments as images"
15057 (if (featurep 'org-exp)
15058 (setq org-export-with-LaTeX-fragments
15059 (not org-export-with-LaTeX-fragments))
15060 (require 'org-exp))
15061 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15062 org-export-with-LaTeX-fragments)])
15063 "--"
15064 ("Documentation"
15065 ["Show Version" org-version t]
15066 ["Info Documentation" org-info t])
15067 ("Customize"
15068 ["Browse Org Group" org-customize t]
15069 "--"
15070 ["Expand This Menu" org-create-customize-menu
15071 (fboundp 'customize-menu-create)])
15072 "--"
15073 ("Refresh/Reload"
15074 ["Refresh setup current buffer" org-mode-restart t]
15075 ["Reload Org (after update)" org-reload t]
15076 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15079 (defun org-info (&optional node)
15080 "Read documentation for Org-mode in the info system.
15081 With optional NODE, go directly to that node."
15082 (interactive)
15083 (info (format "(org)%s" (or node ""))))
15085 (defun org-install-agenda-files-menu ()
15086 (let ((bl (buffer-list)))
15087 (save-excursion
15088 (while bl
15089 (set-buffer (pop bl))
15090 (if (org-mode-p) (setq bl nil)))
15091 (when (org-mode-p)
15092 (easy-menu-change
15093 '("Org") "File List for Agenda"
15094 (append
15095 (list
15096 ["Edit File List" (org-edit-agenda-file-list) t]
15097 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15098 ["Remove Current File from List" org-remove-file t]
15099 ["Cycle through agenda files" org-cycle-agenda-files t]
15100 ["Occur in all agenda files" org-occur-in-agenda-files t]
15101 "--")
15102 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15104 ;;;; Documentation
15106 ;;;###autoload
15107 (defun org-require-autoloaded-modules ()
15108 (interactive)
15109 (mapc 'require
15110 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15111 org-docbook org-exp org-html org-icalendar
15112 org-id org-latex
15113 org-publish org-remember org-table
15114 org-timer org-xoxo)))
15116 ;;;###autoload
15117 (defun org-reload (&optional uncompiled)
15118 "Reload all org lisp files.
15119 With prefix arg UNCOMPILED, load the uncompiled versions."
15120 (interactive "P")
15121 (require 'find-func)
15122 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15123 (dir-org (file-name-directory (org-find-library-name "org")))
15124 (dir-org-contrib (ignore-errors
15125 (file-name-directory
15126 (org-find-library-name "org-contribdir"))))
15127 (files
15128 (append (directory-files dir-org t file-re)
15129 (and dir-org-contrib
15130 (directory-files dir-org-contrib t file-re))))
15131 (remove-re (concat (if (featurep 'xemacs)
15132 "org-colview" "org-colview-xemacs")
15133 "\\'")))
15134 (setq files (mapcar 'file-name-sans-extension files))
15135 (setq files (mapcar
15136 (lambda (x) (if (string-match remove-re x) nil x))
15137 files))
15138 (setq files (delq nil files))
15139 (mapc
15140 (lambda (f)
15141 (when (featurep (intern (file-name-nondirectory f)))
15142 (if (and (not uncompiled)
15143 (file-exists-p (concat f ".elc")))
15144 (load (concat f ".elc") nil nil t)
15145 (load (concat f ".el") nil nil t))))
15146 files))
15147 (org-version))
15149 ;;;###autoload
15150 (defun org-customize ()
15151 "Call the customize function with org as argument."
15152 (interactive)
15153 (org-load-modules-maybe)
15154 (org-require-autoloaded-modules)
15155 (customize-browse 'org))
15157 (defun org-create-customize-menu ()
15158 "Create a full customization menu for Org-mode, insert it into the menu."
15159 (interactive)
15160 (org-load-modules-maybe)
15161 (org-require-autoloaded-modules)
15162 (if (fboundp 'customize-menu-create)
15163 (progn
15164 (easy-menu-change
15165 '("Org") "Customize"
15166 `(["Browse Org group" org-customize t]
15167 "--"
15168 ,(customize-menu-create 'org)
15169 ["Set" Custom-set t]
15170 ["Save" Custom-save t]
15171 ["Reset to Current" Custom-reset-current t]
15172 ["Reset to Saved" Custom-reset-saved t]
15173 ["Reset to Standard Settings" Custom-reset-standard t]))
15174 (message "\"Org\"-menu now contains full customization menu"))
15175 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15177 ;;;; Miscellaneous stuff
15179 ;;; Generally useful functions
15181 (defun org-find-text-property-in-string (prop s)
15182 "Return the first non-nil value of property PROP in string S."
15183 (or (get-text-property 0 prop s)
15184 (get-text-property (or (next-single-property-change 0 prop s) 0)
15185 prop s)))
15187 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15188 "Display the given MESSAGE as a warning."
15189 (if (fboundp 'display-warning)
15190 (display-warning 'org message
15191 (if (featurep 'xemacs)
15192 'warning
15193 :warning))
15194 (let ((buf (get-buffer-create "*Org warnings*")))
15195 (with-current-buffer buf
15196 (goto-char (point-max))
15197 (insert "Warning (Org): " message)
15198 (unless (bolp)
15199 (newline)))
15200 (display-buffer buf)
15201 (sit-for 0))))
15203 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15204 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15205 (if (and marker (marker-buffer marker)
15206 (buffer-live-p (marker-buffer marker)))
15207 (progn
15208 (switch-to-buffer (marker-buffer marker))
15209 (if (or (> marker (point-max)) (< marker (point-min)))
15210 (widen))
15211 (goto-char marker)
15212 (org-show-context 'org-goto))
15213 (if bookmark
15214 (bookmark-jump bookmark)
15215 (error "Cannot find location"))))
15217 (defun org-quote-csv-field (s)
15218 "Quote field for inclusion in CSV material."
15219 (if (string-match "[\",]" s)
15220 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15223 (defun org-plist-delete (plist property)
15224 "Delete PROPERTY from PLIST.
15225 This is in contrast to merely setting it to 0."
15226 (let (p)
15227 (while plist
15228 (if (not (eq property (car plist)))
15229 (setq p (plist-put p (car plist) (nth 1 plist))))
15230 (setq plist (cddr plist)))
15233 (defun org-force-self-insert (N)
15234 "Needed to enforce self-insert under remapping."
15235 (interactive "p")
15236 (self-insert-command N))
15238 (defun org-string-width (s)
15239 "Compute width of string, ignoring invisible characters.
15240 This ignores character with invisibility property `org-link', and also
15241 characters with property `org-cwidth', because these will become invisible
15242 upon the next fontification round."
15243 (let (b l)
15244 (when (or (eq t buffer-invisibility-spec)
15245 (assq 'org-link buffer-invisibility-spec))
15246 (while (setq b (text-property-any 0 (length s)
15247 'invisible 'org-link s))
15248 (setq s (concat (substring s 0 b)
15249 (substring s (or (next-single-property-change
15250 b 'invisible s) (length s)))))))
15251 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15252 (setq s (concat (substring s 0 b)
15253 (substring s (or (next-single-property-change
15254 b 'org-cwidth s) (length s))))))
15255 (setq l (string-width s) b -1)
15256 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15257 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15260 (defun org-get-indentation (&optional line)
15261 "Get the indentation of the current line, interpreting tabs.
15262 When LINE is given, assume it represents a line and compute its indentation."
15263 (if line
15264 (if (string-match "^ *" (org-remove-tabs line))
15265 (match-end 0))
15266 (save-excursion
15267 (beginning-of-line 1)
15268 (skip-chars-forward " \t")
15269 (current-column))))
15271 (defun org-remove-tabs (s &optional width)
15272 "Replace tabulators in S with spaces.
15273 Assumes that s is a single line, starting in column 0."
15274 (setq width (or width tab-width))
15275 (while (string-match "\t" s)
15276 (setq s (replace-match
15277 (make-string
15278 (- (* width (/ (+ (match-beginning 0) width) width))
15279 (match-beginning 0)) ?\ )
15280 t t s)))
15283 (defun org-fix-indentation (line ind)
15284 "Fix indentation in LINE.
15285 IND is a cons cell with target and minimum indentation.
15286 If the current indentation in LINE is smaller than the minimum,
15287 leave it alone. If it is larger than ind, set it to the target."
15288 (let* ((l (org-remove-tabs line))
15289 (i (org-get-indentation l))
15290 (i1 (car ind)) (i2 (cdr ind)))
15291 (if (>= i i2) (setq l (substring line i2)))
15292 (if (> i1 0)
15293 (concat (make-string i1 ?\ ) l)
15294 l)))
15296 (defun org-remove-indentation (code &optional n)
15297 "Remove the maximum common indentation from the lines in CODE.
15298 N may optionally be the number of spaces to remove."
15299 (with-temp-buffer
15300 (insert code)
15301 (org-do-remove-indentation n)
15302 (buffer-string)))
15304 (defun org-do-remove-indentation (&optional n)
15305 "Remove the maximum common indentation from the buffer."
15306 (untabify (point-min) (point-max))
15307 (let ((min 10000) re)
15308 (if n
15309 (setq min n)
15310 (goto-char (point-min))
15311 (while (re-search-forward "^ *[^ \n]" nil t)
15312 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
15313 (unless (or (= min 0) (= min 10000))
15314 (setq re (format "^ \\{%d\\}" min))
15315 (goto-char (point-min))
15316 (while (re-search-forward re nil t)
15317 (replace-match "")
15318 (end-of-line 1))
15319 min)))
15321 (defun org-base-buffer (buffer)
15322 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15323 (if (not buffer)
15324 buffer
15325 (or (buffer-base-buffer buffer)
15326 buffer)))
15328 (defun org-trim (s)
15329 "Remove whitespace at beginning and end of string."
15330 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15331 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15334 (defun org-wrap (string &optional width lines)
15335 "Wrap string to either a number of lines, or a width in characters.
15336 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15337 that costs. If there is a word longer than WIDTH, the text is actually
15338 wrapped to the length of that word.
15339 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15340 many lines, whatever width that takes.
15341 The return value is a list of lines, without newlines at the end."
15342 (let* ((words (org-split-string string "[ \t\n]+"))
15343 (maxword (apply 'max (mapcar 'org-string-width words)))
15344 w ll)
15345 (cond (width
15346 (org-do-wrap words (max maxword width)))
15347 (lines
15348 (setq w maxword)
15349 (setq ll (org-do-wrap words maxword))
15350 (if (<= (length ll) lines)
15352 (setq ll words)
15353 (while (> (length ll) lines)
15354 (setq w (1+ w))
15355 (setq ll (org-do-wrap words w)))
15356 ll))
15357 (t (error "Cannot wrap this")))))
15359 (defun org-do-wrap (words width)
15360 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15361 (let (lines line)
15362 (while words
15363 (setq line (pop words))
15364 (while (and words (< (+ (length line) (length (car words))) width))
15365 (setq line (concat line " " (pop words))))
15366 (setq lines (push line lines)))
15367 (nreverse lines)))
15369 (defun org-split-string (string &optional separators)
15370 "Splits STRING into substrings at SEPARATORS.
15371 No empty strings are returned if there are matches at the beginning
15372 and end of string."
15373 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15374 (start 0)
15375 notfirst
15376 (list nil))
15377 (while (and (string-match rexp string
15378 (if (and notfirst
15379 (= start (match-beginning 0))
15380 (< start (length string)))
15381 (1+ start) start))
15382 (< (match-beginning 0) (length string)))
15383 (setq notfirst t)
15384 (or (eq (match-beginning 0) 0)
15385 (and (eq (match-beginning 0) (match-end 0))
15386 (eq (match-beginning 0) start))
15387 (setq list
15388 (cons (substring string start (match-beginning 0))
15389 list)))
15390 (setq start (match-end 0)))
15391 (or (eq start (length string))
15392 (setq list
15393 (cons (substring string start)
15394 list)))
15395 (nreverse list)))
15397 (defun org-quote-vert (s)
15398 "Replace \"|\" with \"\\vert\"."
15399 (while (string-match "|" s)
15400 (setq s (replace-match "\\vert" t t s)))
15403 (defun org-uuidgen-p (s)
15404 "Is S an ID created by UUIDGEN?"
15405 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15407 (defun org-context ()
15408 "Return a list of contexts of the current cursor position.
15409 If several contexts apply, all are returned.
15410 Each context entry is a list with a symbol naming the context, and
15411 two positions indicating start and end of the context. Possible
15412 contexts are:
15414 :headline anywhere in a headline
15415 :headline-stars on the leading stars in a headline
15416 :todo-keyword on a TODO keyword (including DONE) in a headline
15417 :tags on the TAGS in a headline
15418 :priority on the priority cookie in a headline
15419 :item on the first line of a plain list item
15420 :item-bullet on the bullet/number of a plain list item
15421 :checkbox on the checkbox in a plain list item
15422 :table in an org-mode table
15423 :table-special on a special filed in a table
15424 :table-table in a table.el table
15425 :link on a hyperlink
15426 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15427 :target on a <<target>>
15428 :radio-target on a <<<radio-target>>>
15429 :latex-fragment on a LaTeX fragment
15430 :latex-preview on a LaTeX fragment with overlayed preview image
15432 This function expects the position to be visible because it uses font-lock
15433 faces as a help to recognize the following contexts: :table-special, :link,
15434 and :keyword."
15435 (let* ((f (get-text-property (point) 'face))
15436 (faces (if (listp f) f (list f)))
15437 (p (point)) clist o)
15438 ;; First the large context
15439 (cond
15440 ((org-on-heading-p t)
15441 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15442 (when (progn
15443 (beginning-of-line 1)
15444 (looking-at org-todo-line-tags-regexp))
15445 (push (org-point-in-group p 1 :headline-stars) clist)
15446 (push (org-point-in-group p 2 :todo-keyword) clist)
15447 (push (org-point-in-group p 4 :tags) clist))
15448 (goto-char p)
15449 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15450 (if (looking-at "\\[#[A-Z0-9]\\]")
15451 (push (org-point-in-group p 0 :priority) clist)))
15453 ((org-at-item-p)
15454 (push (org-point-in-group p 2 :item-bullet) clist)
15455 (push (list :item (point-at-bol)
15456 (save-excursion (org-end-of-item) (point)))
15457 clist)
15458 (and (org-at-item-checkbox-p)
15459 (push (org-point-in-group p 0 :checkbox) clist)))
15461 ((org-at-table-p)
15462 (push (list :table (org-table-begin) (org-table-end)) clist)
15463 (if (memq 'org-formula faces)
15464 (push (list :table-special
15465 (previous-single-property-change p 'face)
15466 (next-single-property-change p 'face)) clist)))
15467 ((org-at-table-p 'any)
15468 (push (list :table-table) clist)))
15469 (goto-char p)
15471 ;; Now the small context
15472 (cond
15473 ((org-at-timestamp-p)
15474 (push (org-point-in-group p 0 :timestamp) clist))
15475 ((memq 'org-link faces)
15476 (push (list :link
15477 (previous-single-property-change p 'face)
15478 (next-single-property-change p 'face)) clist))
15479 ((memq 'org-special-keyword faces)
15480 (push (list :keyword
15481 (previous-single-property-change p 'face)
15482 (next-single-property-change p 'face)) clist))
15483 ((org-on-target-p)
15484 (push (org-point-in-group p 0 :target) clist)
15485 (goto-char (1- (match-beginning 0)))
15486 (if (looking-at org-radio-target-regexp)
15487 (push (org-point-in-group p 0 :radio-target) clist))
15488 (goto-char p))
15489 ((setq o (car (delq nil
15490 (mapcar
15491 (lambda (x)
15492 (if (memq x org-latex-fragment-image-overlays) x))
15493 (org-overlays-at (point))))))
15494 (push (list :latex-fragment
15495 (org-overlay-start o) (org-overlay-end o)) clist)
15496 (push (list :latex-preview
15497 (org-overlay-start o) (org-overlay-end o)) clist))
15498 ((org-inside-LaTeX-fragment-p)
15499 ;; FIXME: positions wrong.
15500 (push (list :latex-fragment (point) (point)) clist)))
15502 (setq clist (nreverse (delq nil clist)))
15503 clist))
15505 ;; FIXME: Compare with at-regexp-p Do we need both?
15506 (defun org-in-regexp (re &optional nlines visually)
15507 "Check if point is inside a match of regexp.
15508 Normally only the current line is checked, but you can include NLINES extra
15509 lines both before and after point into the search.
15510 If VISUALLY is set, require that the cursor is not after the match but
15511 really on, so that the block visually is on the match."
15512 (catch 'exit
15513 (let ((pos (point))
15514 (eol (point-at-eol (+ 1 (or nlines 0))))
15515 (inc (if visually 1 0)))
15516 (save-excursion
15517 (beginning-of-line (- 1 (or nlines 0)))
15518 (while (re-search-forward re eol t)
15519 (if (and (<= (match-beginning 0) pos)
15520 (>= (+ inc (match-end 0)) pos))
15521 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15523 (defun org-at-regexp-p (regexp)
15524 "Is point inside a match of REGEXP in the current line?"
15525 (catch 'exit
15526 (save-excursion
15527 (let ((pos (point)) (end (point-at-eol)))
15528 (beginning-of-line 1)
15529 (while (re-search-forward regexp end t)
15530 (if (and (<= (match-beginning 0) pos)
15531 (>= (match-end 0) pos))
15532 (throw 'exit t)))
15533 nil))))
15535 (defun org-occur-in-agenda-files (regexp &optional nlines)
15536 "Call `multi-occur' with buffers for all agenda files."
15537 (interactive "sOrg-files matching: \np")
15538 (let* ((files (org-agenda-files))
15539 (tnames (mapcar 'file-truename files))
15540 (extra org-agenda-text-search-extra-files)
15542 (when (eq (car extra) 'agenda-archives)
15543 (setq extra (cdr extra))
15544 (setq files (org-add-archive-files files)))
15545 (while (setq f (pop extra))
15546 (unless (member (file-truename f) tnames)
15547 (add-to-list 'files f 'append)
15548 (add-to-list 'tnames (file-truename f) 'append)))
15549 (multi-occur
15550 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15551 regexp)))
15553 (if (boundp 'occur-mode-find-occurrence-hook)
15554 ;; Emacs 23
15555 (add-hook 'occur-mode-find-occurrence-hook
15556 (lambda ()
15557 (when (org-mode-p)
15558 (org-reveal))))
15559 ;; Emacs 22
15560 (defadvice occur-mode-goto-occurrence
15561 (after org-occur-reveal activate)
15562 (and (org-mode-p) (org-reveal)))
15563 (defadvice occur-mode-goto-occurrence-other-window
15564 (after org-occur-reveal activate)
15565 (and (org-mode-p) (org-reveal)))
15566 (defadvice occur-mode-display-occurrence
15567 (after org-occur-reveal activate)
15568 (when (org-mode-p)
15569 (let ((pos (occur-mode-find-occurrence)))
15570 (with-current-buffer (marker-buffer pos)
15571 (save-excursion
15572 (goto-char pos)
15573 (org-reveal)))))))
15575 (defun org-uniquify (list)
15576 "Remove duplicate elements from LIST."
15577 (let (res)
15578 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15579 res))
15581 (defun org-delete-all (elts list)
15582 "Remove all elements in ELTS from LIST."
15583 (while elts
15584 (setq list (delete (pop elts) list)))
15585 list)
15587 (defun org-back-over-empty-lines ()
15588 "Move backwards over whitespace, to the beginning of the first empty line.
15589 Returns the number of empty lines passed."
15590 (let ((pos (point)))
15591 (skip-chars-backward " \t\n\r")
15592 (beginning-of-line 2)
15593 (goto-char (min (point) pos))
15594 (count-lines (point) pos)))
15596 (defun org-skip-whitespace ()
15597 (skip-chars-forward " \t\n\r"))
15599 (defun org-point-in-group (point group &optional context)
15600 "Check if POINT is in match-group GROUP.
15601 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15602 match. If the match group does ot exist or point is not inside it,
15603 return nil."
15604 (and (match-beginning group)
15605 (>= point (match-beginning group))
15606 (<= point (match-end group))
15607 (if context
15608 (list context (match-beginning group) (match-end group))
15609 t)))
15611 (defun org-switch-to-buffer-other-window (&rest args)
15612 "Switch to buffer in a second window on the current frame.
15613 In particular, do not allow pop-up frames."
15614 (let (pop-up-frames special-display-buffer-names special-display-regexps
15615 special-display-function)
15616 (apply 'switch-to-buffer-other-window args)))
15618 (defun org-combine-plists (&rest plists)
15619 "Create a single property list from all plists in PLISTS.
15620 The process starts by copying the first list, and then setting properties
15621 from the other lists. Settings in the last list are the most significant
15622 ones and overrule settings in the other lists."
15623 (let ((rtn (copy-sequence (pop plists)))
15624 p v ls)
15625 (while plists
15626 (setq ls (pop plists))
15627 (while ls
15628 (setq p (pop ls) v (pop ls))
15629 (setq rtn (plist-put rtn p v))))
15630 rtn))
15632 (defun org-move-line-down (arg)
15633 "Move the current line down. With prefix argument, move it past ARG lines."
15634 (interactive "p")
15635 (let ((col (current-column))
15636 beg end pos)
15637 (beginning-of-line 1) (setq beg (point))
15638 (beginning-of-line 2) (setq end (point))
15639 (beginning-of-line (+ 1 arg))
15640 (setq pos (move-marker (make-marker) (point)))
15641 (insert (delete-and-extract-region beg end))
15642 (goto-char pos)
15643 (org-move-to-column col)))
15645 (defun org-move-line-up (arg)
15646 "Move the current line up. With prefix argument, move it past ARG lines."
15647 (interactive "p")
15648 (let ((col (current-column))
15649 beg end pos)
15650 (beginning-of-line 1) (setq beg (point))
15651 (beginning-of-line 2) (setq end (point))
15652 (beginning-of-line (- arg))
15653 (setq pos (move-marker (make-marker) (point)))
15654 (insert (delete-and-extract-region beg end))
15655 (goto-char pos)
15656 (org-move-to-column col)))
15658 (defun org-replace-escapes (string table)
15659 "Replace %-escapes in STRING with values in TABLE.
15660 TABLE is an association list with keys like \"%a\" and string values.
15661 The sequences in STRING may contain normal field width and padding information,
15662 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15663 so values can contain further %-escapes if they are define later in TABLE."
15664 (let ((case-fold-search nil)
15665 e re rpl)
15666 (while (setq e (pop table))
15667 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15668 (while (string-match re string)
15669 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15670 (cdr e)))
15671 (setq string (replace-match rpl t t string))))
15672 string))
15675 (defun org-sublist (list start end)
15676 "Return a section of LIST, from START to END.
15677 Counting starts at 1."
15678 (let (rtn (c start))
15679 (setq list (nthcdr (1- start) list))
15680 (while (and list (<= c end))
15681 (push (pop list) rtn)
15682 (setq c (1+ c)))
15683 (nreverse rtn)))
15685 (defun org-find-base-buffer-visiting (file)
15686 "Like `find-buffer-visiting' but always return the base buffer and
15687 not an indirect buffer."
15688 (let ((buf (or (get-file-buffer file)
15689 (find-buffer-visiting file))))
15690 (if buf
15691 (or (buffer-base-buffer buf) buf)
15692 nil)))
15694 (defun org-image-file-name-regexp (&optional extensions)
15695 "Return regexp matching the file names of images.
15696 If EXTENSIONS is given, only match these."
15697 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15698 (image-file-name-regexp)
15699 (let ((image-file-name-extensions
15700 (or extensions
15701 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15702 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15703 (concat "\\."
15704 (regexp-opt (nconc (mapcar 'upcase
15705 image-file-name-extensions)
15706 image-file-name-extensions)
15708 "\\'"))))
15710 (defun org-file-image-p (file &optional extensions)
15711 "Return non-nil if FILE is an image."
15712 (save-match-data
15713 (string-match (org-image-file-name-regexp extensions) file)))
15715 (defun org-get-cursor-date ()
15716 "Return the date at cursor in as a time.
15717 This works in the calendar and in the agenda, anywhere else it just
15718 returns the current time."
15719 (let (date day defd)
15720 (cond
15721 ((eq major-mode 'calendar-mode)
15722 (setq date (calendar-cursor-to-date)
15723 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15724 ((eq major-mode 'org-agenda-mode)
15725 (setq day (get-text-property (point) 'day))
15726 (if day
15727 (setq date (calendar-gregorian-from-absolute day)
15728 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15729 (nth 2 date))))))
15730 (or defd (current-time))))
15732 (defvar org-agenda-action-marker (make-marker)
15733 "Marker pointing to the entry for the next agenda action.")
15735 (defun org-mark-entry-for-agenda-action ()
15736 "Mark the current entry as target of an agenda action.
15737 Agenda actions are actions executed from the agenda with the key `k',
15738 which make use of the date at the cursor."
15739 (interactive)
15740 (move-marker org-agenda-action-marker
15741 (save-excursion (org-back-to-heading t) (point))
15742 (current-buffer))
15743 (message
15744 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15746 ;;; Paragraph filling stuff.
15747 ;; We want this to be just right, so use the full arsenal.
15749 (defun org-indent-line-function ()
15750 "Indent line like previous, but further if previous was headline or item."
15751 (interactive)
15752 (let* ((pos (point))
15753 (itemp (org-at-item-p))
15754 (case-fold-search t)
15755 (org-drawer-regexp (or org-drawer-regexp "\000"))
15756 column bpos bcol tpos tcol bullet btype bullet-type)
15757 ;; Find the previous relevant line
15758 (beginning-of-line 1)
15759 (cond
15760 ((looking-at "#") (setq column 0))
15761 ((looking-at "\\*+ ") (setq column 0))
15762 ((and (looking-at "[ \t]*:END:")
15763 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15764 (save-excursion
15765 (goto-char (1- (match-beginning 1)))
15766 (setq column (current-column))))
15767 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
15768 (save-excursion
15769 (re-search-backward
15770 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
15771 (setq column (org-get-indentation (match-string 0))))
15773 (beginning-of-line 0)
15774 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15775 (not (looking-at "[ \t]*:END:"))
15776 (not (looking-at org-drawer-regexp)))
15777 (beginning-of-line 0))
15778 (cond
15779 ((looking-at "\\*+[ \t]+")
15780 (if (not org-adapt-indentation)
15781 (setq column 0)
15782 (goto-char (match-end 0))
15783 (setq column (current-column))))
15784 ((looking-at org-drawer-regexp)
15785 (goto-char (1- (match-beginning 1)))
15786 (setq column (current-column)))
15787 ((looking-at "\\([ \t]*\\):END:")
15788 (goto-char (match-end 1))
15789 (setq column (current-column)))
15790 ((org-in-item-p)
15791 (org-beginning-of-item)
15792 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15793 (setq bpos (match-beginning 1) tpos (match-end 0)
15794 bcol (progn (goto-char bpos) (current-column))
15795 tcol (progn (goto-char tpos) (current-column))
15796 bullet (match-string 1)
15797 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15798 (if (> tcol (+ bcol org-description-max-indent))
15799 (setq tcol (+ bcol 5)))
15800 (if (not itemp)
15801 (setq column tcol)
15802 (goto-char pos)
15803 (beginning-of-line 1)
15804 (if (looking-at "\\S-")
15805 (progn
15806 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15807 (setq bullet (match-string 1)
15808 btype (if (string-match "[0-9]" bullet) "n" bullet))
15809 (setq column (if (equal btype bullet-type) bcol tcol)))
15810 (setq column (org-get-indentation)))))
15811 (t (setq column (org-get-indentation))))))
15812 (goto-char pos)
15813 (if (<= (current-column) (current-indentation))
15814 (org-indent-line-to column)
15815 (save-excursion (org-indent-line-to column)))
15816 (setq column (current-column))
15817 (beginning-of-line 1)
15818 (if (looking-at
15819 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15820 (replace-match (concat "\\1" (format org-property-format
15821 (match-string 2) (match-string 3)))
15822 t nil))
15823 (org-move-to-column column)))
15825 (defun org-set-autofill-regexps ()
15826 (interactive)
15827 ;; In the paragraph separator we include headlines, because filling
15828 ;; text in a line directly attached to a headline would otherwise
15829 ;; fill the headline as well.
15830 (org-set-local 'comment-start-skip "^#+[ \t]*")
15831 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15832 ;; The paragraph starter includes hand-formatted lists.
15833 (org-set-local
15834 'paragraph-start
15835 (concat
15836 "\f" "\\|"
15837 "[ ]*$" "\\|"
15838 "\\*+ " "\\|"
15839 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
15840 "[ \t]*[:|]" "\\|"
15841 "\\$\\$" "\\|"
15842 "\\\\\\(begin\\|end\\|[][]\\)"))
15843 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15844 ;; But only if the user has not turned off tables or fixed-width regions
15845 (org-set-local
15846 'auto-fill-inhibit-regexp
15847 (concat "\\*+ \\|#\\+"
15848 "\\|[ \t]*" org-keyword-time-regexp
15849 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15850 (concat
15851 "\\|[ \t]*["
15852 (if org-enable-table-editor "|" "")
15853 (if org-enable-fixed-width-editor ":" "")
15854 "]"))))
15855 ;; We use our own fill-paragraph function, to make sure that tables
15856 ;; and fixed-width regions are not wrapped. That function will pass
15857 ;; through to `fill-paragraph' when appropriate.
15858 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15859 ; Adaptive filling: To get full control, first make sure that
15860 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15861 (org-set-local 'adaptive-fill-regexp "\000")
15862 (org-set-local 'adaptive-fill-function
15863 'org-adaptive-fill-function)
15864 (org-set-local
15865 'align-mode-rules-list
15866 '((org-in-buffer-settings
15867 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15868 (modes . '(org-mode))))))
15870 (defun org-fill-paragraph (&optional justify)
15871 "Re-align a table, pass through to fill-paragraph if no table."
15872 (let ((table-p (org-at-table-p))
15873 (table.el-p (org-at-table.el-p)))
15874 (cond ((and (equal (char-after (point-at-bol)) ?*)
15875 (save-excursion (goto-char (point-at-bol))
15876 (looking-at outline-regexp)))
15877 t) ; skip headlines
15878 (table.el-p t) ; skip table.el tables
15879 (table-p (org-table-align) t) ; align org-mode tables
15880 (t nil)))) ; call paragraph-fill
15882 ;; For reference, this is the default value of adaptive-fill-regexp
15883 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15885 (defun org-adaptive-fill-function ()
15886 "Return a fill prefix for org-mode files.
15887 In particular, this makes sure hanging paragraphs for hand-formatted lists
15888 work correctly."
15889 (cond ((looking-at "#[ \t]+")
15890 (match-string 0))
15891 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15892 (save-excursion
15893 (if (> (match-end 1) (+ (match-beginning 1)
15894 org-description-max-indent))
15895 (goto-char (+ (match-beginning 1) 5))
15896 (goto-char (match-end 0)))
15897 (make-string (current-column) ?\ )))
15898 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15899 (save-excursion
15900 (goto-char (match-end 0))
15901 (make-string (current-column) ?\ )))
15902 (t nil)))
15904 ;;; Other stuff.
15906 (defun org-toggle-fixed-width-section (arg)
15907 "Toggle the fixed-width export.
15908 If there is no active region, the QUOTE keyword at the current headline is
15909 inserted or removed. When present, it causes the text between this headline
15910 and the next to be exported as fixed-width text, and unmodified.
15911 If there is an active region, this command adds or removes a colon as the
15912 first character of this line. If the first character of a line is a colon,
15913 this line is also exported in fixed-width font."
15914 (interactive "P")
15915 (let* ((cc 0)
15916 (regionp (org-region-active-p))
15917 (beg (if regionp (region-beginning) (point)))
15918 (end (if regionp (region-end)))
15919 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15920 (case-fold-search nil)
15921 (re "[ \t]*\\(: \\)")
15922 off)
15923 (if regionp
15924 (save-excursion
15925 (goto-char beg)
15926 (setq cc (current-column))
15927 (beginning-of-line 1)
15928 (setq off (looking-at re))
15929 (while (> nlines 0)
15930 (setq nlines (1- nlines))
15931 (beginning-of-line 1)
15932 (cond
15933 (arg
15934 (org-move-to-column cc t)
15935 (insert ": \n")
15936 (forward-line -1))
15937 ((and off (looking-at re))
15938 (replace-match "" t t nil 1))
15939 ((not off) (org-move-to-column cc t) (insert ": ")))
15940 (forward-line 1)))
15941 (save-excursion
15942 (org-back-to-heading)
15943 (if (looking-at (concat outline-regexp
15944 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15945 (replace-match "" t t nil 1)
15946 (if (looking-at outline-regexp)
15947 (progn
15948 (goto-char (match-end 0))
15949 (insert org-quote-string " "))))))))
15951 (defun org-reftex-citation ()
15952 "Use reftex-citation to insert a citation into the buffer.
15953 This looks for a line like
15955 #+BIBLIOGRAPHY: foo plain option:-d
15957 and derives from it that foo.bib is the bbliography file relevant
15958 for this document. It then installs the necessary environment for RefTeX
15959 to work in this buffer and calls `reftex-citation' to insert a citation
15960 into the buffer.
15962 Export of such citations to both LaTeX and HTML is handled by the contributed
15963 package org-exp-bibtex by Taru Karttunen."
15964 (interactive)
15965 (let ((reftex-docstruct-symbol 'rds)
15966 (reftex-cite-format "\\cite{%l}")
15967 rds bib)
15968 (save-excursion
15969 (save-restriction
15970 (widen)
15971 (let ((case-fold-search t)
15972 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
15973 (if (not (save-excursion
15974 (or (re-search-forward re nil t)
15975 (re-search-backward re nil t))))
15976 (error "No bibliography defined in file")
15977 (setq bib (concat (match-string 1) ".bib")
15978 rds (list (list 'bib bib)))))))
15979 (call-interactively 'reftex-citation)))
15981 ;;;; Functions extending outline functionality
15983 (defun org-beginning-of-line (&optional arg)
15984 "Go to the beginning of the current line. If that is invisible, continue
15985 to a visible line beginning. This makes the function of C-a more intuitive.
15986 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15987 first attempt, and only move to after the tags when the cursor is already
15988 beyond the end of the headline."
15989 (interactive "P")
15990 (let ((pos (point))
15991 (special (if (consp org-special-ctrl-a/e)
15992 (car org-special-ctrl-a/e)
15993 org-special-ctrl-a/e))
15994 refpos)
15995 (if (org-bound-and-true-p line-move-visual)
15996 (beginning-of-visual-line 1)
15997 (beginning-of-line 1))
15998 (if (and arg (fboundp 'move-beginning-of-line))
15999 (call-interactively 'move-beginning-of-line)
16000 (if (bobp)
16002 (backward-char 1)
16003 (if (org-invisible-p)
16004 (while (and (not (bobp)) (org-invisible-p))
16005 (backward-char 1)
16006 (beginning-of-line 1))
16007 (forward-char 1))))
16008 (when special
16009 (cond
16010 ((and (looking-at org-complex-heading-regexp)
16011 (= (char-after (match-end 1)) ?\ ))
16012 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16013 (point-at-eol)))
16014 (goto-char
16015 (if (eq special t)
16016 (cond ((> pos refpos) refpos)
16017 ((= pos (point)) refpos)
16018 (t (point)))
16019 (cond ((> pos (point)) (point))
16020 ((not (eq last-command this-command)) (point))
16021 (t refpos)))))
16022 ((org-at-item-p)
16023 (goto-char
16024 (if (eq special t)
16025 (cond ((> pos (match-end 4)) (match-end 4))
16026 ((= pos (point)) (match-end 4))
16027 (t (point)))
16028 (cond ((> pos (point)) (point))
16029 ((not (eq last-command this-command)) (point))
16030 (t (match-end 4))))))))
16031 (org-no-warnings
16032 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16034 (defun org-end-of-line (&optional arg)
16035 "Go to the end of the line.
16036 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16037 first attempt, and only move to after the tags when the cursor is already
16038 beyond the end of the headline."
16039 (interactive "P")
16040 (let ((special (if (consp org-special-ctrl-a/e)
16041 (cdr org-special-ctrl-a/e)
16042 org-special-ctrl-a/e)))
16043 (if (or (not special)
16044 (not (org-on-heading-p))
16045 arg)
16046 (call-interactively
16047 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
16048 ((fboundp 'move-end-of-line) 'move-end-of-line)
16049 (t 'end-of-line)))
16050 (let ((pos (point)))
16051 (beginning-of-line 1)
16052 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16053 (if (eq special t)
16054 (if (or (< pos (match-beginning 1))
16055 (= pos (match-end 0)))
16056 (goto-char (match-beginning 1))
16057 (goto-char (match-end 0)))
16058 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16059 (goto-char (match-end 0))
16060 (goto-char (match-beginning 1))))
16061 (call-interactively (if (fboundp 'move-end-of-line)
16062 'move-end-of-line
16063 'end-of-line)))))
16064 (org-no-warnings
16065 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16067 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16068 (define-key org-mode-map "\C-e" 'org-end-of-line)
16070 (defun org-backward-sentence (&optional arg)
16071 "Go to beginning of sentence, or beginning of table field.
16072 This will call `backward-sentence' or `org-table-beginning-of-field',
16073 depending on context."
16074 (interactive "P")
16075 (cond
16076 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16077 (t (call-interactively 'backward-sentence))))
16079 (defun org-forward-sentence (&optional arg)
16080 "Go to end of sentence, or end of table field.
16081 This will call `forward-sentence' or `org-table-end-of-field',
16082 depending on context."
16083 (interactive "P")
16084 (cond
16085 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16086 (t (call-interactively 'forward-sentence))))
16088 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16089 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16091 (defun org-kill-line (&optional arg)
16092 "Kill line, to tags or end of line."
16093 (interactive "P")
16094 (cond
16095 ((or (not org-special-ctrl-k)
16096 (bolp)
16097 (not (org-on-heading-p)))
16098 (call-interactively 'kill-line))
16099 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16100 (kill-region (point) (match-beginning 1))
16101 (org-set-tags nil t))
16102 (t (kill-region (point) (point-at-eol)))))
16104 (define-key org-mode-map "\C-k" 'org-kill-line)
16106 (defun org-yank (&optional arg)
16107 "Yank. If the kill is a subtree, treat it specially.
16108 This command will look at the current kill and check if is a single
16109 subtree, or a series of subtrees[1]. If it passes the test, and if the
16110 cursor is at the beginning of a line or after the stars of a currently
16111 empty headline, then the yank is handled specially. How exactly depends
16112 on the value of the following variables, both set by default.
16114 org-yank-folded-subtrees
16115 When set, the subtree(s) will be folded after insertion, but only
16116 if doing so would now swallow text after the yanked text.
16118 org-yank-adjusted-subtrees
16119 When set, the subtree will be promoted or demoted in order to
16120 fit into the local outline tree structure, which means that the level
16121 will be adjusted so that it becomes the smaller one of the two
16122 *visible* surrounding headings.
16124 Any prefix to this command will cause `yank' to be called directly with
16125 no special treatment. In particular, a simple `C-u' prefix will just
16126 plainly yank the text as it is.
16128 \[1] The test checks if the first non-white line is a heading
16129 and if there are no other headings with fewer stars."
16130 (interactive "P")
16131 (org-yank-generic 'yank arg))
16133 (defun org-yank-generic (command arg)
16134 "Perform some yank-like command.
16136 This function implements the behavior described in the `org-yank'
16137 documentation. However, it has been generalized to work for any
16138 interactive command with similar behavior."
16140 ;; pretend to be command COMMAND
16141 (setq this-command command)
16143 (if arg
16144 (call-interactively command)
16146 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16147 (and (org-kill-is-subtree-p)
16148 (or (bolp)
16149 (and (looking-at "[ \t]*$")
16150 (string-match
16151 "\\`\\*+\\'"
16152 (buffer-substring (point-at-bol) (point)))))))
16153 swallowp)
16154 (cond
16155 ((and subtreep org-yank-folded-subtrees)
16156 (let ((beg (point))
16157 end)
16158 (if (and subtreep org-yank-adjusted-subtrees)
16159 (org-paste-subtree nil nil 'for-yank)
16160 (call-interactively command))
16162 (setq end (point))
16163 (goto-char beg)
16164 (when (and (bolp) subtreep
16165 (not (setq swallowp
16166 (org-yank-folding-would-swallow-text beg end))))
16167 (or (looking-at outline-regexp)
16168 (re-search-forward (concat "^" outline-regexp) end t))
16169 (while (and (< (point) end) (looking-at outline-regexp))
16170 (hide-subtree)
16171 (org-cycle-show-empty-lines 'folded)
16172 (condition-case nil
16173 (outline-forward-same-level 1)
16174 (error (goto-char end)))))
16175 (when swallowp
16176 (message
16177 "Inserted text not folded because that would swallow text"))
16179 (goto-char end)
16180 (skip-chars-forward " \t\n\r")
16181 (beginning-of-line 1)
16182 (push-mark beg 'nomsg)))
16183 ((and subtreep org-yank-adjusted-subtrees)
16184 (let ((beg (point-at-bol)))
16185 (org-paste-subtree nil nil 'for-yank)
16186 (push-mark beg 'nomsg)))
16188 (call-interactively command))))))
16190 (defun org-yank-folding-would-swallow-text (beg end)
16191 "Would hide-subtree at BEG swallow any text after END?"
16192 (let (level)
16193 (save-excursion
16194 (goto-char beg)
16195 (when (or (looking-at outline-regexp)
16196 (re-search-forward (concat "^" outline-regexp) end t))
16197 (setq level (org-outline-level)))
16198 (goto-char end)
16199 (skip-chars-forward " \t\r\n\v\f")
16200 (if (or (eobp)
16201 (and (bolp) (looking-at org-outline-regexp)
16202 (<= (org-outline-level) level)))
16203 nil ; Nothing would be swallowed
16204 t)))) ; something would swallow
16206 (define-key org-mode-map "\C-y" 'org-yank)
16208 (defun org-invisible-p ()
16209 "Check if point is at a character currently not visible."
16210 ;; Early versions of noutline don't have `outline-invisible-p'.
16211 (if (fboundp 'outline-invisible-p)
16212 (outline-invisible-p)
16213 (get-char-property (point) 'invisible)))
16215 (defun org-invisible-p2 ()
16216 "Check if point is at a character currently not visible."
16217 (save-excursion
16218 (if (and (eolp) (not (bobp))) (backward-char 1))
16219 ;; Early versions of noutline don't have `outline-invisible-p'.
16220 (if (fboundp 'outline-invisible-p)
16221 (outline-invisible-p)
16222 (get-char-property (point) 'invisible))))
16224 (defun org-back-to-heading (&optional invisible-ok)
16225 "Call `outline-back-to-heading', but provide a better error message."
16226 (condition-case nil
16227 (outline-back-to-heading invisible-ok)
16228 (error (error "Before first headline at position %d in buffer %s"
16229 (point) (current-buffer)))))
16231 (defun org-before-first-heading-p ()
16232 "Before first heading?"
16233 (save-excursion
16234 (null (re-search-backward "^\\*+ " nil t))))
16236 (defalias 'org-on-heading-p 'outline-on-heading-p)
16237 (defalias 'org-at-heading-p 'outline-on-heading-p)
16238 (defun org-at-heading-or-item-p ()
16239 (or (org-on-heading-p) (org-at-item-p)))
16241 (defun org-on-target-p ()
16242 (or (org-in-regexp org-radio-target-regexp)
16243 (org-in-regexp org-target-regexp)))
16245 (defun org-up-heading-all (arg)
16246 "Move to the heading line of which the present line is a subheading.
16247 This function considers both visible and invisible heading lines.
16248 With argument, move up ARG levels."
16249 (if (fboundp 'outline-up-heading-all)
16250 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16251 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16253 (defun org-up-heading-safe ()
16254 "Move to the heading line of which the present line is a subheading.
16255 This version will not throw an error. It will return the level of the
16256 headline found, or nil if no higher level is found.
16258 Also, this function will be a lot faster than `outline-up-heading',
16259 because it relies on stars being the outline starters. This can really
16260 make a significant difference in outlines with very many siblings."
16261 (let (start-level re)
16262 (org-back-to-heading t)
16263 (setq start-level (funcall outline-level))
16264 (if (equal start-level 1)
16266 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16267 (if (re-search-backward re nil t)
16268 (funcall outline-level)))))
16270 (defun org-first-sibling-p ()
16271 "Is this heading the first child of its parents?"
16272 (interactive)
16273 (let ((re (concat "^" outline-regexp))
16274 level l)
16275 (unless (org-at-heading-p t)
16276 (error "Not at a heading"))
16277 (setq level (funcall outline-level))
16278 (save-excursion
16279 (if (not (re-search-backward re nil t))
16281 (setq l (funcall outline-level))
16282 (< l level)))))
16284 (defun org-goto-sibling (&optional previous)
16285 "Goto the next sibling, even if it is invisible.
16286 When PREVIOUS is set, go to the previous sibling instead. Returns t
16287 when a sibling was found. When none is found, return nil and don't
16288 move point."
16289 (let ((fun (if previous 're-search-backward 're-search-forward))
16290 (pos (point))
16291 (re (concat "^" outline-regexp))
16292 level l)
16293 (when (condition-case nil (org-back-to-heading t) (error nil))
16294 (setq level (funcall outline-level))
16295 (catch 'exit
16296 (or previous (forward-char 1))
16297 (while (funcall fun re nil t)
16298 (setq l (funcall outline-level))
16299 (when (< l level) (goto-char pos) (throw 'exit nil))
16300 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16301 (goto-char pos)
16302 nil))))
16304 (defun org-show-siblings ()
16305 "Show all siblings of the current headline."
16306 (save-excursion
16307 (while (org-goto-sibling) (org-flag-heading nil)))
16308 (save-excursion
16309 (while (org-goto-sibling 'previous)
16310 (org-flag-heading nil))))
16312 (defun org-show-hidden-entry ()
16313 "Show an entry where even the heading is hidden."
16314 (save-excursion
16315 (org-show-entry)))
16317 (defun org-flag-heading (flag &optional entry)
16318 "Flag the current heading. FLAG non-nil means make invisible.
16319 When ENTRY is non-nil, show the entire entry."
16320 (save-excursion
16321 (org-back-to-heading t)
16322 ;; Check if we should show the entire entry
16323 (if entry
16324 (progn
16325 (org-show-entry)
16326 (save-excursion
16327 (and (outline-next-heading)
16328 (org-flag-heading nil))))
16329 (outline-flag-region (max (point-min) (1- (point)))
16330 (save-excursion (outline-end-of-heading) (point))
16331 flag))))
16333 (defun org-forward-same-level (arg)
16334 "Move forward to the ARG'th subheading at same level as this one.
16335 Stop at the first and last subheadings of a superior heading.
16336 This is like outline-forward-same-level, but invisible headings are ok."
16337 (interactive "p")
16338 (org-back-to-heading t)
16339 (while (> arg 0)
16340 (let ((point-to-move-to (save-excursion
16341 (org-get-next-sibling))))
16342 (if point-to-move-to
16343 (progn
16344 (goto-char point-to-move-to)
16345 (setq arg (1- arg)))
16346 (progn
16347 (setq arg 0)
16348 (error "No following same-level heading"))))))
16350 (defun org-get-next-sibling ()
16351 "Move to next heading of the same level, and return point.
16352 If there is no such heading, return nil.
16353 This is like outline-next-sibling, but invisible headings are ok."
16354 (let ((level (funcall outline-level)))
16355 (outline-next-heading)
16356 (while (and (not (eobp)) (> (funcall outline-level) level))
16357 (outline-next-heading))
16358 (if (or (eobp) (< (funcall outline-level) level))
16360 (point))))
16362 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16363 ;; This contains an exact copy of the original function, but it uses
16364 ;; `org-back-to-heading', to make it work also in invisible
16365 ;; trees. And is uses an invisible-OK argument.
16366 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16367 ;; Furthermore, when used inside Org, finding the end of a large subtree
16368 ;; with many children and grandchildren etc, this can be much faster
16369 ;; than the outline version.
16370 (org-back-to-heading invisible-OK)
16371 (let ((first t)
16372 (level (funcall outline-level)))
16373 (if (and (org-mode-p) (< level 1000))
16374 ;; A true heading (not a plain list item), in Org-mode
16375 ;; This means we can easily find the end by looking
16376 ;; only for the right number of stars. Using a regexp to do
16377 ;; this is so much faster than using a Lisp loop.
16378 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16379 (forward-char 1)
16380 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16381 ;; something else, do it the slow way
16382 (while (and (not (eobp))
16383 (or first (> (funcall outline-level) level)))
16384 (setq first nil)
16385 (outline-next-heading)))
16386 (unless to-heading
16387 (if (memq (preceding-char) '(?\n ?\^M))
16388 (progn
16389 ;; Go to end of line before heading
16390 (forward-char -1)
16391 (if (memq (preceding-char) '(?\n ?\^M))
16392 ;; leave blank line before heading
16393 (forward-char -1))))))
16394 (point))
16396 (defun org-show-subtree ()
16397 "Show everything after this heading at deeper levels."
16398 (outline-flag-region
16399 (point)
16400 (save-excursion
16401 (outline-end-of-subtree) (outline-next-heading) (point))
16402 nil))
16404 (defun org-show-entry ()
16405 "Show the body directly following this heading.
16406 Show the heading too, if it is currently invisible."
16407 (interactive)
16408 (save-excursion
16409 (condition-case nil
16410 (progn
16411 (org-back-to-heading t)
16412 (outline-flag-region
16413 (max (point-min) (1- (point)))
16414 (save-excursion
16415 (if (re-search-forward
16416 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16417 (match-beginning 1)
16418 (point-max)))
16419 nil)
16420 (org-cycle-hide-drawers 'children))
16421 (error nil))))
16423 (defun org-make-options-regexp (kwds &optional extra)
16424 "Make a regular expression for keyword lines."
16425 (concat
16427 "#?[ \t]*\\+\\("
16428 (mapconcat 'regexp-quote kwds "\\|")
16429 (if extra (concat "\\|" extra))
16430 "\\):[ \t]*"
16431 "\\(.+\\)"))
16433 ;; Make isearch reveal the necessary context
16434 (defun org-isearch-end ()
16435 "Reveal context after isearch exits."
16436 (when isearch-success ; only if search was successful
16437 (if (featurep 'xemacs)
16438 ;; Under XEmacs, the hook is run in the correct place,
16439 ;; we directly show the context.
16440 (org-show-context 'isearch)
16441 ;; In Emacs the hook runs *before* restoring the overlays.
16442 ;; So we have to use a one-time post-command-hook to do this.
16443 ;; (Emacs 22 has a special variable, see function `org-mode')
16444 (unless (and (boundp 'isearch-mode-end-hook-quit)
16445 isearch-mode-end-hook-quit)
16446 ;; Only when the isearch was not quitted.
16447 (org-add-hook 'post-command-hook 'org-isearch-post-command
16448 'append 'local)))))
16450 (defun org-isearch-post-command ()
16451 "Remove self from hook, and show context."
16452 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16453 (org-show-context 'isearch))
16456 ;;;; Integration with and fixes for other packages
16458 ;;; Imenu support
16460 (defvar org-imenu-markers nil
16461 "All markers currently used by Imenu.")
16462 (make-variable-buffer-local 'org-imenu-markers)
16464 (defun org-imenu-new-marker (&optional pos)
16465 "Return a new marker for use by Imenu, and remember the marker."
16466 (let ((m (make-marker)))
16467 (move-marker m (or pos (point)))
16468 (push m org-imenu-markers)
16471 (defun org-imenu-get-tree ()
16472 "Produce the index for Imenu."
16473 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16474 (setq org-imenu-markers nil)
16475 (let* ((n org-imenu-depth)
16476 (re (concat "^" outline-regexp))
16477 (subs (make-vector (1+ n) nil))
16478 (last-level 0)
16479 m level head)
16480 (save-excursion
16481 (save-restriction
16482 (widen)
16483 (goto-char (point-max))
16484 (while (re-search-backward re nil t)
16485 (setq level (org-reduced-level (funcall outline-level)))
16486 (when (<= level n)
16487 (looking-at org-complex-heading-regexp)
16488 (setq head (org-link-display-format
16489 (org-match-string-no-properties 4))
16490 m (org-imenu-new-marker))
16491 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16492 (if (>= level last-level)
16493 (push (cons head m) (aref subs level))
16494 (push (cons head (aref subs (1+ level))) (aref subs level))
16495 (loop for i from (1+ level) to n do (aset subs i nil)))
16496 (setq last-level level)))))
16497 (aref subs 1)))
16499 (eval-after-load "imenu"
16500 '(progn
16501 (add-hook 'imenu-after-jump-hook
16502 (lambda ()
16503 (if (eq major-mode 'org-mode)
16504 (org-show-context 'org-goto))))))
16506 (defun org-link-display-format (link)
16507 "Replace a link with either the description, or the link target
16508 if no description is present"
16509 (save-match-data
16510 (if (string-match org-bracket-link-analytic-regexp link)
16511 (replace-match (or (match-string 5 link)
16512 (concat (match-string 1 link)
16513 (match-string 3 link)))
16514 nil nil link)
16515 link)))
16517 ;; Speedbar support
16519 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16520 "Overlay marking the agenda restriction line in speedbar.")
16521 (org-overlay-put org-speedbar-restriction-lock-overlay
16522 'face 'org-agenda-restriction-lock)
16523 (org-overlay-put org-speedbar-restriction-lock-overlay
16524 'help-echo "Agendas are currently limited to this item.")
16525 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16527 (defun org-speedbar-set-agenda-restriction ()
16528 "Restrict future agenda commands to the location at point in speedbar.
16529 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16530 (interactive)
16531 (require 'org-agenda)
16532 (let (p m tp np dir txt)
16533 (cond
16534 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16535 'org-imenu t))
16536 (setq m (get-text-property p 'org-imenu-marker))
16537 (save-excursion
16538 (save-restriction
16539 (set-buffer (marker-buffer m))
16540 (goto-char m)
16541 (org-agenda-set-restriction-lock 'subtree))))
16542 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16543 'speedbar-function 'speedbar-find-file))
16544 (setq tp (previous-single-property-change
16545 (1+ p) 'speedbar-function)
16546 np (next-single-property-change
16547 tp 'speedbar-function)
16548 dir (speedbar-line-directory)
16549 txt (buffer-substring-no-properties (or tp (point-min))
16550 (or np (point-max))))
16551 (save-excursion
16552 (save-restriction
16553 (set-buffer (find-file-noselect
16554 (let ((default-directory dir))
16555 (expand-file-name txt))))
16556 (unless (org-mode-p)
16557 (error "Cannot restrict to non-Org-mode file"))
16558 (org-agenda-set-restriction-lock 'file))))
16559 (t (error "Don't know how to restrict Org-mode's agenda")))
16560 (org-move-overlay org-speedbar-restriction-lock-overlay
16561 (point-at-bol) (point-at-eol))
16562 (setq current-prefix-arg nil)
16563 (org-agenda-maybe-redo)))
16565 (eval-after-load "speedbar"
16566 '(progn
16567 (speedbar-add-supported-extension ".org")
16568 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16569 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16570 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16571 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16572 (add-hook 'speedbar-visiting-tag-hook
16573 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16576 ;;; Fixes and Hacks for problems with other packages
16578 ;; Make flyspell not check words in links, to not mess up our keymap
16579 (defun org-mode-flyspell-verify ()
16580 "Don't let flyspell put overlays at active buttons."
16581 (and (not (get-text-property (point) 'keymap))
16582 (not (get-text-property (point) 'org-no-flyspell))))
16584 (defun org-remove-flyspell-overlays-in (beg end)
16585 "Remove flyspell overlays in region."
16586 (and (org-bound-and-true-p flyspell-mode)
16587 (fboundp 'flyspell-delete-region-overlays)
16588 (flyspell-delete-region-overlays beg end))
16589 (add-text-properties beg end '(org-no-flyspell t)))
16591 ;; Make `bookmark-jump' show the jump location if it was hidden.
16592 (eval-after-load "bookmark"
16593 '(if (boundp 'bookmark-after-jump-hook)
16594 ;; We can use the hook
16595 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16596 ;; Hook not available, use advice
16597 (defadvice bookmark-jump (after org-make-visible activate)
16598 "Make the position visible."
16599 (org-bookmark-jump-unhide))))
16601 ;; Make sure saveplace show the location if it was hidden
16602 (eval-after-load "saveplace"
16603 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16604 "Make the position visible."
16605 (org-bookmark-jump-unhide)))
16607 (defun org-bookmark-jump-unhide ()
16608 "Unhide the current position, to show the bookmark location."
16609 (and (org-mode-p)
16610 (or (org-invisible-p)
16611 (save-excursion (goto-char (max (point-min) (1- (point))))
16612 (org-invisible-p)))
16613 (org-show-context 'bookmark-jump)))
16615 ;; Make session.el ignore our circular variable
16616 (eval-after-load "session"
16617 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16619 ;;;; Experimental code
16621 (defun org-closed-in-range ()
16622 "Sparse tree of items closed in a certain time range.
16623 Still experimental, may disappear in the future."
16624 (interactive)
16625 ;; Get the time interval from the user.
16626 (let* ((time1 (time-to-seconds
16627 (org-read-date nil 'to-time nil "Starting date: ")))
16628 (time2 (time-to-seconds
16629 (org-read-date nil 'to-time nil "End date:")))
16630 ;; callback function
16631 (callback (lambda ()
16632 (let ((time
16633 (time-to-seconds
16634 (apply 'encode-time
16635 (org-parse-time-string
16636 (match-string 1))))))
16637 ;; check if time in interval
16638 (and (>= time time1) (<= time time2))))))
16639 ;; make tree, check each match with the callback
16640 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16642 ;;;; Finish up
16644 (provide 'org)
16646 (run-hooks 'org-load-hook)
16648 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16650 ;;; org.el ends here