HTML export: Move home/up link div into the content div
[org-mode.git] / lisp / org.el
blob74540276d9bf60a2a026d27415af8d4e3b13201e
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.33trans
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.33trans"
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* ((origin default-directory)
106 (version org-version)
107 (git-version)
108 (dir (concat (file-name-directory (locate-library "org")) "../" )))
109 (when (and (file-exists-p (expand-file-name ".git" dir))
110 (executable-find "git"))
111 (unwind-protect
112 (progn
113 (cd dir)
114 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
115 (with-current-buffer "*Shell Command Output*"
116 (goto-char (point-min))
117 (setq git-version (buffer-substring (point) (point-at-eol))))
118 (subst-char-in-string ?- ?. git-version t)
119 (when (string-match "\\S-"
120 (shell-command-to-string
121 "git diff-index --name-only HEAD --"))
122 (setq git-version (concat git-version ".dirty")))
123 (setq version (concat version " (" git-version ")"))))
124 (cd origin)))
125 (setq version (format "Org-mode version %s" version))
126 (if here (insert version))
127 (message version)))
129 ;;; Compatibility constants
131 ;;; The custom variables
133 (defgroup org nil
134 "Outline-based notes management and organizer."
135 :tag "Org"
136 :group 'outlines
137 :group 'hypermedia
138 :group 'calendar)
140 (defcustom org-mode-hook nil
141 "Mode hook for Org-mode, run after the mode was turned on."
142 :group 'org
143 :type 'hook)
145 (defcustom org-load-hook nil
146 "Hook that is run after org.el has been loaded."
147 :group 'org
148 :type 'hook)
150 (defvar org-modules) ; defined below
151 (defvar org-modules-loaded nil
152 "Have the modules been loaded already?")
154 (defun org-load-modules-maybe (&optional force)
155 "Load all extensions listed in `org-modules'."
156 (when (or force (not org-modules-loaded))
157 (mapc (lambda (ext)
158 (condition-case nil (require ext)
159 (error (message "Problems while trying to load feature `%s'" ext))))
160 org-modules)
161 (setq org-modules-loaded t)))
163 (defun org-set-modules (var value)
164 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
165 (set var value)
166 (when (featurep 'org)
167 (org-load-modules-maybe 'force)))
169 (when (org-bound-and-true-p org-modules)
170 (let ((a (member 'org-infojs org-modules)))
171 (and a (setcar a 'org-jsinfo))))
173 (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)
174 "Modules that should always be loaded together with org.el.
175 If a description starts with <C>, the file is not part of Emacs
176 and loading it will require that you have downloaded and properly installed
177 the org-mode distribution.
179 You can also use this system to load external packages (i.e. neither Org
180 core modules, nor modules from the CONTRIB directory). Just add symbols
181 to the end of the list. If the package is called org-xyz.el, then you need
182 to add the symbol `xyz', and the package must have a call to
184 (provide 'org-xyz)"
185 :group 'org
186 :set 'org-set-modules
187 :type
188 '(set :greedy t
189 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
190 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
191 (const :tag " crypt: Encryption of subtrees" org-crypt)
192 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
193 (const :tag " id: Global IDs for identifying entries" org-id)
194 (const :tag " info: Links to Info nodes" org-info)
195 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
196 (const :tag " habit: Track your consistency with habits" org-habit)
197 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
198 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
199 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
200 (const :tag " mew Links to Mew folders/messages" org-mew)
201 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
202 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
203 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
204 (const :tag " vm: Links to VM folders/messages" org-vm)
205 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
206 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
207 (const :tag " mouse: Additional mouse support" org-mouse)
209 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
210 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
211 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
212 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
213 (const :tag "C collector: Collect properties into tables" org-collector)
214 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
215 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
216 (const :tag "C eval: Include command output as text" org-eval)
217 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
218 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
219 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
220 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
221 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
223 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
225 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
226 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
227 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
228 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
229 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
230 (const :tag "C mtags: Support for muse-like tags" org-mtags)
231 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
232 (const :tag "C R: Computation using the R language" org-R)
233 (const :tag "C registry: A registry for Org-mode links" org-registry)
234 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
235 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
236 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
237 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
238 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
239 (const :tag "C track: Keep up with Org-mode development" org-track)
240 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
242 (defcustom org-support-shift-select nil
243 "Non-nil means, make shift-cursor commands select text when possible.
245 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
246 selecting a region, or enlarge thusly regions started in this way.
247 In Org-mode, in special contexts, these same keys are used for other
248 purposes, important enough to compete with shift selection. Org tries
249 to balance these needs by supporting `shift-select-mode' outside these
250 special contexts, under control of this variable.
252 The default of this variable is nil, to avoid confusing behavior. Shifted
253 cursor keys will then execute Org commands in the following contexts:
254 - on a headline, changing TODO state (left/right) and priority (up/down)
255 - on a time stamp, changing the time
256 - in a plain list item, changing the bullet type
257 - in a property definition line, switching between allowed values
258 - in the BEGIN line of a clock table (changing the time block).
259 Outside these contexts, the commands will throw an error.
261 When this variable is t and the cursor is not in a special context,
262 Org-mode will support shift-selection for making and enlarging regions.
263 To make this more effective, the bullet cycling will no longer happen
264 anywhere in an item line, but only if the cursor is exactly on the bullet.
266 If you set this variable to the symbol `always', then the keys
267 will not be special in headlines, property lines, and item lines, to make
268 shift selection work there as well. If this is what you want, you can
269 use the following alternative commands: `C-c C-t' and `C-c ,' to
270 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
271 TODO sets, `C-c -' to cycle item bullet types, and properties can be
272 edited by hand or in column view.
274 However, when the cursor is on a timestamp, shift-cursor commands
275 will still edit the time stamp - this is just too good to give up.
277 XEmacs user should have this variable set to nil, because shift-select-mode
278 is Emacs 23 only."
279 :group 'org
280 :type '(choice
281 (const :tag "Never" nil)
282 (const :tag "When outside special context" t)
283 (const :tag "Everywhere except timestamps" always)))
285 (defgroup org-startup nil
286 "Options concerning startup of Org-mode."
287 :tag "Org Startup"
288 :group 'org)
290 (defcustom org-startup-folded t
291 "Non-nil means, entering Org-mode will switch to OVERVIEW.
292 This can also be configured on a per-file basis by adding one of
293 the following lines anywhere in the buffer:
295 #+STARTUP: fold (or `overview', this is equivalent)
296 #+STARTUP: nofold (or `showall', this is equivalent)
297 #+STARTUP: content
298 #+STARTUP: showeverything"
299 :group 'org-startup
300 :type '(choice
301 (const :tag "nofold: show all" nil)
302 (const :tag "fold: overview" t)
303 (const :tag "content: all headlines" content)
304 (const :tag "show everything, even drawers" showeverything)))
306 (defcustom org-startup-truncated t
307 "Non-nil means, entering Org-mode will set `truncate-lines'.
308 This is useful since some lines containing links can be very long and
309 uninteresting. Also tables look terrible when wrapped."
310 :group 'org-startup
311 :type 'boolean)
313 (defcustom org-startup-indented nil
314 "Non-nil means, turn on `org-indent-mode' on startup.
315 This can also be configured on a per-file basis by adding one of
316 the following lines anywhere in the buffer:
318 #+STARTUP: indent
319 #+STARTUP: noindent"
320 :group 'org-structure
321 :type '(choice
322 (const :tag "Not" nil)
323 (const :tag "Globally (slow on startup in large files)" t)))
325 (defcustom org-startup-align-all-tables nil
326 "Non-nil means, align all tables when visiting a file.
327 This is useful when the column width in tables is forced with <N> cookies
328 in table fields. Such tables will look correct only after the first re-align.
329 This can also be configured on a per-file basis by adding one of
330 the following lines anywhere in the buffer:
331 #+STARTUP: align
332 #+STARTUP: noalign"
333 :group 'org-startup
334 :type 'boolean)
336 (defcustom org-insert-mode-line-in-empty-file nil
337 "Non-nil means insert the first line setting Org-mode in empty files.
338 When the function `org-mode' is called interactively in an empty file, this
339 normally means that the file name does not automatically trigger Org-mode.
340 To ensure that the file will always be in Org-mode in the future, a
341 line enforcing Org-mode will be inserted into the buffer, if this option
342 has been set."
343 :group 'org-startup
344 :type 'boolean)
346 (defcustom org-replace-disputed-keys nil
347 "Non-nil means use alternative key bindings for some keys.
348 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
349 These keys are also used by other packages like shift-selection-mode'
350 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
351 If you want to use Org-mode together with one of these other modes,
352 or more generally if you would like to move some Org-mode commands to
353 other keys, set this variable and configure the keys with the variable
354 `org-disputed-keys'.
356 This option is only relevant at load-time of Org-mode, and must be set
357 *before* org.el is loaded. Changing it requires a restart of Emacs to
358 become effective."
359 :group 'org-startup
360 :type 'boolean)
362 (defcustom org-use-extra-keys nil
363 "Non-nil means use extra key sequence definitions for certain
364 commands. This happens automatically if you run XEmacs or if
365 window-system is nil. This variable lets you do the same
366 manually. You must set it before loading org.
368 Example: on Carbon Emacs 22 running graphically, with an external
369 keyboard on a Powerbook, the default way of setting M-left might
370 not work for either Alt or ESC. Setting this variable will make
371 it work for ESC."
372 :group 'org-startup
373 :type 'boolean)
375 (if (fboundp 'defvaralias)
376 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
378 (defcustom org-disputed-keys
379 '(([(shift up)] . [(meta p)])
380 ([(shift down)] . [(meta n)])
381 ([(shift left)] . [(meta -)])
382 ([(shift right)] . [(meta +)])
383 ([(control shift right)] . [(meta shift +)])
384 ([(control shift left)] . [(meta shift -)]))
385 "Keys for which Org-mode and other modes compete.
386 This is an alist, cars are the default keys, second element specifies
387 the alternative to use when `org-replace-disputed-keys' is t.
389 Keys can be specified in any syntax supported by `define-key'.
390 The value of this option takes effect only at Org-mode's startup,
391 therefore you'll have to restart Emacs to apply it after changing."
392 :group 'org-startup
393 :type 'alist)
395 (defun org-key (key)
396 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
397 Or return the original if not disputed."
398 (if org-replace-disputed-keys
399 (let* ((nkey (key-description key))
400 (x (org-find-if (lambda (x)
401 (equal (key-description (car x)) nkey))
402 org-disputed-keys)))
403 (if x (cdr x) key))
404 key))
406 (defun org-find-if (predicate seq)
407 (catch 'exit
408 (while seq
409 (if (funcall predicate (car seq))
410 (throw 'exit (car seq))
411 (pop seq)))))
413 (defun org-defkey (keymap key def)
414 "Define a key, possibly translated, as returned by `org-key'."
415 (define-key keymap (org-key key) def))
417 (defcustom org-ellipsis nil
418 "The ellipsis to use in the Org-mode outline.
419 When nil, just use the standard three dots. When a string, use that instead,
420 When a face, use the standard 3 dots, but with the specified face.
421 The change affects only Org-mode (which will then use its own display table).
422 Changing this requires executing `M-x org-mode' in a buffer to become
423 effective."
424 :group 'org-startup
425 :type '(choice (const :tag "Default" nil)
426 (face :tag "Face" :value org-warning)
427 (string :tag "String" :value "...#")))
429 (defvar org-display-table nil
430 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
432 (defgroup org-keywords nil
433 "Keywords in Org-mode."
434 :tag "Org Keywords"
435 :group 'org)
437 (defcustom org-deadline-string "DEADLINE:"
438 "String to mark deadline entries.
439 A deadline is this string, followed by a time stamp. Should be a word,
440 terminated by a colon. You can insert a schedule keyword and
441 a timestamp with \\[org-deadline].
442 Changes become only effective after restarting Emacs."
443 :group 'org-keywords
444 :type 'string)
446 (defcustom org-scheduled-string "SCHEDULED:"
447 "String to mark scheduled TODO entries.
448 A schedule is this string, followed by a time stamp. Should be a word,
449 terminated by a colon. You can insert a schedule keyword and
450 a timestamp with \\[org-schedule].
451 Changes become only effective after restarting Emacs."
452 :group 'org-keywords
453 :type 'string)
455 (defcustom org-closed-string "CLOSED:"
456 "String used as the prefix for timestamps logging closing a TODO entry."
457 :group 'org-keywords
458 :type 'string)
460 (defcustom org-clock-string "CLOCK:"
461 "String used as prefix for timestamps clocking work hours on an item."
462 :group 'org-keywords
463 :type 'string)
465 (defcustom org-comment-string "COMMENT"
466 "Entries starting with this keyword will never be exported.
467 An entry can be toggled between COMMENT and normal with
468 \\[org-toggle-comment].
469 Changes become only effective after restarting Emacs."
470 :group 'org-keywords
471 :type 'string)
473 (defcustom org-quote-string "QUOTE"
474 "Entries starting with this keyword will be exported in fixed-width font.
475 Quoting applies only to the text in the entry following the headline, and does
476 not extend beyond the next headline, even if that is lower level.
477 An entry can be toggled between QUOTE and normal with
478 \\[org-toggle-fixed-width-section]."
479 :group 'org-keywords
480 :type 'string)
482 (defconst org-repeat-re
483 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
484 "Regular expression for specifying repeated events.
485 After a match, group 1 contains the repeat expression.")
487 (defgroup org-structure nil
488 "Options concerning the general structure of Org-mode files."
489 :tag "Org Structure"
490 :group 'org)
492 (defgroup org-reveal-location nil
493 "Options about how to make context of a location visible."
494 :tag "Org Reveal Location"
495 :group 'org-structure)
497 (defconst org-context-choice
498 '(choice
499 (const :tag "Always" t)
500 (const :tag "Never" nil)
501 (repeat :greedy t :tag "Individual contexts"
502 (cons
503 (choice :tag "Context"
504 (const agenda)
505 (const org-goto)
506 (const occur-tree)
507 (const tags-tree)
508 (const link-search)
509 (const mark-goto)
510 (const bookmark-jump)
511 (const isearch)
512 (const default))
513 (boolean))))
514 "Contexts for the reveal options.")
516 (defcustom org-show-hierarchy-above '((default . t))
517 "Non-nil means, show full hierarchy when revealing a location.
518 Org-mode often shows locations in an org-mode file which might have
519 been invisible before. When this is set, the hierarchy of headings
520 above the exposed location is shown.
521 Turning this off for example for sparse trees makes them very compact.
522 Instead of t, this can also be an alist specifying this option for different
523 contexts. Valid contexts are
524 agenda when exposing an entry from the agenda
525 org-goto when using the command `org-goto' on key C-c C-j
526 occur-tree when using the command `org-occur' on key C-c /
527 tags-tree when constructing a sparse tree based on tags matches
528 link-search when exposing search matches associated with a link
529 mark-goto when exposing the jump goal of a mark
530 bookmark-jump when exposing a bookmark location
531 isearch when exiting from an incremental search
532 default default for all contexts not set explicitly"
533 :group 'org-reveal-location
534 :type org-context-choice)
536 (defcustom org-show-following-heading '((default . nil))
537 "Non-nil means, show following heading when revealing a location.
538 Org-mode often shows locations in an org-mode file which might have
539 been invisible before. When this is set, the heading following the
540 match is shown.
541 Turning this off for example for sparse trees makes them very compact,
542 but makes it harder to edit the location of the match. In such a case,
543 use the command \\[org-reveal] to show more context.
544 Instead of t, this can also be an alist specifying this option for different
545 contexts. See `org-show-hierarchy-above' for valid contexts."
546 :group 'org-reveal-location
547 :type org-context-choice)
549 (defcustom org-show-siblings '((default . nil) (isearch t))
550 "Non-nil means, show all sibling heading when revealing a location.
551 Org-mode often shows locations in an org-mode file which might have
552 been invisible before. When this is set, the sibling of the current entry
553 heading are all made visible. If `org-show-hierarchy-above' is t,
554 the same happens on each level of the hierarchy above the current entry.
556 By default this is on for the isearch context, off for all other contexts.
557 Turning this off for example for sparse trees makes them very compact,
558 but makes it harder to edit the location of the match. In such a case,
559 use the command \\[org-reveal] to show more context.
560 Instead of t, this can also be an alist specifying this option for different
561 contexts. See `org-show-hierarchy-above' for valid contexts."
562 :group 'org-reveal-location
563 :type org-context-choice)
565 (defcustom org-show-entry-below '((default . nil))
566 "Non-nil means, show the entry below a headline when revealing a location.
567 Org-mode often shows locations in an org-mode file which might have
568 been invisible before. When this is set, the text below the headline that is
569 exposed is also shown.
571 By default this is off for all contexts.
572 Instead of t, this can also be an alist specifying this option for different
573 contexts. See `org-show-hierarchy-above' for valid contexts."
574 :group 'org-reveal-location
575 :type org-context-choice)
577 (defcustom org-indirect-buffer-display 'other-window
578 "How should indirect tree buffers be displayed?
579 This applies to indirect buffers created with the commands
580 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
581 Valid values are:
582 current-window Display in the current window
583 other-window Just display in another window.
584 dedicated-frame Create one new frame, and re-use it each time.
585 new-frame Make a new frame each time. Note that in this case
586 previously-made indirect buffers are kept, and you need to
587 kill these buffers yourself."
588 :group 'org-structure
589 :group 'org-agenda-windows
590 :type '(choice
591 (const :tag "In current window" current-window)
592 (const :tag "In current frame, other window" other-window)
593 (const :tag "Each time a new frame" new-frame)
594 (const :tag "One dedicated frame" dedicated-frame)))
596 (defcustom org-use-speed-commands nil
597 "Non-nil means, activate single letter commands at beginning of a headline.
598 This may also be a function to test for appropriate locations where speed
599 commands should be active."
600 :group 'org-structure
601 :type '(choice
602 (const :tag "Never" nil)
603 (const :tag "At beginning of headline stars" t)
604 (function)))
606 (defcustom org-speed-commands-user nil
607 "Alist of additional speed commands.
608 This list will be checked before `org-speed-commands-default'
609 when the variable `org-use-speed-commands' is non-nil
610 and when the cursor is at the beginning of a headline.
611 The car if each entry is a string with a single letter, which must
612 be assigned to `self-insert-command' in the global map.
613 The cdr is either a command to be called interactively, a function
614 to be called, or a form to be evaluated.
615 An entry that is just a list with a single string will be interpreted
616 as a descriptive headline that will be added when listing the speed
617 copmmands in the Help buffer using the `?' speed command."
618 :group 'org-structure
619 :type '(repeat :value ("k" . ignore)
620 (choice :value ("k" . ignore)
621 (list :tag "Descriptive Headline" (string :tag "Headline"))
622 (cons :tag "Letter and Command"
623 (string :tag "Command letter")
624 (choice
625 (function)
626 (sexp))))))
628 (defgroup org-cycle nil
629 "Options concerning visibility cycling in Org-mode."
630 :tag "Org Cycle"
631 :group 'org-structure)
633 (defcustom org-cycle-skip-children-state-if-no-children t
634 "Non-nil means, skip CHILDREN state in entries that don't have any."
635 :group 'org-cycle
636 :type 'boolean)
638 (defcustom org-cycle-max-level nil
639 "Maximum level which should still be subject to visibility cycling.
640 Levels higher than this will, for cycling, be treated as text, not a headline.
641 When `org-odd-levels-only' is set, a value of N in this variable actually
642 means 2N-1 stars as the limiting headline.
643 When nil, cycle all levels.
644 Note that the limiting level of cycling is also influenced by
645 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
646 `org-inlinetask-min-level' is, cycling will be limited to levels one less
647 than its value."
648 :group 'org-cycle
649 :type '(choice
650 (const :tag "No limit" nil)
651 (integer :tag "Maximum level")))
653 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
654 "Names of drawers. Drawers are not opened by cycling on the headline above.
655 Drawers only open with a TAB on the drawer line itself. A drawer looks like
656 this:
657 :DRAWERNAME:
658 .....
659 :END:
660 The drawer \"PROPERTIES\" is special for capturing properties through
661 the property API.
663 Drawers can be defined on the per-file basis with a line like:
665 #+DRAWERS: HIDDEN STATE PROPERTIES"
666 :group 'org-structure
667 :group 'org-cycle
668 :type '(repeat (string :tag "Drawer Name")))
670 (defcustom org-hide-block-startup nil
671 "Non-nil means, , entering Org-mode will fold all blocks.
672 This can also be set in on a per-file basis with
674 #+STARTUP: hideblocks
675 #+STARTUP: showblocks"
676 :group 'org-startup
677 :group 'org-cycle
678 :type 'boolean)
680 (defcustom org-cycle-global-at-bob nil
681 "Cycle globally if cursor is at beginning of buffer and not at a headline.
682 This makes it possible to do global cycling without having to use S-TAB or
683 C-u TAB. For this special case to work, the first line of the buffer
684 must not be a headline - it may be empty or some other text. When used in
685 this way, `org-cycle-hook' is disables temporarily, to make sure the
686 cursor stays at the beginning of the buffer.
687 When this option is nil, don't do anything special at the beginning
688 of the buffer."
689 :group 'org-cycle
690 :type 'boolean)
692 (defcustom org-cycle-level-after-item/entry-creation t
693 "Non-nil means, cycle entry level or item indentation in new empty entries.
695 When the cursor is at the end of an empty headline, i.e with only stars
696 and maybe a TODO keyword, TAB will then switch the entry to become a child,
697 and then all possible anchestor states, before returning to the original state.
698 This makes data entry extremely fast: M-RET to create a new headline,
699 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
701 When the cursor is at the end of an empty plain list item, one TAB will
702 make it a subitem, two or more tabs will back up to make this an item
703 higher up in the item hierarchy."
704 :group 'org-cycle
705 :type 'boolean)
707 (defcustom org-cycle-emulate-tab t
708 "Where should `org-cycle' emulate TAB.
709 nil Never
710 white Only in completely white lines
711 whitestart Only at the beginning of lines, before the first non-white char
712 t Everywhere except in headlines
713 exc-hl-bol Everywhere except at the start of a headline
714 If TAB is used in a place where it does not emulate TAB, the current subtree
715 visibility is cycled."
716 :group 'org-cycle
717 :type '(choice (const :tag "Never" nil)
718 (const :tag "Only in completely white lines" white)
719 (const :tag "Before first char in a line" whitestart)
720 (const :tag "Everywhere except in headlines" t)
721 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
724 (defcustom org-cycle-separator-lines 2
725 "Number of empty lines needed to keep an empty line between collapsed trees.
726 If you leave an empty line between the end of a subtree and the following
727 headline, this empty line is hidden when the subtree is folded.
728 Org-mode will leave (exactly) one empty line visible if the number of
729 empty lines is equal or larger to the number given in this variable.
730 So the default 2 means, at least 2 empty lines after the end of a subtree
731 are needed to produce free space between a collapsed subtree and the
732 following headline.
734 If the number is negative, and the number of empty lines is at least -N,
735 all empty lines are shown.
737 Special case: when 0, never leave empty lines in collapsed view."
738 :group 'org-cycle
739 :type 'integer)
740 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
742 (defcustom org-pre-cycle-hook nil
743 "Hook that is run before visibility cycling is happening.
744 The function(s) in this hook must accept a single argument which indicates
745 the new state that will be set right after running this hook. The
746 argument is a symbol. Before a global state change, it can have the values
747 `overview', `content', or `all'. Before a local state change, it can have
748 the values `folded', `children', or `subtree'."
749 :group 'org-cycle
750 :type 'hook)
752 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
753 org-cycle-hide-drawers
754 org-cycle-show-empty-lines
755 org-optimize-window-after-visibility-change)
756 "Hook that is run after `org-cycle' has changed the buffer visibility.
757 The function(s) in this hook must accept a single argument which indicates
758 the new state that was set by the most recent `org-cycle' command. The
759 argument is a symbol. After a global state change, it can have the values
760 `overview', `content', or `all'. After a local state change, it can have
761 the values `folded', `children', or `subtree'."
762 :group 'org-cycle
763 :type 'hook)
765 (defgroup org-edit-structure nil
766 "Options concerning structure editing in Org-mode."
767 :tag "Org Edit Structure"
768 :group 'org-structure)
770 (defcustom org-odd-levels-only nil
771 "Non-nil means, skip even levels and only use odd levels for the outline.
772 This has the effect that two stars are being added/taken away in
773 promotion/demotion commands. It also influences how levels are
774 handled by the exporters.
775 Changing it requires restart of `font-lock-mode' to become effective
776 for fontification also in regions already fontified.
777 You may also set this on a per-file basis by adding one of the following
778 lines to the buffer:
780 #+STARTUP: odd
781 #+STARTUP: oddeven"
782 :group 'org-edit-structure
783 :group 'org-font-lock
784 :type 'boolean)
786 (defcustom org-adapt-indentation t
787 "Non-nil means, adapt indentation to outline node level.
789 When this variable is set, Org assumes that you write outlines by
790 indenting text in each node to align with the headline (after the stars).
791 The following issues are influenced by this variable:
793 - When this is set and the *entire* text in an entry is indented, the
794 indentation is increased by one space in a demotion command, and
795 decreased by one in a promotion command. If any line in the entry
796 body starts with text at column 0, indentation is not changed at all.
798 - Property drawers and planning information is inserted indented when
799 this variable s set. When nil, they will not be indented.
801 - TAB indents a line relative to context. The lines below a headline
802 will be indented when this variable is set.
804 Note that this is all about true indentation, by adding and removing
805 space characters. See also `org-indent.el' which does level-dependent
806 indentation in a virtual way, i.e. at display time in Emacs."
807 :group 'org-edit-structure
808 :type 'boolean)
810 (defcustom org-special-ctrl-a/e nil
811 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
813 When t, `C-a' will bring back the cursor to the beginning of the
814 headline text, i.e. after the stars and after a possible TODO keyword.
815 In an item, this will be the position after the bullet.
816 When the cursor is already at that position, another `C-a' will bring
817 it to the beginning of the line.
819 `C-e' will jump to the end of the headline, ignoring the presence of tags
820 in the headline. A second `C-e' will then jump to the true end of the
821 line, after any tags. This also means that, when this variable is
822 non-nil, `C-e' also will never jump beyond the end of the heading of a
823 folded section, i.e. not after the ellipses.
825 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
826 going to the true line boundary first. Only a directly following, identical
827 keypress will bring the cursor to the special positions.
829 This may also be a cons cell where the behavior for `C-a' and `C-e' is
830 set separately."
831 :group 'org-edit-structure
832 :type '(choice
833 (const :tag "off" nil)
834 (const :tag "on: after stars/bullet and before tags first" t)
835 (const :tag "reversed: true line boundary first" reversed)
836 (cons :tag "Set C-a and C-e separately"
837 (choice :tag "Special C-a"
838 (const :tag "off" nil)
839 (const :tag "on: after stars/bullet first" t)
840 (const :tag "reversed: before stars/bullet first" reversed))
841 (choice :tag "Special C-e"
842 (const :tag "off" nil)
843 (const :tag "on: before tags first" t)
844 (const :tag "reversed: after tags first" reversed)))))
845 (if (fboundp 'defvaralias)
846 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
848 (defcustom org-special-ctrl-k nil
849 "Non-nil means `C-k' will behave specially in headlines.
850 When nil, `C-k' will call the default `kill-line' command.
851 When t, the following will happen while the cursor is in the headline:
853 - When the cursor is at the beginning of a headline, kill the entire
854 line and possible the folded subtree below the line.
855 - When in the middle of the headline text, kill the headline up to the tags.
856 - When after the headline text, kill the tags."
857 :group 'org-edit-structure
858 :type 'boolean)
860 (defcustom org-yank-folded-subtrees t
861 "Non-nil means, when yanking subtrees, fold them.
862 If the kill is a single subtree, or a sequence of subtrees, i.e. if
863 it starts with a heading and all other headings in it are either children
864 or siblings, then fold all the subtrees. However, do this only if no
865 text after the yank would be swallowed into a folded tree by this action."
866 :group 'org-edit-structure
867 :type 'boolean)
869 (defcustom org-yank-adjusted-subtrees nil
870 "Non-nil means, when yanking subtrees, adjust the level.
871 With this setting, `org-paste-subtree' is used to insert the subtree, see
872 this function for details."
873 :group 'org-edit-structure
874 :type 'boolean)
876 (defcustom org-M-RET-may-split-line '((default . t))
877 "Non-nil means, M-RET will split the line at the cursor position.
878 When nil, it will go to the end of the line before making a
879 new line.
880 You may also set this option in a different way for different
881 contexts. Valid contexts are:
883 headline when creating a new headline
884 item when creating a new item
885 table in a table field
886 default the value to be used for all contexts not explicitly
887 customized"
888 :group 'org-structure
889 :group 'org-table
890 :type '(choice
891 (const :tag "Always" t)
892 (const :tag "Never" nil)
893 (repeat :greedy t :tag "Individual contexts"
894 (cons
895 (choice :tag "Context"
896 (const headline)
897 (const item)
898 (const table)
899 (const default))
900 (boolean)))))
903 (defcustom org-insert-heading-respect-content nil
904 "Non-nil means, insert new headings after the current subtree.
905 When nil, the new heading is created directly after the current line.
906 The commands \\[org-insert-heading-respect-content] and
907 \\[org-insert-todo-heading-respect-content] turn this variable on
908 for the duration of the command."
909 :group 'org-structure
910 :type 'boolean)
912 (defcustom org-blank-before-new-entry '((heading . auto)
913 (plain-list-item . auto))
914 "Should `org-insert-heading' leave a blank line before new heading/item?
915 The value is an alist, with `heading' and `plain-list-item' as car,
916 and a boolean flag as cdr. For plain lists, if the variable
917 `org-empty-line-terminates-plain-lists' is set, the setting here
918 is ignored and no empty line is inserted, to keep the list in tact."
919 :group 'org-edit-structure
920 :type '(list
921 (cons (const heading)
922 (choice (const :tag "Never" nil)
923 (const :tag "Always" t)
924 (const :tag "Auto" auto)))
925 (cons (const plain-list-item)
926 (choice (const :tag "Never" nil)
927 (const :tag "Always" t)
928 (const :tag "Auto" auto)))))
930 (defcustom org-insert-heading-hook nil
931 "Hook being run after inserting a new heading."
932 :group 'org-edit-structure
933 :type 'hook)
935 (defcustom org-enable-fixed-width-editor t
936 "Non-nil means, lines starting with \":\" are treated as fixed-width.
937 This currently only means, they are never auto-wrapped.
938 When nil, such lines will be treated like ordinary lines.
939 See also the QUOTE keyword."
940 :group 'org-edit-structure
941 :type 'boolean)
944 (defcustom org-goto-auto-isearch t
945 "Non-nil means, typing characters in org-goto starts incremental search."
946 :group 'org-edit-structure
947 :type 'boolean)
949 (defgroup org-sparse-trees nil
950 "Options concerning sparse trees in Org-mode."
951 :tag "Org Sparse Trees"
952 :group 'org-structure)
954 (defcustom org-highlight-sparse-tree-matches t
955 "Non-nil means, highlight all matches that define a sparse tree.
956 The highlights will automatically disappear the next time the buffer is
957 changed by an edit command."
958 :group 'org-sparse-trees
959 :type 'boolean)
961 (defcustom org-remove-highlights-with-change t
962 "Non-nil means, any change to the buffer will remove temporary highlights.
963 Such highlights are created by `org-occur' and `org-clock-display'.
964 When nil, `C-c C-c needs to be used to get rid of the highlights.
965 The highlights created by `org-preview-latex-fragment' always need
966 `C-c C-c' to be removed."
967 :group 'org-sparse-trees
968 :group 'org-time
969 :type 'boolean)
972 (defcustom org-occur-hook '(org-first-headline-recenter)
973 "Hook that is run after `org-occur' has constructed a sparse tree.
974 This can be used to recenter the window to show as much of the structure
975 as possible."
976 :group 'org-sparse-trees
977 :type 'hook)
979 (defgroup org-imenu-and-speedbar nil
980 "Options concerning imenu and speedbar in Org-mode."
981 :tag "Org Imenu and Speedbar"
982 :group 'org-structure)
984 (defcustom org-imenu-depth 2
985 "The maximum level for Imenu access to Org-mode headlines.
986 This also applied for speedbar access."
987 :group 'org-imenu-and-speedbar
988 :type 'integer)
990 (defgroup org-table nil
991 "Options concerning tables in Org-mode."
992 :tag "Org Table"
993 :group 'org)
995 (defcustom org-enable-table-editor 'optimized
996 "Non-nil means, lines starting with \"|\" are handled by the table editor.
997 When nil, such lines will be treated like ordinary lines.
999 When equal to the symbol `optimized', the table editor will be optimized to
1000 do the following:
1001 - Automatic overwrite mode in front of whitespace in table fields.
1002 This makes the structure of the table stay in tact as long as the edited
1003 field does not exceed the column width.
1004 - Minimize the number of realigns. Normally, the table is aligned each time
1005 TAB or RET are pressed to move to another field. With optimization this
1006 happens only if changes to a field might have changed the column width.
1007 Optimization requires replacing the functions `self-insert-command',
1008 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1009 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1010 very good at guessing when a re-align will be necessary, but you can always
1011 force one with \\[org-ctrl-c-ctrl-c].
1013 If you would like to use the optimized version in Org-mode, but the
1014 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1016 This variable can be used to turn on and off the table editor during a session,
1017 but in order to toggle optimization, a restart is required.
1019 See also the variable `org-table-auto-blank-field'."
1020 :group 'org-table
1021 :type '(choice
1022 (const :tag "off" nil)
1023 (const :tag "on" t)
1024 (const :tag "on, optimized" optimized)))
1026 (defcustom org-self-insert-cluster-for-undo t
1027 "Non-nil means cluster self-insert commands for undo when possible.
1028 If this is set, then, like in the Emacs command loop, 20 consecutive
1029 characters will be undone together.
1030 This is configurable, because there is some impact on typing performance."
1031 :group 'org-table
1032 :type 'boolean)
1034 (defcustom org-table-tab-recognizes-table.el t
1035 "Non-nil means, TAB will automatically notice a table.el table.
1036 When it sees such a table, it moves point into it and - if necessary -
1037 calls `table-recognize-table'."
1038 :group 'org-table-editing
1039 :type 'boolean)
1041 (defgroup org-link nil
1042 "Options concerning links in Org-mode."
1043 :tag "Org Link"
1044 :group 'org)
1046 (defvar org-link-abbrev-alist-local nil
1047 "Buffer-local version of `org-link-abbrev-alist', which see.
1048 The value of this is taken from the #+LINK lines.")
1049 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1051 (defcustom org-link-abbrev-alist nil
1052 "Alist of link abbreviations.
1053 The car of each element is a string, to be replaced at the start of a link.
1054 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1055 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1057 [[linkkey:tag][description]]
1059 The 'linkkey' must be a word word, starting with a letter, followed
1060 by letters, numbers, '-' or '_'.
1062 If REPLACE is a string, the tag will simply be appended to create the link.
1063 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1064 the placeholder \"%h\" will cause a url-encoded version of the tag to
1065 be inserted at that point (see the function `url-hexify-string').
1067 REPLACE may also be a function that will be called with the tag as the
1068 only argument to create the link, which should be returned as a string.
1070 See the manual for examples."
1071 :group 'org-link
1072 :type '(repeat
1073 (cons
1074 (string :tag "Protocol")
1075 (choice
1076 (string :tag "Format")
1077 (function)))))
1079 (defcustom org-descriptive-links t
1080 "Non-nil means, hide link part and only show description of bracket links.
1081 Bracket links are like [[link][description]]. This variable sets the initial
1082 state in new org-mode buffers. The setting can then be toggled on a
1083 per-buffer basis from the Org->Hyperlinks menu."
1084 :group 'org-link
1085 :type 'boolean)
1087 (defcustom org-link-file-path-type 'adaptive
1088 "How the path name in file links should be stored.
1089 Valid values are:
1091 relative Relative to the current directory, i.e. the directory of the file
1092 into which the link is being inserted.
1093 absolute Absolute path, if possible with ~ for home directory.
1094 noabbrev Absolute path, no abbreviation of home directory.
1095 adaptive Use relative path for files in the current directory and sub-
1096 directories of it. For other files, use an absolute path."
1097 :group 'org-link
1098 :type '(choice
1099 (const relative)
1100 (const absolute)
1101 (const noabbrev)
1102 (const adaptive)))
1104 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1105 "Types of links that should be activated in Org-mode files.
1106 This is a list of symbols, each leading to the activation of a certain link
1107 type. In principle, it does not hurt to turn on most link types - there may
1108 be a small gain when turning off unused link types. The types are:
1110 bracket The recommended [[link][description]] or [[link]] links with hiding.
1111 angular Links in angular brackets that may contain whitespace like
1112 <bbdb:Carsten Dominik>.
1113 plain Plain links in normal text, no whitespace, like http://google.com.
1114 radio Text that is matched by a radio target, see manual for details.
1115 tag Tag settings in a headline (link to tag search).
1116 date Time stamps (link to calendar).
1117 footnote Footnote labels.
1119 Changing this variable requires a restart of Emacs to become effective."
1120 :group 'org-link
1121 :type '(set :greedy t
1122 (const :tag "Double bracket links (new style)" bracket)
1123 (const :tag "Angular bracket links (old style)" angular)
1124 (const :tag "Plain text links" plain)
1125 (const :tag "Radio target matches" radio)
1126 (const :tag "Tags" tag)
1127 (const :tag "Timestamps" date)
1128 (const :tag "Footnotes" footnote)))
1130 (defcustom org-make-link-description-function nil
1131 "Function to use to generate link descriptions from links. If
1132 nil the link location will be used. This function must take two
1133 parameters; the first is the link and the second the description
1134 org-insert-link has generated, and should return the description
1135 to use."
1136 :group 'org-link
1137 :type 'function)
1139 (defgroup org-link-store nil
1140 "Options concerning storing links in Org-mode."
1141 :tag "Org Store Link"
1142 :group 'org-link)
1144 (defcustom org-email-link-description-format "Email %c: %.30s"
1145 "Format of the description part of a link to an email or usenet message.
1146 The following %-escapes will be replaced by corresponding information:
1148 %F full \"From\" field
1149 %f name, taken from \"From\" field, address if no name
1150 %T full \"To\" field
1151 %t first name in \"To\" field, address if no name
1152 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1153 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1154 %s subject
1155 %m message-id.
1157 You may use normal field width specification between the % and the letter.
1158 This is for example useful to limit the length of the subject.
1160 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1161 :group 'org-link-store
1162 :type 'string)
1164 (defcustom org-from-is-user-regexp
1165 (let (r1 r2)
1166 (when (and user-mail-address (not (string= user-mail-address "")))
1167 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1168 (when (and user-full-name (not (string= user-full-name "")))
1169 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1170 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1171 "Regexp matched against the \"From:\" header of an email or usenet message.
1172 It should match if the message is from the user him/herself."
1173 :group 'org-link-store
1174 :type 'regexp)
1176 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1177 "Non-nil means, storing a link to an Org file will use entry IDs.
1179 Note that before this variable is even considered, org-id must be loaded,
1180 so please customize `org-modules' and turn it on.
1182 The variable can have the following values:
1184 t Create an ID if needed to make a link to the current entry.
1186 create-if-interactive
1187 If `org-store-link' is called directly (interactively, as a user
1188 command), do create an ID to support the link. But when doing the
1189 job for remember, only use the ID if it already exists. The
1190 purpose of this setting is to avoid proliferation of unwanted
1191 IDs, just because you happen to be in an Org file when you
1192 call `org-remember' that automatically and preemptively
1193 creates a link. If you do want to get an ID link in a remember
1194 template to an entry not having an ID, create it first by
1195 explicitly creating a link to it, using `C-c C-l' first.
1197 create-if-interactive-and-no-custom-id
1198 Like create-if-interactive, but do not create an ID if there is
1199 a CUSTOM_ID property defined in the entry. This is the default.
1201 use-existing
1202 Use existing ID, do not create one.
1204 nil Never use an ID to make a link, instead link using a text search for
1205 the headline text."
1206 :group 'org-link-store
1207 :type '(choice
1208 (const :tag "Create ID to make link" t)
1209 (const :tag "Create if storing link interactively"
1210 create-if-interactive)
1211 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1212 create-if-interactive-and-no-custom-id)
1213 (const :tag "Only use existing" use-existing)
1214 (const :tag "Do not use ID to create link" nil)))
1216 (defcustom org-context-in-file-links t
1217 "Non-nil means, file links from `org-store-link' contain context.
1218 A search string will be added to the file name with :: as separator and
1219 used to find the context when the link is activated by the command
1220 `org-open-at-point'.
1221 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1222 negates this setting for the duration of the command."
1223 :group 'org-link-store
1224 :type 'boolean)
1226 (defcustom org-keep-stored-link-after-insertion nil
1227 "Non-nil means, keep link in list for entire session.
1229 The command `org-store-link' adds a link pointing to the current
1230 location to an internal list. These links accumulate during a session.
1231 The command `org-insert-link' can be used to insert links into any
1232 Org-mode file (offering completion for all stored links). When this
1233 option is nil, every link which has been inserted once using \\[org-insert-link]
1234 will be removed from the list, to make completing the unused links
1235 more efficient."
1236 :group 'org-link-store
1237 :type 'boolean)
1239 (defgroup org-link-follow nil
1240 "Options concerning following links in Org-mode."
1241 :tag "Org Follow Link"
1242 :group 'org-link)
1244 (defcustom org-link-translation-function nil
1245 "Function to translate links with different syntax to Org syntax.
1246 This can be used to translate links created for example by the Planner
1247 or emacs-wiki packages to Org syntax.
1248 The function must accept two parameters, a TYPE containing the link
1249 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1250 which is everything after the link protocol. It should return a cons
1251 with possibly modified values of type and path.
1252 Org contains a function for this, so if you set this variable to
1253 `org-translate-link-from-planner', you should be able follow many
1254 links created by planner."
1255 :group 'org-link-follow
1256 :type 'function)
1258 (defcustom org-follow-link-hook nil
1259 "Hook that is run after a link has been followed."
1260 :group 'org-link-follow
1261 :type 'hook)
1263 (defcustom org-tab-follows-link nil
1264 "Non-nil means, on links TAB will follow the link.
1265 Needs to be set before org.el is loaded.
1266 This really should not be used, it does not make sense, and the
1267 implementation is bad."
1268 :group 'org-link-follow
1269 :type 'boolean)
1271 (defcustom org-return-follows-link nil
1272 "Non-nil means, on links RET will follow the link.
1273 Needs to be set before org.el is loaded."
1274 :group 'org-link-follow
1275 :type 'boolean)
1277 (defcustom org-mouse-1-follows-link
1278 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1279 "Non-nil means, mouse-1 on a link will follow the link.
1280 A longer mouse click will still set point. Does not work on XEmacs.
1281 Needs to be set before org.el is loaded."
1282 :group 'org-link-follow
1283 :type 'boolean)
1285 (defcustom org-mark-ring-length 4
1286 "Number of different positions to be recorded in the ring
1287 Changing this requires a restart of Emacs to work correctly."
1288 :group 'org-link-follow
1289 :type 'integer)
1291 (defcustom org-link-frame-setup
1292 '((vm . vm-visit-folder-other-frame)
1293 (gnus . gnus-other-frame)
1294 (file . find-file-other-window))
1295 "Setup the frame configuration for following links.
1296 When following a link with Emacs, it may often be useful to display
1297 this link in another window or frame. This variable can be used to
1298 set this up for the different types of links.
1299 For VM, use any of
1300 `vm-visit-folder'
1301 `vm-visit-folder-other-frame'
1302 For Gnus, use any of
1303 `gnus'
1304 `gnus-other-frame'
1305 `org-gnus-no-new-news'
1306 For FILE, use any of
1307 `find-file'
1308 `find-file-other-window'
1309 `find-file-other-frame'
1310 For the calendar, use the variable `calendar-setup'.
1311 For BBDB, it is currently only possible to display the matches in
1312 another window."
1313 :group 'org-link-follow
1314 :type '(list
1315 (cons (const vm)
1316 (choice
1317 (const vm-visit-folder)
1318 (const vm-visit-folder-other-window)
1319 (const vm-visit-folder-other-frame)))
1320 (cons (const gnus)
1321 (choice
1322 (const gnus)
1323 (const gnus-other-frame)
1324 (const org-gnus-no-new-news)))
1325 (cons (const file)
1326 (choice
1327 (const find-file)
1328 (const find-file-other-window)
1329 (const find-file-other-frame)))))
1331 (defcustom org-display-internal-link-with-indirect-buffer nil
1332 "Non-nil means, use indirect buffer to display infile links.
1333 Activating internal links (from one location in a file to another location
1334 in the same file) normally just jumps to the location. When the link is
1335 activated with a C-u prefix (or with mouse-3), the link is displayed in
1336 another window. When this option is set, the other window actually displays
1337 an indirect buffer clone of the current buffer, to avoid any visibility
1338 changes to the current buffer."
1339 :group 'org-link-follow
1340 :type 'boolean)
1342 (defcustom org-open-non-existing-files nil
1343 "Non-nil means, `org-open-file' will open non-existing files.
1344 When nil, an error will be generated.
1345 This variable applies only to external applications because they
1346 might choke on non-existing files. If the link is to a file that
1347 will be opened in Emacs, the variable is ignored."
1348 :group 'org-link-follow
1349 :type 'boolean)
1351 (defcustom org-open-directory-means-index-dot-org nil
1352 "Non-nil means, a link to a directory really means to index.org.
1353 When nil, following a directory link will run dired or open a finder/explorer
1354 window on that directory."
1355 :group 'org-link-follow
1356 :type 'boolean)
1358 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1359 "Function and arguments to call for following mailto links.
1360 This is a list with the first element being a lisp function, and the
1361 remaining elements being arguments to the function. In string arguments,
1362 %a will be replaced by the address, and %s will be replaced by the subject
1363 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1364 :group 'org-link-follow
1365 :type '(choice
1366 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1367 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1368 (const :tag "message-mail" (message-mail "%a" "%s"))
1369 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1371 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1372 "Non-nil means, ask for confirmation before executing shell links.
1373 Shell links can be dangerous: just think about a link
1375 [[shell:rm -rf ~/*][Google Search]]
1377 This link would show up in your Org-mode document as \"Google Search\",
1378 but really it would remove your entire home directory.
1379 Therefore we advise against setting this variable to nil.
1380 Just change it to `y-or-n-p' if you want to confirm with a
1381 single keystroke rather than having to type \"yes\"."
1382 :group 'org-link-follow
1383 :type '(choice
1384 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1385 (const :tag "with y-or-n (faster)" y-or-n-p)
1386 (const :tag "no confirmation (dangerous)" nil)))
1388 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1389 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1390 Elisp links can be dangerous: just think about a link
1392 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1394 This link would show up in your Org-mode document as \"Google Search\",
1395 but really it would remove your entire home directory.
1396 Therefore we advise against setting this variable to nil.
1397 Just change it to `y-or-n-p' if you want to confirm with a
1398 single keystroke rather than having to type \"yes\"."
1399 :group 'org-link-follow
1400 :type '(choice
1401 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1402 (const :tag "with y-or-n (faster)" y-or-n-p)
1403 (const :tag "no confirmation (dangerous)" nil)))
1405 (defconst org-file-apps-defaults-gnu
1406 '((remote . emacs)
1407 (system . mailcap)
1408 (t . mailcap))
1409 "Default file applications on a UNIX or GNU/Linux system.
1410 See `org-file-apps'.")
1412 (defconst org-file-apps-defaults-macosx
1413 '((remote . emacs)
1414 (t . "open %s")
1415 (system . "open %s")
1416 ("ps.gz" . "gv %s")
1417 ("eps.gz" . "gv %s")
1418 ("dvi" . "xdvi %s")
1419 ("fig" . "xfig %s"))
1420 "Default file applications on a MacOS X system.
1421 The system \"open\" is known as a default, but we use X11 applications
1422 for some files for which the OS does not have a good default.
1423 See `org-file-apps'.")
1425 (defconst org-file-apps-defaults-windowsnt
1426 (list
1427 '(remote . emacs)
1428 (cons t
1429 (list (if (featurep 'xemacs)
1430 'mswindows-shell-execute
1431 'w32-shell-execute)
1432 "open" 'file))
1433 (cons 'system
1434 (list (if (featurep 'xemacs)
1435 'mswindows-shell-execute
1436 'w32-shell-execute)
1437 "open" 'file)))
1438 "Default file applications on a Windows NT system.
1439 The system \"open\" is used for most files.
1440 See `org-file-apps'.")
1442 (defcustom org-file-apps
1444 (auto-mode . emacs)
1445 ("\\.mm\\'" . default)
1446 ("\\.x?html?\\'" . default)
1447 ("\\.pdf\\'" . default)
1449 "External applications for opening `file:path' items in a document.
1450 Org-mode uses system defaults for different file types, but
1451 you can use this variable to set the application for a given file
1452 extension. The entries in this list are cons cells where the car identifies
1453 files and the cdr the corresponding command. Possible values for the
1454 file identifier are
1455 \"regex\" Regular expression matched against the file name. For backward
1456 compatibility, this can also be a string with only alphanumeric
1457 characters, which is then interpreted as an extension.
1458 `directory' Matches a directory
1459 `remote' Matches a remote file, accessible through tramp or efs.
1460 Remote files most likely should be visited through Emacs
1461 because external applications cannot handle such paths.
1462 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1463 so all files Emacs knows how to handle. Using this with
1464 command `emacs' will open most files in Emacs. Beware that this
1465 will also open html files inside Emacs, unless you add
1466 (\"html\" . default) to the list as well.
1467 t Default for files not matched by any of the other options.
1468 `system' The system command to open files, like `open' on Windows
1469 and Mac OS X, and mailcap under GNU/Linux. This is the command
1470 that will be selected if you call `C-c C-o' with a double
1471 `C-u C-u' prefix.
1473 Possible values for the command are:
1474 `emacs' The file will be visited by the current Emacs process.
1475 `default' Use the default application for this file type, which is the
1476 association for t in the list, most likely in the system-specific
1477 part.
1478 This can be used to overrule an unwanted setting in the
1479 system-specific variable.
1480 `system' Use the system command for opening files, like \"open\".
1481 This command is specified by the entry whose car is `system'.
1482 Most likely, the system-specific version of this variable
1483 does define this command, but you can overrule/replace it
1484 here.
1485 string A command to be executed by a shell; %s will be replaced
1486 by the path to the file.
1487 sexp A Lisp form which will be evaluated. The file path will
1488 be available in the Lisp variable `file'.
1489 For more examples, see the system specific constants
1490 `org-file-apps-defaults-macosx'
1491 `org-file-apps-defaults-windowsnt'
1492 `org-file-apps-defaults-gnu'."
1493 :group 'org-link-follow
1494 :type '(repeat
1495 (cons (choice :value ""
1496 (string :tag "Extension")
1497 (const :tag "System command to open files" system)
1498 (const :tag "Default for unrecognized files" t)
1499 (const :tag "Remote file" remote)
1500 (const :tag "Links to a directory" directory)
1501 (const :tag "Any files that have Emacs modes"
1502 auto-mode))
1503 (choice :value ""
1504 (const :tag "Visit with Emacs" emacs)
1505 (const :tag "Use default" default)
1506 (const :tag "Use the system command" system)
1507 (string :tag "Command")
1508 (sexp :tag "Lisp form")))))
1510 (defgroup org-refile nil
1511 "Options concerning refiling entries in Org-mode."
1512 :tag "Org Refile"
1513 :group 'org)
1515 (defcustom org-directory "~/org"
1516 "Directory with org files.
1517 This is just a default location to look for Org files. There is no need
1518 at all to put your files into this directory. It is only used in the
1519 following situations:
1521 1. When a remember template specifies a target file that is not an
1522 absolute path. The path will then be interpreted relative to
1523 `org-directory'
1524 2. When a remember note is filed away in an interactive way (when exiting the
1525 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1526 with `org-directory' as the default path."
1527 :group 'org-refile
1528 :group 'org-remember
1529 :type 'directory)
1531 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1532 "Default target for storing notes.
1533 Used by the hooks for remember.el. This can be a string, or nil to mean
1534 the value of `remember-data-file'.
1535 You can set this on a per-template basis with the variable
1536 `org-remember-templates'."
1537 :group 'org-refile
1538 :group 'org-remember
1539 :type '(choice
1540 (const :tag "Default from remember-data-file" nil)
1541 file))
1543 (defcustom org-goto-interface 'outline
1544 "The default interface to be used for `org-goto'.
1545 Allowed values are:
1546 outline The interface shows an outline of the relevant file
1547 and the correct heading is found by moving through
1548 the outline or by searching with incremental search.
1549 outline-path-completion Headlines in the current buffer are offered via
1550 completion. This is the interface also used by
1551 the refile command."
1552 :group 'org-refile
1553 :type '(choice
1554 (const :tag "Outline" outline)
1555 (const :tag "Outline-path-completion" outline-path-completion)))
1557 (defcustom org-goto-max-level 5
1558 "Maximum level to be considered when running org-goto with refile interface."
1559 :group 'org-refile
1560 :type 'integer)
1562 (defcustom org-reverse-note-order nil
1563 "Non-nil means, store new notes at the beginning of a file or entry.
1564 When nil, new notes will be filed to the end of a file or entry.
1565 This can also be a list with cons cells of regular expressions that
1566 are matched against file names, and values."
1567 :group 'org-remember
1568 :group 'org-refile
1569 :type '(choice
1570 (const :tag "Reverse always" t)
1571 (const :tag "Reverse never" nil)
1572 (repeat :tag "By file name regexp"
1573 (cons regexp boolean))))
1575 (defcustom org-refile-targets nil
1576 "Targets for refiling entries with \\[org-refile].
1577 This is list of cons cells. Each cell contains:
1578 - a specification of the files to be considered, either a list of files,
1579 or a symbol whose function or variable value will be used to retrieve
1580 a file name or a list of file names. If you use `org-agenda-files' for
1581 that, all agenda files will be scanned for targets. Nil means, consider
1582 headings in the current buffer.
1583 - A specification of how to find candidate refile targets. This may be
1584 any of:
1585 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1586 This tag has to be present in all target headlines, inheritance will
1587 not be considered.
1588 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1589 todo keyword.
1590 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1591 headlines that are refiling targets.
1592 - a cons cell (:level . N). Any headline of level N is considered a target.
1593 Note that, when `org-odd-levels-only' is set, level corresponds to
1594 order in hierarchy, not to the number of stars.
1595 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1596 Note that, when `org-odd-levels-only' is set, level corresponds to
1597 order in hierarchy, not to the number of stars.
1599 You can set the variable `org-refile-target-verify-function' to a function
1600 to verify each headline found by the simple critery above.
1602 When this variable is nil, all top-level headlines in the current buffer
1603 are used, equivalent to the value `((nil . (:level . 1))'."
1604 :group 'org-refile
1605 :type '(repeat
1606 (cons
1607 (choice :value org-agenda-files
1608 (const :tag "All agenda files" org-agenda-files)
1609 (const :tag "Current buffer" nil)
1610 (function) (variable) (file))
1611 (choice :tag "Identify target headline by"
1612 (cons :tag "Specific tag" (const :value :tag) (string))
1613 (cons :tag "TODO keyword" (const :value :todo) (string))
1614 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1615 (cons :tag "Level number" (const :value :level) (integer))
1616 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1618 (defcustom org-refile-target-verify-function nil
1619 "Function to verify if the headline at point should be a refile target.
1620 The function will be called without arguments, with point at the
1621 beginning of the headline. It should return t and leave point
1622 where it is if the headline is a valid target for refiling.
1624 If the target should not be selected, the function must return nil.
1625 In addition to this, it may move point to a place from where the search
1626 should be continued. For example, the function may decide that the entire
1627 subtree of the current entry should be excluded and move point to the end
1628 of the subtree."
1629 :group 'org-refile
1630 :type 'function)
1632 (defcustom org-refile-use-outline-path nil
1633 "Non-nil means, provide refile targets as paths.
1634 So a level 3 headline will be available as level1/level2/level3.
1636 When the value is `file', also include the file name (without directory)
1637 into the path. In this case, you can also stop the completion after
1638 the file name, to get entries inserted as top level in the file.
1640 When `full-file-path', include the full file path."
1641 :group 'org-refile
1642 :type '(choice
1643 (const :tag "Not" nil)
1644 (const :tag "Yes" t)
1645 (const :tag "Start with file name" file)
1646 (const :tag "Start with full file path" full-file-path)))
1648 (defcustom org-outline-path-complete-in-steps t
1649 "Non-nil means, complete the outline path in hierarchical steps.
1650 When Org-mode uses the refile interface to select an outline path
1651 \(see variable `org-refile-use-outline-path'), the completion of
1652 the path can be done is a single go, or if can be done in steps down
1653 the headline hierarchy. Going in steps is probably the best if you
1654 do not use a special completion package like `ido' or `icicles'.
1655 However, when using these packages, going in one step can be very
1656 fast, while still showing the whole path to the entry."
1657 :group 'org-refile
1658 :type 'boolean)
1660 (defcustom org-refile-allow-creating-parent-nodes nil
1661 "Non-nil means, allow to create new nodes as refile targets.
1662 New nodes are then created by adding \"/new node name\" to the completion
1663 of an existing node. When the value of this variable is `confirm',
1664 new node creation must be confirmed by the user (recommended)
1665 When nil, the completion must match an existing entry.
1667 Note that, if the new heading is not seen by the criteria
1668 listed in `org-refile-targets', multiple instances of the same
1669 heading would be created by trying again to file under the new
1670 heading."
1671 :group 'org-refile
1672 :type '(choice
1673 (const :tag "Never" nil)
1674 (const :tag "Always" t)
1675 (const :tag "Prompt for confirmation" confirm)))
1677 (defgroup org-todo nil
1678 "Options concerning TODO items in Org-mode."
1679 :tag "Org TODO"
1680 :group 'org)
1682 (defgroup org-progress nil
1683 "Options concerning Progress logging in Org-mode."
1684 :tag "Org Progress"
1685 :group 'org-time)
1687 (defvar org-todo-interpretation-widgets
1689 (:tag "Sequence (cycling hits every state)" sequence)
1690 (:tag "Type (cycling directly to DONE)" type))
1691 "The available interpretation symbols for customizing
1692 `org-todo-keywords'.
1693 Interested libraries should add to this list.")
1695 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1696 "List of TODO entry keyword sequences and their interpretation.
1697 \\<org-mode-map>This is a list of sequences.
1699 Each sequence starts with a symbol, either `sequence' or `type',
1700 indicating if the keywords should be interpreted as a sequence of
1701 action steps, or as different types of TODO items. The first
1702 keywords are states requiring action - these states will select a headline
1703 for inclusion into the global TODO list Org-mode produces. If one of
1704 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1705 signify that no further action is necessary. If \"|\" is not found,
1706 the last keyword is treated as the only DONE state of the sequence.
1708 The command \\[org-todo] cycles an entry through these states, and one
1709 additional state where no keyword is present. For details about this
1710 cycling, see the manual.
1712 TODO keywords and interpretation can also be set on a per-file basis with
1713 the special #+SEQ_TODO and #+TYP_TODO lines.
1715 Each keyword can optionally specify a character for fast state selection
1716 \(in combination with the variable `org-use-fast-todo-selection')
1717 and specifiers for state change logging, using the same syntax
1718 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1719 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1720 indicates to record a time stamp each time this state is selected.
1722 Each keyword may also specify if a timestamp or a note should be
1723 recorded when entering or leaving the state, by adding additional
1724 characters in the parenthesis after the keyword. This looks like this:
1725 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1726 record only the time of the state change. With X and Y being either
1727 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1728 Y when leaving the state if and only if the *target* state does not
1729 define X. You may omit any of the fast-selection key or X or /Y,
1730 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1732 For backward compatibility, this variable may also be just a list
1733 of keywords - in this case the interpretation (sequence or type) will be
1734 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1735 :group 'org-todo
1736 :group 'org-keywords
1737 :type '(choice
1738 (repeat :tag "Old syntax, just keywords"
1739 (string :tag "Keyword"))
1740 (repeat :tag "New syntax"
1741 (cons
1742 (choice
1743 :tag "Interpretation"
1744 ;;Quick and dirty way to see
1745 ;;`org-todo-interpretations'. This takes the
1746 ;;place of item arguments
1747 :convert-widget
1748 (lambda (widget)
1749 (widget-put widget
1750 :args (mapcar
1751 #'(lambda (x)
1752 (widget-convert
1753 (cons 'const x)))
1754 org-todo-interpretation-widgets))
1755 widget))
1756 (repeat
1757 (string :tag "Keyword"))))))
1759 (defvar org-todo-keywords-1 nil
1760 "All TODO and DONE keywords active in a buffer.")
1761 (make-variable-buffer-local 'org-todo-keywords-1)
1762 (defvar org-todo-keywords-for-agenda nil)
1763 (defvar org-done-keywords-for-agenda nil)
1764 (defvar org-drawers-for-agenda nil)
1765 (defvar org-todo-keyword-alist-for-agenda nil)
1766 (defvar org-tag-alist-for-agenda nil)
1767 (defvar org-agenda-contributing-files nil)
1768 (defvar org-not-done-keywords nil)
1769 (make-variable-buffer-local 'org-not-done-keywords)
1770 (defvar org-done-keywords nil)
1771 (make-variable-buffer-local 'org-done-keywords)
1772 (defvar org-todo-heads nil)
1773 (make-variable-buffer-local 'org-todo-heads)
1774 (defvar org-todo-sets nil)
1775 (make-variable-buffer-local 'org-todo-sets)
1776 (defvar org-todo-log-states nil)
1777 (make-variable-buffer-local 'org-todo-log-states)
1778 (defvar org-todo-kwd-alist nil)
1779 (make-variable-buffer-local 'org-todo-kwd-alist)
1780 (defvar org-todo-key-alist nil)
1781 (make-variable-buffer-local 'org-todo-key-alist)
1782 (defvar org-todo-key-trigger nil)
1783 (make-variable-buffer-local 'org-todo-key-trigger)
1785 (defcustom org-todo-interpretation 'sequence
1786 "Controls how TODO keywords are interpreted.
1787 This variable is in principle obsolete and is only used for
1788 backward compatibility, if the interpretation of todo keywords is
1789 not given already in `org-todo-keywords'. See that variable for
1790 more information."
1791 :group 'org-todo
1792 :group 'org-keywords
1793 :type '(choice (const sequence)
1794 (const type)))
1796 (defcustom org-use-fast-todo-selection t
1797 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1798 This variable describes if and under what circumstances the cycling
1799 mechanism for TODO keywords will be replaced by a single-key, direct
1800 selection scheme.
1802 When nil, fast selection is never used.
1804 When the symbol `prefix', it will be used when `org-todo' is called with
1805 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1806 in an agenda buffer.
1808 When t, fast selection is used by default. In this case, the prefix
1809 argument forces cycling instead.
1811 In all cases, the special interface is only used if access keys have actually
1812 been assigned by the user, i.e. if keywords in the configuration are followed
1813 by a letter in parenthesis, like TODO(t)."
1814 :group 'org-todo
1815 :type '(choice
1816 (const :tag "Never" nil)
1817 (const :tag "By default" t)
1818 (const :tag "Only with C-u C-c C-t" prefix)))
1820 (defcustom org-provide-todo-statistics t
1821 "Non-nil means, update todo statistics after insert and toggle.
1822 ALL-HEADLINES means update todo statistics by including headlines
1823 with no TODO keyword as well, counting them as not done.
1824 A list of TODO keywords means the same, but skip keywords that are
1825 not in this list.
1827 When this is set, todo statistics is updated in the parent of the
1828 current entry each time a todo state is changed."
1829 :group 'org-todo
1830 :type '(choice
1831 (const :tag "Yes, only for TODO entries" t)
1832 (const :tag "Yes, including all entries" 'all-headlines)
1833 (repeat :tag "Yes, for TODOs in this list"
1834 (string :tag "TODO keyword"))
1835 (other :tag "No TODO statistics" nil)))
1837 (defcustom org-hierarchical-todo-statistics t
1838 "Non-nil means, TODO statistics covers just direct children.
1839 When nil, all entries in the subtree are considered.
1840 This has only an effect if `org-provide-todo-statistics' is set.
1841 To set this to nil for only a single subtree, use a COOKIE_DATA
1842 property and include the word \"recursive\" into the value."
1843 :group 'org-todo
1844 :type 'boolean)
1846 (defcustom org-after-todo-state-change-hook nil
1847 "Hook which is run after the state of a TODO item was changed.
1848 The new state (a string with a TODO keyword, or nil) is available in the
1849 Lisp variable `state'."
1850 :group 'org-todo
1851 :type 'hook)
1853 (defvar org-blocker-hook nil
1854 "Hook for functions that are allowed to block a state change.
1856 Each function gets as its single argument a property list, see
1857 `org-trigger-hook' for more information about this list.
1859 If any of the functions in this hook returns nil, the state change
1860 is blocked.")
1862 (defvar org-trigger-hook nil
1863 "Hook for functions that are triggered by a state change.
1865 Each function gets as its single argument a property list with at least
1866 the following elements:
1868 (:type type-of-change :position pos-at-entry-start
1869 :from old-state :to new-state)
1871 Depending on the type, more properties may be present.
1873 This mechanism is currently implemented for:
1875 TODO state changes
1876 ------------------
1877 :type todo-state-change
1878 :from previous state (keyword as a string), or nil, or a symbol
1879 'todo' or 'done', to indicate the general type of state.
1880 :to new state, like in :from")
1882 (defcustom org-enforce-todo-dependencies nil
1883 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1884 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1885 be blocked if any prior sibling is not yet done.
1886 Finally, if the parent is blocked because of ordered siblings of its own,
1887 the child will also be blocked.
1888 This variable needs to be set before org.el is loaded, and you need to
1889 restart Emacs after a change to make the change effective. The only way
1890 to change is while Emacs is running is through the customize interface."
1891 :set (lambda (var val)
1892 (set var val)
1893 (if val
1894 (add-hook 'org-blocker-hook
1895 'org-block-todo-from-children-or-siblings-or-parent)
1896 (remove-hook 'org-blocker-hook
1897 'org-block-todo-from-children-or-siblings-or-parent)))
1898 :group 'org-todo
1899 :type 'boolean)
1901 (defcustom org-enforce-todo-checkbox-dependencies nil
1902 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1903 When this is nil, checkboxes have no influence on switching TODO states.
1904 When non-nil, you first need to check off all check boxes before the TODO
1905 entry can be switched to DONE.
1906 This variable needs to be set before org.el is loaded, and you need to
1907 restart Emacs after a change to make the change effective. The only way
1908 to change is while Emacs is running is through the customize interface."
1909 :set (lambda (var val)
1910 (set var val)
1911 (if val
1912 (add-hook 'org-blocker-hook
1913 'org-block-todo-from-checkboxes)
1914 (remove-hook 'org-blocker-hook
1915 'org-block-todo-from-checkboxes)))
1916 :group 'org-todo
1917 :type 'boolean)
1919 (defcustom org-treat-insert-todo-heading-as-state-change nil
1920 "Non-nil means, inserting a TODO heading is treated as state change.
1921 So when the command \\[org-insert-todo-heading] is used, state change
1922 logging will apply if appropriate. When nil, the new TODO item will
1923 be inserted directly, and no logging will take place."
1924 :group 'org-todo
1925 :type 'boolean)
1927 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1928 "Non-nil means, switching TODO states with S-cursor counts as state change.
1929 This is the default behavior. However, setting this to nil allows a
1930 convenient way to select a TODO state and bypass any logging associated
1931 with that."
1932 :group 'org-todo
1933 :type 'boolean)
1935 (defcustom org-todo-state-tags-triggers nil
1936 "Tag changes that should be triggered by TODO state changes.
1937 This is a list. Each entry is
1939 (state-change (tag . flag) .......)
1941 State-change can be a string with a state, and empty string to indicate the
1942 state that has no TODO keyword, or it can be one of the symbols `todo'
1943 or `done', meaning any not-done or done state, respectively."
1944 :group 'org-todo
1945 :group 'org-tags
1946 :type '(repeat
1947 (cons (choice :tag "When changing to"
1948 (const :tag "Not-done state" todo)
1949 (const :tag "Done state" done)
1950 (string :tag "State"))
1951 (repeat
1952 (cons :tag "Tag action"
1953 (string :tag "Tag")
1954 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1956 (defcustom org-log-done nil
1957 "Information to record when a task moves to the DONE state.
1959 Possible values are:
1961 nil Don't add anything, just change the keyword
1962 time Add a time stamp to the task
1963 note Prompt for a note and add it with template `org-log-note-headings'
1965 This option can also be set with on a per-file-basis with
1967 #+STARTUP: nologdone
1968 #+STARTUP: logdone
1969 #+STARTUP: lognotedone
1971 You can have local logging settings for a subtree by setting the LOGGING
1972 property to one or more of these keywords."
1973 :group 'org-todo
1974 :group 'org-progress
1975 :type '(choice
1976 (const :tag "No logging" nil)
1977 (const :tag "Record CLOSED timestamp" time)
1978 (const :tag "Record CLOSED timestamp with note." note)))
1980 ;; Normalize old uses of org-log-done.
1981 (cond
1982 ((eq org-log-done t) (setq org-log-done 'time))
1983 ((and (listp org-log-done) (memq 'done org-log-done))
1984 (setq org-log-done 'note)))
1986 (defcustom org-log-reschedule nil
1987 "Information to record when the scheduling date of a tasks is modified.
1989 Possible values are:
1991 nil Don't add anything, just change the date
1992 time Add a time stamp to the task
1993 note Prompt for a note and add it with template `org-log-note-headings'
1995 This option can also be set with on a per-file-basis with
1997 #+STARTUP: nologreschedule
1998 #+STARTUP: logreschedule
1999 #+STARTUP: lognotereschedule"
2000 :group 'org-todo
2001 :group 'org-progress
2002 :type '(choice
2003 (const :tag "No logging" nil)
2004 (const :tag "Record timestamp" time)
2005 (const :tag "Record timestamp with note." note)))
2007 (defcustom org-log-redeadline nil
2008 "Information to record when the deadline date of a tasks is modified.
2010 Possible values are:
2012 nil Don't add anything, just change the date
2013 time Add a time stamp to the task
2014 note Prompt for a note and add it with template `org-log-note-headings'
2016 This option can also be set with on a per-file-basis with
2018 #+STARTUP: nologredeadline
2019 #+STARTUP: logredeadline
2020 #+STARTUP: lognoteredeadline
2022 You can have local logging settings for a subtree by setting the LOGGING
2023 property to one or more of these keywords."
2024 :group 'org-todo
2025 :group 'org-progress
2026 :type '(choice
2027 (const :tag "No logging" nil)
2028 (const :tag "Record timestamp" time)
2029 (const :tag "Record timestamp with note." note)))
2031 (defcustom org-log-note-clock-out nil
2032 "Non-nil means, record a note when clocking out of an item.
2033 This can also be configured on a per-file basis by adding one of
2034 the following lines anywhere in the buffer:
2036 #+STARTUP: lognoteclock-out
2037 #+STARTUP: nolognoteclock-out"
2038 :group 'org-todo
2039 :group 'org-progress
2040 :type 'boolean)
2042 (defcustom org-log-done-with-time t
2043 "Non-nil means, the CLOSED time stamp will contain date and time.
2044 When nil, only the date will be recorded."
2045 :group 'org-progress
2046 :type 'boolean)
2048 (defcustom org-log-note-headings
2049 '((done . "CLOSING NOTE %t")
2050 (state . "State %-12s from %-12S %t")
2051 (note . "Note taken on %t")
2052 (reschedule . "Rescheduled from %S on %t")
2053 (redeadline . "New deadline from %S on %t")
2054 (clock-out . ""))
2055 "Headings for notes added to entries.
2056 The value is an alist, with the car being a symbol indicating the note
2057 context, and the cdr is the heading to be used. The heading may also be the
2058 empty string.
2059 %t in the heading will be replaced by a time stamp.
2060 %s will be replaced by the new TODO state, in double quotes.
2061 %S will be replaced by the old TODO state, in double quotes.
2062 %u will be replaced by the user name.
2063 %U will be replaced by the full user name."
2064 :group 'org-todo
2065 :group 'org-progress
2066 :type '(list :greedy t
2067 (cons (const :tag "Heading when closing an item" done) string)
2068 (cons (const :tag
2069 "Heading when changing todo state (todo sequence only)"
2070 state) string)
2071 (cons (const :tag "Heading when just taking a note" note) string)
2072 (cons (const :tag "Heading when clocking out" clock-out) string)
2073 (cons (const :tag "Heading when rescheduling" reschedule) string)
2074 (cons (const :tag "Heading when changing deadline" redeadline) string)))
2076 (unless (assq 'note org-log-note-headings)
2077 (push '(note . "%t") org-log-note-headings))
2079 (defcustom org-log-into-drawer nil
2080 "Non-nil means, insert state change notes and time stamps into a drawer.
2081 When nil, state changes notes will be inserted after the headline and
2082 any scheduling and clock lines, but not inside a drawer.
2084 The value of this variable should be the name of the drawer to use.
2085 LOGBOOK is proposed at the default drawer for this purpose, you can
2086 also set this to a string to define the drawer of your choice.
2088 A value of t is also allowed, representing \"LOGBOOK\".
2090 If this variable is set, `org-log-state-notes-insert-after-drawers'
2091 will be ignored.
2093 You can set the property LOG_INTO_DRAWER to overrule this setting for
2094 a subtree."
2095 :group 'org-todo
2096 :group 'org-progress
2097 :type '(choice
2098 (const :tag "Not into a drawer" nil)
2099 (const :tag "LOGBOOK" t)
2100 (string :tag "Other")))
2102 (if (fboundp 'defvaralias)
2103 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2105 (defun org-log-into-drawer ()
2106 "Return the value of `org-log-into-drawer', but let properties overrule.
2107 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2108 used instead of the default value."
2109 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2110 (cond
2111 ((or (not p) (equal p "nil")) org-log-into-drawer)
2112 ((equal p "t") "LOGBOOK")
2113 (t p))))
2115 (defcustom org-log-state-notes-insert-after-drawers nil
2116 "Non-nil means, insert state change notes after any drawers in entry.
2117 Only the drawers that *immediately* follow the headline and the
2118 deadline/scheduled line are skipped.
2119 When nil, insert notes right after the heading and perhaps the line
2120 with deadline/scheduling if present.
2122 This variable will have no effect if `org-log-into-drawer' is
2123 set."
2124 :group 'org-todo
2125 :group 'org-progress
2126 :type 'boolean)
2128 (defcustom org-log-states-order-reversed t
2129 "Non-nil means, the latest state change note will be directly after heading.
2130 When nil, the notes will be orderer according to time."
2131 :group 'org-todo
2132 :group 'org-progress
2133 :type 'boolean)
2135 (defcustom org-log-repeat 'time
2136 "Non-nil means, record moving through the DONE state when triggering repeat.
2137 An auto-repeating task is immediately switched back to TODO when
2138 marked DONE. If you are not logging state changes (by adding \"@\"
2139 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2140 record a closing note, there will be no record of the task moving
2141 through DONE. This variable forces taking a note anyway.
2143 nil Don't force a record
2144 time Record a time stamp
2145 note Record a note
2147 This option can also be set with on a per-file-basis with
2149 #+STARTUP: logrepeat
2150 #+STARTUP: lognoterepeat
2151 #+STARTUP: nologrepeat
2153 You can have local logging settings for a subtree by setting the LOGGING
2154 property to one or more of these keywords."
2155 :group 'org-todo
2156 :group 'org-progress
2157 :type '(choice
2158 (const :tag "Don't force a record" nil)
2159 (const :tag "Force recording the DONE state" time)
2160 (const :tag "Force recording a note with the DONE state" note)))
2163 (defgroup org-priorities nil
2164 "Priorities in Org-mode."
2165 :tag "Org Priorities"
2166 :group 'org-todo)
2168 (defcustom org-enable-priority-commands t
2169 "Non-nil means, priority commands are active.
2170 When nil, these commands will be disabled, so that you never accidentally
2171 set a priority."
2172 :group 'org-priorities
2173 :type 'boolean)
2175 (defcustom org-highest-priority ?A
2176 "The highest priority of TODO items. A character like ?A, ?B etc.
2177 Must have a smaller ASCII number than `org-lowest-priority'."
2178 :group 'org-priorities
2179 :type 'character)
2181 (defcustom org-lowest-priority ?C
2182 "The lowest priority of TODO items. A character like ?A, ?B etc.
2183 Must have a larger ASCII number than `org-highest-priority'."
2184 :group 'org-priorities
2185 :type 'character)
2187 (defcustom org-default-priority ?B
2188 "The default priority of TODO items.
2189 This is the priority an item get if no explicit priority is given."
2190 :group 'org-priorities
2191 :type 'character)
2193 (defcustom org-priority-start-cycle-with-default t
2194 "Non-nil means, start with default priority when starting to cycle.
2195 When this is nil, the first step in the cycle will be (depending on the
2196 command used) one higher or lower that the default priority."
2197 :group 'org-priorities
2198 :type 'boolean)
2200 (defgroup org-time nil
2201 "Options concerning time stamps and deadlines in Org-mode."
2202 :tag "Org Time"
2203 :group 'org)
2205 (defcustom org-insert-labeled-timestamps-at-point nil
2206 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2207 When nil, these labeled time stamps are forces into the second line of an
2208 entry, just after the headline. When scheduling from the global TODO list,
2209 the time stamp will always be forced into the second line."
2210 :group 'org-time
2211 :type 'boolean)
2213 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2214 "Formats for `format-time-string' which are used for time stamps.
2215 It is not recommended to change this constant.")
2217 (defcustom org-time-stamp-rounding-minutes '(0 5)
2218 "Number of minutes to round time stamps to.
2219 These are two values, the first applies when first creating a time stamp.
2220 The second applies when changing it with the commands `S-up' and `S-down'.
2221 When changing the time stamp, this means that it will change in steps
2222 of N minutes, as given by the second value.
2224 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2225 numbers should be factors of 60, so for example 5, 10, 15.
2227 When this is larger than 1, you can still force an exact time-stamp by using
2228 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2229 and by using a prefix arg to `S-up/down' to specify the exact number
2230 of minutes to shift."
2231 :group 'org-time
2232 :get '(lambda (var) ; Make sure all entries have 5 elements
2233 (if (integerp (default-value var))
2234 (list (default-value var) 5)
2235 (default-value var)))
2236 :type '(list
2237 (integer :tag "when inserting times")
2238 (integer :tag "when modifying times")))
2240 ;; Normalize old customizations of this variable.
2241 (when (integerp org-time-stamp-rounding-minutes)
2242 (setq org-time-stamp-rounding-minutes
2243 (list org-time-stamp-rounding-minutes
2244 org-time-stamp-rounding-minutes)))
2246 (defcustom org-display-custom-times nil
2247 "Non-nil means, overlay custom formats over all time stamps.
2248 The formats are defined through the variable `org-time-stamp-custom-formats'.
2249 To turn this on on a per-file basis, insert anywhere in the file:
2250 #+STARTUP: customtime"
2251 :group 'org-time
2252 :set 'set-default
2253 :type 'sexp)
2254 (make-variable-buffer-local 'org-display-custom-times)
2256 (defcustom org-time-stamp-custom-formats
2257 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2258 "Custom formats for time stamps. See `format-time-string' for the syntax.
2259 These are overlayed over the default ISO format if the variable
2260 `org-display-custom-times' is set. Time like %H:%M should be at the
2261 end of the second format. The custom formats are also honored by export
2262 commands, if custom time display is turned on at the time of export."
2263 :group 'org-time
2264 :type 'sexp)
2266 (defun org-time-stamp-format (&optional long inactive)
2267 "Get the right format for a time string."
2268 (let ((f (if long (cdr org-time-stamp-formats)
2269 (car org-time-stamp-formats))))
2270 (if inactive
2271 (concat "[" (substring f 1 -1) "]")
2272 f)))
2274 (defcustom org-time-clocksum-format "%d:%02d"
2275 "The format string used when creating CLOCKSUM lines, or when
2276 org-mode generates a time duration."
2277 :group 'org-time
2278 :type 'string)
2280 (defcustom org-time-clocksum-use-fractional nil
2281 "If non-nil, \\[org-clock-display] uses fractional times.
2282 org-mode generates a time duration."
2283 :group 'org-time
2284 :type 'boolean)
2286 (defcustom org-time-clocksum-fractional-format "%.2f"
2287 "The format string used when creating CLOCKSUM lines, or when
2288 org-mode generates a time duration."
2289 :group 'org-time
2290 :type 'string)
2292 (defcustom org-deadline-warning-days 14
2293 "No. of days before expiration during which a deadline becomes active.
2294 This variable governs the display in sparse trees and in the agenda.
2295 When 0 or negative, it means use this number (the absolute value of it)
2296 even if a deadline has a different individual lead time specified.
2298 Custom commands can set this variable in the options section."
2299 :group 'org-time
2300 :group 'org-agenda-daily/weekly
2301 :type 'integer)
2303 (defcustom org-read-date-prefer-future t
2304 "Non-nil means, assume future for incomplete date input from user.
2305 This affects the following situations:
2306 1. The user gives a month but not a year.
2307 For example, if it is april and you enter \"feb 2\", this will be read
2308 as feb 2, *next* year. \"May 5\", however, will be this year.
2309 2. The user gives a day, but no month.
2310 For example, if today is the 15th, and you enter \"3\", Org-mode will
2311 read this as the third of *next* month. However, if you enter \"17\",
2312 it will be considered as *this* month.
2314 If you set this variable to the symbol `time', then also the following
2315 will work:
2317 3. If the user gives a time, but no day. If the time is before now,
2318 to will be interpreted as tomorrow.
2320 Currently none of this works for ISO week specifications.
2322 When this option is nil, the current day, month and year will always be
2323 used as defaults."
2324 :group 'org-time
2325 :type '(choice
2326 (const :tag "Never" nil)
2327 (const :tag "Check month and day" t)
2328 (const :tag "Check month, day, and time" time)))
2330 (defcustom org-read-date-display-live t
2331 "Non-nil means, display current interpretation of date prompt live.
2332 This display will be in an overlay, in the minibuffer."
2333 :group 'org-time
2334 :type 'boolean)
2336 (defcustom org-read-date-popup-calendar t
2337 "Non-nil means, pop up a calendar when prompting for a date.
2338 In the calendar, the date can be selected with mouse-1. However, the
2339 minibuffer will also be active, and you can simply enter the date as well.
2340 When nil, only the minibuffer will be available."
2341 :group 'org-time
2342 :type 'boolean)
2343 (if (fboundp 'defvaralias)
2344 (defvaralias 'org-popup-calendar-for-date-prompt
2345 'org-read-date-popup-calendar))
2347 (defcustom org-read-date-minibuffer-setup-hook nil
2348 "Hook to be used to set up keys for the date/time interface.
2349 Add key definitions to `minibuffer-local-map', which will be a temporary
2350 copy."
2351 :group 'org-time
2352 :type 'hook)
2354 (defcustom org-extend-today-until 0
2355 "The hour when your day really ends. Must be an integer.
2356 This has influence for the following applications:
2357 - When switching the agenda to \"today\". It it is still earlier than
2358 the time given here, the day recognized as TODAY is actually yesterday.
2359 - When a date is read from the user and it is still before the time given
2360 here, the current date and time will be assumed to be yesterday, 23:59.
2361 Also, timestamps inserted in remember templates follow this rule.
2363 IMPORTANT: This is a feature whose implementation is and likely will
2364 remain incomplete. Really, it is only here because past midnight seems to
2365 be the favorite working time of John Wiegley :-)"
2366 :group 'org-time
2367 :type 'integer)
2369 (defcustom org-edit-timestamp-down-means-later nil
2370 "Non-nil means, S-down will increase the time in a time stamp.
2371 When nil, S-up will increase."
2372 :group 'org-time
2373 :type 'boolean)
2375 (defcustom org-calendar-follow-timestamp-change t
2376 "Non-nil means, make the calendar window follow timestamp changes.
2377 When a timestamp is modified and the calendar window is visible, it will be
2378 moved to the new date."
2379 :group 'org-time
2380 :type 'boolean)
2382 (defgroup org-tags nil
2383 "Options concerning tags in Org-mode."
2384 :tag "Org Tags"
2385 :group 'org)
2387 (defcustom org-tag-alist nil
2388 "List of tags allowed in Org-mode files.
2389 When this list is nil, Org-mode will base TAG input on what is already in the
2390 buffer.
2391 The value of this variable is an alist, the car of each entry must be a
2392 keyword as a string, the cdr may be a character that is used to select
2393 that tag through the fast-tag-selection interface.
2394 See the manual for details."
2395 :group 'org-tags
2396 :type '(repeat
2397 (choice
2398 (cons (string :tag "Tag name")
2399 (character :tag "Access char"))
2400 (list :tag "Start radio group"
2401 (const :startgroup)
2402 (option (string :tag "Group description")))
2403 (list :tag "End radio group"
2404 (const :endgroup)
2405 (option (string :tag "Group description")))
2406 (const :tag "New line" (:newline)))))
2408 (defcustom org-tag-persistent-alist nil
2409 "List of tags that will always appear in all Org-mode files.
2410 This is in addition to any in buffer settings or customizations
2411 of `org-tag-alist'.
2412 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2413 The value of this variable is an alist, the car of each entry must be a
2414 keyword as a string, the cdr may be a character that is used to select
2415 that tag through the fast-tag-selection interface.
2416 See the manual for details.
2417 To disable these tags on a per-file basis, insert anywhere in the file:
2418 #+STARTUP: noptag"
2419 :group 'org-tags
2420 :type '(repeat
2421 (choice
2422 (cons (string :tag "Tag name")
2423 (character :tag "Access char"))
2424 (const :tag "Start radio group" (:startgroup))
2425 (const :tag "End radio group" (:endgroup))
2426 (const :tag "New line" (:newline)))))
2428 (defvar org-file-tags nil
2429 "List of tags that can be inherited by all entries in the file.
2430 The tags will be inherited if the variable `org-use-tag-inheritance'
2431 says they should be.
2432 This variable is populated from #+FILETAGS lines.")
2434 (defcustom org-use-fast-tag-selection 'auto
2435 "Non-nil means, use fast tag selection scheme.
2436 This is a special interface to select and deselect tags with single keys.
2437 When nil, fast selection is never used.
2438 When the symbol `auto', fast selection is used if and only if selection
2439 characters for tags have been configured, either through the variable
2440 `org-tag-alist' or through a #+TAGS line in the buffer.
2441 When t, fast selection is always used and selection keys are assigned
2442 automatically if necessary."
2443 :group 'org-tags
2444 :type '(choice
2445 (const :tag "Always" t)
2446 (const :tag "Never" nil)
2447 (const :tag "When selection characters are configured" 'auto)))
2449 (defcustom org-fast-tag-selection-single-key nil
2450 "Non-nil means, fast tag selection exits after first change.
2451 When nil, you have to press RET to exit it.
2452 During fast tag selection, you can toggle this flag with `C-c'.
2453 This variable can also have the value `expert'. In this case, the window
2454 displaying the tags menu is not even shown, until you press C-c again."
2455 :group 'org-tags
2456 :type '(choice
2457 (const :tag "No" nil)
2458 (const :tag "Yes" t)
2459 (const :tag "Expert" expert)))
2461 (defvar org-fast-tag-selection-include-todo nil
2462 "Non-nil means, fast tags selection interface will also offer TODO states.
2463 This is an undocumented feature, you should not rely on it.")
2465 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2466 "The column to which tags should be indented in a headline.
2467 If this number is positive, it specifies the column. If it is negative,
2468 it means that the tags should be flushright to that column. For example,
2469 -80 works well for a normal 80 character screen."
2470 :group 'org-tags
2471 :type 'integer)
2473 (defcustom org-auto-align-tags t
2474 "Non-nil means, realign tags after pro/demotion of TODO state change.
2475 These operations change the length of a headline and therefore shift
2476 the tags around. With this options turned on, after each such operation
2477 the tags are again aligned to `org-tags-column'."
2478 :group 'org-tags
2479 :type 'boolean)
2481 (defcustom org-use-tag-inheritance t
2482 "Non-nil means, tags in levels apply also for sublevels.
2483 When nil, only the tags directly given in a specific line apply there.
2484 This may also be a list of tags that should be inherited, or a regexp that
2485 matches tags that should be inherited. Additional control is possible
2486 with the variable `org-tags-exclude-from-inheritance' which gives an
2487 explicit list of tags to be excluded from inheritance., even if the value of
2488 `org-use-tag-inheritance' would select it for inheritance.
2490 If this option is t, a match early-on in a tree can lead to a large
2491 number of matches in the subtree when constructing the agenda or creating
2492 a sparse tree. If you only want to see the first match in a tree during
2493 a search, check out the variable `org-tags-match-list-sublevels'."
2494 :group 'org-tags
2495 :type '(choice
2496 (const :tag "Not" nil)
2497 (const :tag "Always" t)
2498 (repeat :tag "Specific tags" (string :tag "Tag"))
2499 (regexp :tag "Tags matched by regexp")))
2501 (defcustom org-tags-exclude-from-inheritance nil
2502 "List of tags that should never be inherited.
2503 This is a way to exclude a few tags from inheritance. For way to do
2504 the opposite, to actively allow inheritance for selected tags,
2505 see the variable `org-use-tag-inheritance'."
2506 :group 'org-tags
2507 :type '(repeat (string :tag "Tag")))
2509 (defun org-tag-inherit-p (tag)
2510 "Check if TAG is one that should be inherited."
2511 (cond
2512 ((member tag org-tags-exclude-from-inheritance) nil)
2513 ((eq org-use-tag-inheritance t) t)
2514 ((not org-use-tag-inheritance) nil)
2515 ((stringp org-use-tag-inheritance)
2516 (string-match org-use-tag-inheritance tag))
2517 ((listp org-use-tag-inheritance)
2518 (member tag org-use-tag-inheritance))
2519 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2521 (defcustom org-tags-match-list-sublevels t
2522 "Non-nil means list also sublevels of headlines matching a search.
2523 This variable applies to tags/property searches, and also to stuck
2524 projects because this search is based on a tags match as well.
2526 When set to the symbol `indented', sublevels are indented with
2527 leading dots.
2529 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2530 the sublevels of a headline matching a tag search often also match
2531 the same search. Listing all of them can create very long lists.
2532 Setting this variable to nil causes subtrees of a match to be skipped.
2534 This variable is semi-obsolete and probably should always be true. It
2535 is better to limit inheritance to certain tags using the variables
2536 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2537 :group 'org-tags
2538 :type '(choice
2539 (const :tag "No, don't list them" nil)
2540 (const :tag "Yes, do list them" t)
2541 (const :tag "List them, indented with leading dots" indented)))
2543 (defcustom org-tags-sort-function nil
2544 "When set, tags are sorted using this function as a comparator"
2545 :group 'org-tags
2546 :type '(choice
2547 (const :tag "No sorting" nil)
2548 (const :tag "Alphabetical" string<)
2549 (const :tag "Reverse alphabetical" string>)
2550 (function :tag "Custom function" nil)))
2552 (defvar org-tags-history nil
2553 "History of minibuffer reads for tags.")
2554 (defvar org-last-tags-completion-table nil
2555 "The last used completion table for tags.")
2556 (defvar org-after-tags-change-hook nil
2557 "Hook that is run after the tags in a line have changed.")
2559 (defgroup org-properties nil
2560 "Options concerning properties in Org-mode."
2561 :tag "Org Properties"
2562 :group 'org)
2564 (defcustom org-property-format "%-10s %s"
2565 "How property key/value pairs should be formatted by `indent-line'.
2566 When `indent-line' hits a property definition, it will format the line
2567 according to this format, mainly to make sure that the values are
2568 lined-up with respect to each other."
2569 :group 'org-properties
2570 :type 'string)
2572 (defcustom org-use-property-inheritance nil
2573 "Non-nil means, properties apply also for sublevels.
2575 This setting is chiefly used during property searches. Turning it on can
2576 cause significant overhead when doing a search, which is why it is not
2577 on by default.
2579 When nil, only the properties directly given in the current entry count.
2580 When t, every property is inherited. The value may also be a list of
2581 properties that should have inheritance, or a regular expression matching
2582 properties that should be inherited.
2584 However, note that some special properties use inheritance under special
2585 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2586 and the properties ending in \"_ALL\" when they are used as descriptor
2587 for valid values of a property.
2589 Note for programmers:
2590 When querying an entry with `org-entry-get', you can control if inheritance
2591 should be used. By default, `org-entry-get' looks only at the local
2592 properties. You can request inheritance by setting the inherit argument
2593 to t (to force inheritance) or to `selective' (to respect the setting
2594 in this variable)."
2595 :group 'org-properties
2596 :type '(choice
2597 (const :tag "Not" nil)
2598 (const :tag "Always" t)
2599 (repeat :tag "Specific properties" (string :tag "Property"))
2600 (regexp :tag "Properties matched by regexp")))
2602 (defun org-property-inherit-p (property)
2603 "Check if PROPERTY is one that should be inherited."
2604 (cond
2605 ((eq org-use-property-inheritance t) t)
2606 ((not org-use-property-inheritance) nil)
2607 ((stringp org-use-property-inheritance)
2608 (string-match org-use-property-inheritance property))
2609 ((listp org-use-property-inheritance)
2610 (member property org-use-property-inheritance))
2611 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2613 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2614 "The default column format, if no other format has been defined.
2615 This variable can be set on the per-file basis by inserting a line
2617 #+COLUMNS: %25ITEM ....."
2618 :group 'org-properties
2619 :type 'string)
2621 (defcustom org-columns-ellipses ".."
2622 "The ellipses to be used when a field in column view is truncated.
2623 When this is the empty string, as many characters as possible are shown,
2624 but then there will be no visual indication that the field has been truncated.
2625 When this is a string of length N, the last N characters of a truncated
2626 field are replaced by this string. If the column is narrower than the
2627 ellipses string, only part of the ellipses string will be shown."
2628 :group 'org-properties
2629 :type 'string)
2631 (defcustom org-columns-modify-value-for-display-function nil
2632 "Function that modifies values for display in column view.
2633 For example, it can be used to cut out a certain part from a time stamp.
2634 The function must take 2 arguments:
2636 column-title The title of the column (*not* the property name)
2637 value The value that should be modified.
2639 The function should return the value that should be displayed,
2640 or nil if the normal value should be used."
2641 :group 'org-properties
2642 :type 'function)
2644 (defcustom org-effort-property "Effort"
2645 "The property that is being used to keep track of effort estimates.
2646 Effort estimates given in this property need to have the format H:MM."
2647 :group 'org-properties
2648 :group 'org-progress
2649 :type '(string :tag "Property"))
2651 (defconst org-global-properties-fixed
2652 '(("VISIBILITY_ALL" . "folded children content all")
2653 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2654 "List of property/value pairs that can be inherited by any entry.
2656 These are fixed values, for the preset properties. The user variable
2657 that can be used to add to this list is `org-global-properties'.
2659 The entries in this list are cons cells where the car is a property
2660 name and cdr is a string with the value. If the value represents
2661 multiple items like an \"_ALL\" property, separate the items by
2662 spaces.")
2664 (defcustom org-global-properties nil
2665 "List of property/value pairs that can be inherited by any entry.
2667 This list will be combined with the constant `org-global-properties-fixed'.
2669 The entries in this list are cons cells where the car is a property
2670 name and cdr is a string with the value.
2672 You can set buffer-local values for the same purpose in the variable
2673 `org-file-properties' this by adding lines like
2675 #+PROPERTY: NAME VALUE"
2676 :group 'org-properties
2677 :type '(repeat
2678 (cons (string :tag "Property")
2679 (string :tag "Value"))))
2681 (defvar org-file-properties nil
2682 "List of property/value pairs that can be inherited by any entry.
2683 Valid for the current buffer.
2684 This variable is populated from #+PROPERTY lines.")
2685 (make-variable-buffer-local 'org-file-properties)
2687 (defgroup org-agenda nil
2688 "Options concerning agenda views in Org-mode."
2689 :tag "Org Agenda"
2690 :group 'org)
2692 (defvar org-category nil
2693 "Variable used by org files to set a category for agenda display.
2694 Such files should use a file variable to set it, for example
2696 # -*- mode: org; org-category: \"ELisp\"
2698 or contain a special line
2700 #+CATEGORY: ELisp
2702 If the file does not specify a category, then file's base name
2703 is used instead.")
2704 (make-variable-buffer-local 'org-category)
2705 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2707 (defcustom org-agenda-files nil
2708 "The files to be used for agenda display.
2709 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2710 \\[org-remove-file]. You can also use customize to edit the list.
2712 If an entry is a directory, all files in that directory that are matched by
2713 `org-agenda-file-regexp' will be part of the file list.
2715 If the value of the variable is not a list but a single file name, then
2716 the list of agenda files is actually stored and maintained in that file, one
2717 agenda file per line."
2718 :group 'org-agenda
2719 :type '(choice
2720 (repeat :tag "List of files and directories" file)
2721 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2723 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2724 "Regular expression to match files for `org-agenda-files'.
2725 If any element in the list in that variable contains a directory instead
2726 of a normal file, all files in that directory that are matched by this
2727 regular expression will be included."
2728 :group 'org-agenda
2729 :type 'regexp)
2731 (defcustom org-agenda-text-search-extra-files nil
2732 "List of extra files to be searched by text search commands.
2733 These files will be search in addition to the agenda files by the
2734 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2735 Note that these files will only be searched for text search commands,
2736 not for the other agenda views like todo lists, tag searches or the weekly
2737 agenda. This variable is intended to list notes and possibly archive files
2738 that should also be searched by these two commands.
2739 In fact, if the first element in the list is the symbol `agenda-archives',
2740 than all archive files of all agenda files will be added to the search
2741 scope."
2742 :group 'org-agenda
2743 :type '(set :greedy t
2744 (const :tag "Agenda Archives" agenda-archives)
2745 (repeat :inline t (file))))
2747 (if (fboundp 'defvaralias)
2748 (defvaralias 'org-agenda-multi-occur-extra-files
2749 'org-agenda-text-search-extra-files))
2751 (defcustom org-agenda-skip-unavailable-files nil
2752 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2753 A nil value means to remove them, after a query, from the list."
2754 :group 'org-agenda
2755 :type 'boolean)
2757 (defcustom org-calendar-to-agenda-key [?c]
2758 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2759 The command `org-calendar-goto-agenda' will be bound to this key. The
2760 default is the character `c' because then `c' can be used to switch back and
2761 forth between agenda and calendar."
2762 :group 'org-agenda
2763 :type 'sexp)
2765 (defcustom org-calendar-agenda-action-key [?k]
2766 "The key to be installed in `calendar-mode-map' for agenda-action.
2767 The command `org-agenda-action' will be bound to this key. The
2768 default is the character `k' because we use the same key in the agenda."
2769 :group 'org-agenda
2770 :type 'sexp)
2772 (defcustom org-calendar-insert-diary-entry-key [?i]
2773 "The key to be installed in `calendar-mode-map' for adding diary entries.
2774 This option is irrelevant until `org-agenda-diary-file' has been configured
2775 to point to an Org-mode file. When that is the case, the command
2776 `org-agenda-diary-entry' will be bound to the key given here, by default
2777 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2778 if you want to continue doing this, you need to change this to a different
2779 key."
2780 :group 'org-agenda
2781 :type 'sexp)
2783 (defcustom org-agenda-diary-file 'diary-file
2784 "File to which to add new entries with the `i' key in agenda and calendar.
2785 When this is the symbol `diary-file', the functionality in the Emacs
2786 calendar will be used to add entries to the `diary-file'. But when this
2787 points to a file, `org-agenda-diary-entry' will be used instead."
2788 :group 'org-agenda
2789 :type '(choice
2790 (const :tag "The standard Emacs diary file" diary-file)
2791 (file :tag "Special Org file diary entries")))
2793 (eval-after-load "calendar"
2794 '(progn
2795 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2796 'org-calendar-goto-agenda)
2797 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2798 'org-agenda-action)
2799 (add-hook 'calendar-mode-hook
2800 (lambda ()
2801 (unless (eq org-agenda-diary-file 'diary-file)
2802 (define-key calendar-mode-map
2803 org-calendar-insert-diary-entry-key
2804 'org-agenda-diary-entry))))))
2806 (defgroup org-latex nil
2807 "Options for embedding LaTeX code into Org-mode."
2808 :tag "Org LaTeX"
2809 :group 'org)
2811 (defcustom org-format-latex-options
2812 '(:foreground default :background default :scale 1.0
2813 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2814 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2815 "Options for creating images from LaTeX fragments.
2816 This is a property list with the following properties:
2817 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2818 `default' means use the foreground of the default face.
2819 :background the background color, or \"Transparent\".
2820 `default' means use the background of the default face.
2821 :scale a scaling factor for the size of the images.
2822 :html-foreground, :html-background, :html-scale
2823 the same numbers for HTML export.
2824 :matchers a list indicating which matchers should be used to
2825 find LaTeX fragments. Valid members of this list are:
2826 \"begin\" find environments
2827 \"$1\" find single characters surrounded by $.$
2828 \"$\" find math expressions surrounded by $...$
2829 \"$$\" find math expressions surrounded by $$....$$
2830 \"\\(\" find math expressions surrounded by \\(...\\)
2831 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2832 :group 'org-latex
2833 :type 'plist)
2835 (defcustom org-format-latex-header "\\documentclass{article}
2836 \\usepackage{amssymb}
2837 \\usepackage[usenames]{color}
2838 \\usepackage{amsmath}
2839 \\usepackage{latexsym}
2840 \\usepackage[mathscr]{eucal}
2841 \\pagestyle{empty} % do not remove
2842 % The settings below are copied from fullpage.sty
2843 \\setlength{\\textwidth}{\\paperwidth}
2844 \\addtolength{\\textwidth}{-3cm}
2845 \\setlength{\\oddsidemargin}{1.5cm}
2846 \\addtolength{\\oddsidemargin}{-2.54cm}
2847 \\setlength{\\evensidemargin}{\\oddsidemargin}
2848 \\setlength{\\textheight}{\\paperheight}
2849 \\addtolength{\\textheight}{-\\headheight}
2850 \\addtolength{\\textheight}{-\\headsep}
2851 \\addtolength{\\textheight}{-\\footskip}
2852 \\addtolength{\\textheight}{-3cm}
2853 \\setlength{\\topmargin}{1.5cm}
2854 \\addtolength{\\topmargin}{-2.54cm}"
2855 "The document header used for processing LaTeX fragments.
2856 It is imperative that this header make sure that no page number
2857 appears on the page."
2858 :group 'org-latex
2859 :type 'string)
2861 ;; The following variable is defined here because is it also used
2862 ;; when formatting latex fragments. Originally it was part of the
2863 ;; LaTeX exporter, which is why the name includes "export".
2864 (defcustom org-export-latex-packages-alist nil
2865 "Alist of packages to be inserted in the header.
2866 Each cell is of the format \( \"option\" . \"package\" \)."
2867 :group 'org-export-latex
2868 :type '(repeat
2869 (list
2870 (string :tag "option")
2871 (string :tag "package"))))
2873 (defgroup org-font-lock nil
2874 "Font-lock settings for highlighting in Org-mode."
2875 :tag "Org Font Lock"
2876 :group 'org)
2878 (defcustom org-level-color-stars-only nil
2879 "Non-nil means fontify only the stars in each headline.
2880 When nil, the entire headline is fontified.
2881 Changing it requires restart of `font-lock-mode' to become effective
2882 also in regions already fontified."
2883 :group 'org-font-lock
2884 :type 'boolean)
2886 (defcustom org-hide-leading-stars nil
2887 "Non-nil means, hide the first N-1 stars in a headline.
2888 This works by using the face `org-hide' for these stars. This
2889 face is white for a light background, and black for a dark
2890 background. You may have to customize the face `org-hide' to
2891 make this work.
2892 Changing it requires restart of `font-lock-mode' to become effective
2893 also in regions already fontified.
2894 You may also set this on a per-file basis by adding one of the following
2895 lines to the buffer:
2897 #+STARTUP: hidestars
2898 #+STARTUP: showstars"
2899 :group 'org-font-lock
2900 :type 'boolean)
2902 (defcustom org-fontify-done-headline nil
2903 "Non-nil means, change the face of a headline if it is marked DONE.
2904 Normally, only the TODO/DONE keyword indicates the state of a headline.
2905 When this is non-nil, the headline after the keyword is set to the
2906 `org-headline-done' as an additional indication."
2907 :group 'org-font-lock
2908 :type 'boolean)
2910 (defcustom org-fontify-emphasized-text t
2911 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2912 Changing this variable requires a restart of Emacs to take effect."
2913 :group 'org-font-lock
2914 :type 'boolean)
2916 (defcustom org-fontify-whole-heading-line nil
2917 "Non-nil means fontify the whole line for headings.
2918 This is useful when setting a background color for the
2919 org-level-* faces."
2920 :group 'org-font-lock
2921 :type 'boolean)
2923 (defcustom org-highlight-latex-fragments-and-specials nil
2924 "Non-nil means, fontify what is treated specially by the exporters."
2925 :group 'org-font-lock
2926 :type 'boolean)
2928 (defcustom org-hide-emphasis-markers nil
2929 "Non-nil mean font-lock should hide the emphasis marker characters."
2930 :group 'org-font-lock
2931 :type 'boolean)
2933 (defvar org-emph-re nil
2934 "Regular expression for matching emphasis.")
2935 (defvar org-verbatim-re nil
2936 "Regular expression for matching verbatim text.")
2937 (defvar org-emphasis-regexp-components) ; defined just below
2938 (defvar org-emphasis-alist) ; defined just below
2939 (defun org-set-emph-re (var val)
2940 "Set variable and compute the emphasis regular expression."
2941 (set var val)
2942 (when (and (boundp 'org-emphasis-alist)
2943 (boundp 'org-emphasis-regexp-components)
2944 org-emphasis-alist org-emphasis-regexp-components)
2945 (let* ((e org-emphasis-regexp-components)
2946 (pre (car e))
2947 (post (nth 1 e))
2948 (border (nth 2 e))
2949 (body (nth 3 e))
2950 (nl (nth 4 e))
2951 (body1 (concat body "*?"))
2952 (markers (mapconcat 'car org-emphasis-alist ""))
2953 (vmarkers (mapconcat
2954 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2955 org-emphasis-alist "")))
2956 ;; make sure special characters appear at the right position in the class
2957 (if (string-match "\\^" markers)
2958 (setq markers (concat (replace-match "" t t markers) "^")))
2959 (if (string-match "-" markers)
2960 (setq markers (concat (replace-match "" t t markers) "-")))
2961 (if (string-match "\\^" vmarkers)
2962 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2963 (if (string-match "-" vmarkers)
2964 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2965 (if (> nl 0)
2966 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2967 (int-to-string nl) "\\}")))
2968 ;; Make the regexp
2969 (setq org-emph-re
2970 (concat "\\([" pre "]\\|^\\)"
2971 "\\("
2972 "\\([" markers "]\\)"
2973 "\\("
2974 "[^" border "]\\|"
2975 "[^" border "]"
2976 body1
2977 "[^" border "]"
2978 "\\)"
2979 "\\3\\)"
2980 "\\([" post "]\\|$\\)"))
2981 (setq org-verbatim-re
2982 (concat "\\([" pre "]\\|^\\)"
2983 "\\("
2984 "\\([" vmarkers "]\\)"
2985 "\\("
2986 "[^" border "]\\|"
2987 "[^" border "]"
2988 body1
2989 "[^" border "]"
2990 "\\)"
2991 "\\3\\)"
2992 "\\([" post "]\\|$\\)")))))
2994 (defcustom org-emphasis-regexp-components
2995 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2996 "Components used to build the regular expression for emphasis.
2997 This is a list with 6 entries. Terminology: In an emphasis string
2998 like \" *strong word* \", we call the initial space PREMATCH, the final
2999 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3000 and \"trong wor\" is the body. The different components in this variable
3001 specify what is allowed/forbidden in each part:
3003 pre Chars allowed as prematch. Beginning of line will be allowed too.
3004 post Chars allowed as postmatch. End of line will be allowed too.
3005 border The chars *forbidden* as border characters.
3006 body-regexp A regexp like \".\" to match a body character. Don't use
3007 non-shy groups here, and don't allow newline here.
3008 newline The maximum number of newlines allowed in an emphasis exp.
3010 Use customize to modify this, or restart Emacs after changing it."
3011 :group 'org-font-lock
3012 :set 'org-set-emph-re
3013 :type '(list
3014 (sexp :tag "Allowed chars in pre ")
3015 (sexp :tag "Allowed chars in post ")
3016 (sexp :tag "Forbidden chars in border ")
3017 (sexp :tag "Regexp for body ")
3018 (integer :tag "number of newlines allowed")
3019 (option (boolean :tag "Please ignore this button"))))
3021 (defcustom org-emphasis-alist
3022 `(("*" bold "<b>" "</b>")
3023 ("/" italic "<i>" "</i>")
3024 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3025 ("=" org-code "<code>" "</code>" verbatim)
3026 ("~" org-verbatim "<code>" "</code>" verbatim)
3027 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3028 "<del>" "</del>")
3030 "Special syntax for emphasized text.
3031 Text starting and ending with a special character will be emphasized, for
3032 example *bold*, _underlined_ and /italic/. This variable sets the marker
3033 characters, the face to be used by font-lock for highlighting in Org-mode
3034 Emacs buffers, and the HTML tags to be used for this.
3035 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3036 Use customize to modify this, or restart Emacs after changing it."
3037 :group 'org-font-lock
3038 :set 'org-set-emph-re
3039 :type '(repeat
3040 (list
3041 (string :tag "Marker character")
3042 (choice
3043 (face :tag "Font-lock-face")
3044 (plist :tag "Face property list"))
3045 (string :tag "HTML start tag")
3046 (string :tag "HTML end tag")
3047 (option (const verbatim)))))
3049 (defvar org-protecting-blocks
3050 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3051 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3052 This is needed for font-lock setup.")
3054 ;;; Miscellaneous options
3056 (defgroup org-completion nil
3057 "Completion in Org-mode."
3058 :tag "Org Completion"
3059 :group 'org)
3061 (defcustom org-completion-use-ido nil
3062 "Non-nil means, use ido completion wherever possible.
3063 Note that `ido-mode' must be active for this variable to be relevant.
3064 If you decide to turn this variable on, you might well want to turn off
3065 `org-outline-path-complete-in-steps'.
3066 See also `org-completion-use-iswitchb'."
3067 :group 'org-completion
3068 :type 'boolean)
3070 (defcustom org-completion-use-iswitchb nil
3071 "Non-nil means, use iswitchb completion wherever possible.
3072 Note that `iswitchb-mode' must be active for this variable to be relevant.
3073 If you decide to turn this variable on, you might well want to turn off
3074 `org-outline-path-complete-in-steps'.
3075 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3076 :group 'org-completion
3077 :type 'boolean)
3079 (defcustom org-completion-fallback-command 'hippie-expand
3080 "The expansion command called by \\[org-complete] in normal context.
3081 Normal means, no org-mode-specific context."
3082 :group 'org-completion
3083 :type 'function)
3085 ;;; Functions and variables from their packages
3086 ;; Declared here to avoid compiler warnings
3088 ;; XEmacs only
3089 (defvar outline-mode-menu-heading)
3090 (defvar outline-mode-menu-show)
3091 (defvar outline-mode-menu-hide)
3092 (defvar zmacs-regions) ; XEmacs regions
3094 ;; Emacs only
3095 (defvar mark-active)
3097 ;; Various packages
3098 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3099 (declare-function calendar-forward-day "cal-move" (arg))
3100 (declare-function calendar-goto-date "cal-move" (date))
3101 (declare-function calendar-goto-today "cal-move" ())
3102 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3103 (defvar calc-embedded-close-formula)
3104 (defvar calc-embedded-open-formula)
3105 (declare-function cdlatex-tab "ext:cdlatex" ())
3106 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3107 (defvar font-lock-unfontify-region-function)
3108 (declare-function iswitchb-read-buffer "iswitchb"
3109 (prompt &optional default require-match start matches-set))
3110 (defvar iswitchb-temp-buflist)
3111 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3112 (defvar org-agenda-tags-todo-honor-ignore-options)
3113 (declare-function org-agenda-skip "org-agenda" ())
3114 (declare-function
3115 org-format-agenda-item "org-agenda"
3116 (extra txt &optional category tags dotime noprefix remove-re habitp))
3117 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3118 (declare-function org-agenda-change-all-lines "org-agenda"
3119 (newhead hdmarker &optional fixface just-this))
3120 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3121 (declare-function org-agenda-maybe-redo "org-agenda" ())
3122 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3123 (beg end))
3124 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3125 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3126 "org-agenda" (&optional end))
3127 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3128 (declare-function org-indent-mode "org-indent" (&optional arg))
3129 (declare-function parse-time-string "parse-time" (string))
3130 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3131 (defvar remember-data-file)
3132 (defvar texmathp-why)
3133 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3134 (declare-function table--at-cell-p "table" (position &optional object at-column))
3136 (defvar w3m-current-url)
3137 (defvar w3m-current-title)
3139 (defvar org-latex-regexps)
3141 ;;; Autoload and prepare some org modules
3143 ;; Some table stuff that needs to be defined here, because it is used
3144 ;; by the functions setting up org-mode or checking for table context.
3146 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3147 "Detects an org-type or table-type table.")
3148 (defconst org-table-line-regexp "^[ \t]*|"
3149 "Detects an org-type table line.")
3150 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3151 "Detects an org-type table line.")
3152 (defconst org-table-hline-regexp "^[ \t]*|-"
3153 "Detects an org-type table hline.")
3154 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3155 "Detects a table-type table hline.")
3156 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3157 "Searching from within a table (any type) this finds the first line
3158 outside the table.")
3160 ;; Autoload the functions in org-table.el that are needed by functions here.
3162 (eval-and-compile
3163 (org-autoload "org-table"
3164 '(org-table-align org-table-begin org-table-blank-field
3165 org-table-convert org-table-convert-region org-table-copy-down
3166 org-table-copy-region org-table-create
3167 org-table-create-or-convert-from-region
3168 org-table-create-with-table.el org-table-current-dline
3169 org-table-cut-region org-table-delete-column org-table-edit-field
3170 org-table-edit-formulas org-table-end org-table-eval-formula
3171 org-table-export org-table-field-info
3172 org-table-get-stored-formulas org-table-goto-column
3173 org-table-hline-and-move org-table-import org-table-insert-column
3174 org-table-insert-hline org-table-insert-row org-table-iterate
3175 org-table-justify-field-maybe org-table-kill-row
3176 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3177 org-table-move-column org-table-move-column-left
3178 org-table-move-column-right org-table-move-row
3179 org-table-move-row-down org-table-move-row-up
3180 org-table-next-field org-table-next-row org-table-paste-rectangle
3181 org-table-previous-field org-table-recalculate
3182 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3183 org-table-toggle-coordinate-overlays
3184 org-table-toggle-formula-debugger org-table-wrap-region
3185 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3187 (defun org-at-table-p (&optional table-type)
3188 "Return t if the cursor is inside an org-type table.
3189 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3190 (if org-enable-table-editor
3191 (save-excursion
3192 (beginning-of-line 1)
3193 (looking-at (if table-type org-table-any-line-regexp
3194 org-table-line-regexp)))
3195 nil))
3196 (defsubst org-table-p () (org-at-table-p))
3198 (defun org-at-table.el-p ()
3199 "Return t if and only if we are at a table.el table."
3200 (and (org-at-table-p 'any)
3201 (save-excursion
3202 (goto-char (org-table-begin 'any))
3203 (looking-at org-table1-hline-regexp))))
3204 (defun org-table-recognize-table.el ()
3205 "If there is a table.el table nearby, recognize it and move into it."
3206 (if org-table-tab-recognizes-table.el
3207 (if (org-at-table.el-p)
3208 (progn
3209 (beginning-of-line 1)
3210 (if (looking-at org-table-dataline-regexp)
3212 (if (looking-at org-table1-hline-regexp)
3213 (progn
3214 (beginning-of-line 2)
3215 (if (looking-at org-table-any-border-regexp)
3216 (beginning-of-line -1)))))
3217 (if (re-search-forward "|" (org-table-end t) t)
3218 (progn
3219 (require 'table)
3220 (if (table--at-cell-p (point))
3222 (message "recognizing table.el table...")
3223 (table-recognize-table)
3224 (message "recognizing table.el table...done")))
3225 (error "This should not happen..."))
3227 nil)
3228 nil))
3230 (defun org-at-table-hline-p ()
3231 "Return t if the cursor is inside a hline in a table."
3232 (if org-enable-table-editor
3233 (save-excursion
3234 (beginning-of-line 1)
3235 (looking-at org-table-hline-regexp))
3236 nil))
3238 (defvar org-table-clean-did-remove-column nil)
3240 (defun org-table-map-tables (function)
3241 "Apply FUNCTION to the start of all tables in the buffer."
3242 (save-excursion
3243 (save-restriction
3244 (widen)
3245 (goto-char (point-min))
3246 (while (re-search-forward org-table-any-line-regexp nil t)
3247 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3248 (beginning-of-line 1)
3249 (when (looking-at org-table-line-regexp)
3250 (save-excursion (funcall function))
3251 (or (looking-at org-table-line-regexp)
3252 (forward-char 1)))
3253 (re-search-forward org-table-any-border-regexp nil 1))))
3254 (message "Mapping tables: done"))
3256 ;; Declare and autoload functions from org-exp.el & Co
3258 (declare-function org-default-export-plist "org-exp")
3259 (declare-function org-infile-export-plist "org-exp")
3260 (declare-function org-get-current-options "org-exp")
3261 (eval-and-compile
3262 (org-autoload "org-exp"
3263 '(org-export org-export-visible
3264 org-insert-export-options-template
3265 org-table-clean-before-export))
3266 (org-autoload "org-ascii"
3267 '(org-export-as-ascii org-export-ascii-preprocess
3268 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3269 org-export-region-as-ascii))
3270 (org-autoload "org-html"
3271 '(org-export-as-html-and-open
3272 org-export-as-html-batch org-export-as-html-to-buffer
3273 org-replace-region-by-html org-export-region-as-html
3274 org-export-as-html))
3275 (org-autoload "org-icalendar"
3276 '(org-export-icalendar-this-file
3277 org-export-icalendar-all-agenda-files
3278 org-export-icalendar-combine-agenda-files))
3279 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3281 ;; Declare and autoload functions from org-agenda.el
3283 (eval-and-compile
3284 (org-autoload "org-agenda"
3285 '(org-agenda org-agenda-list org-search-view
3286 org-todo-list org-tags-view org-agenda-list-stuck-projects
3287 org-diary org-agenda-to-appt
3288 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3290 ;; Autoload org-remember
3292 (eval-and-compile
3293 (org-autoload "org-remember"
3294 '(org-remember-insinuate org-remember-annotation
3295 org-remember-apply-template org-remember org-remember-handler)))
3297 ;; Autoload org-clock.el
3300 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3301 (beg end))
3302 (declare-function org-clock-update-mode-line "org-clock" ())
3303 (declare-function org-resolve-clocks "org-clock"
3304 (&optional also-non-dangling-p prompt last-valid))
3305 (defvar org-clock-start-time)
3306 (defvar org-clock-marker (make-marker)
3307 "Marker recording the last clock-in.")
3308 (defvar org-clock-hd-marker (make-marker)
3309 "Marker recording the last clock-in, but the headline position.")
3310 (defvar org-clock-heading ""
3311 "The heading of the current clock entry.")
3312 (defun org-clock-is-active ()
3313 "Return non-nil if clock is currently running.
3314 The return value is actually the clock marker."
3315 (marker-buffer org-clock-marker))
3317 (eval-and-compile
3318 (org-autoload
3319 "org-clock"
3320 '(org-clock-in org-clock-out org-clock-cancel
3321 org-clock-goto org-clock-sum org-clock-display
3322 org-clock-remove-overlays org-clock-report
3323 org-clocktable-shift org-dblock-write:clocktable
3324 org-get-clocktable org-resolve-clocks)))
3326 (defun org-clock-update-time-maybe ()
3327 "If this is a CLOCK line, update it and return t.
3328 Otherwise, return nil."
3329 (interactive)
3330 (save-excursion
3331 (beginning-of-line 1)
3332 (skip-chars-forward " \t")
3333 (when (looking-at org-clock-string)
3334 (let ((re (concat "[ \t]*" org-clock-string
3335 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3336 "\\([ \t]*=>.*\\)?\\)?"))
3337 ts te h m s neg)
3338 (cond
3339 ((not (looking-at re))
3340 nil)
3341 ((not (match-end 2))
3342 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3343 (> org-clock-marker (point))
3344 (<= org-clock-marker (point-at-eol)))
3345 ;; The clock is running here
3346 (setq org-clock-start-time
3347 (apply 'encode-time
3348 (org-parse-time-string (match-string 1))))
3349 (org-clock-update-mode-line)))
3351 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3352 (end-of-line 1)
3353 (setq ts (match-string 1)
3354 te (match-string 3))
3355 (setq s (- (org-float-time
3356 (apply 'encode-time (org-parse-time-string te)))
3357 (org-float-time
3358 (apply 'encode-time (org-parse-time-string ts))))
3359 neg (< s 0)
3360 s (abs s)
3361 h (floor (/ s 3600))
3362 s (- s (* 3600 h))
3363 m (floor (/ s 60))
3364 s (- s (* 60 s)))
3365 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3366 t))))))
3368 (defun org-check-running-clock ()
3369 "Check if the current buffer contains the running clock.
3370 If yes, offer to stop it and to save the buffer with the changes."
3371 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3372 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3373 (buffer-name))))
3374 (org-clock-out)
3375 (when (y-or-n-p "Save changed buffer?")
3376 (save-buffer))))
3378 (defun org-clocktable-try-shift (dir n)
3379 "Check if this line starts a clock table, if yes, shift the time block."
3380 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3381 (org-clocktable-shift dir n)))
3383 ;; Autoload org-timer.el
3385 (eval-and-compile
3386 (org-autoload
3387 "org-timer"
3388 '(org-timer-start org-timer org-timer-item
3389 org-timer-change-times-in-region
3390 org-timer-set-timer
3391 org-timer-reset-timers
3392 org-timer-show-remaining-time)))
3394 ;; Autoload org-feed.el
3396 (eval-and-compile
3397 (org-autoload
3398 "org-feed"
3399 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3402 ;; Autoload org-indent.el
3404 ;; Define the variable already here, to make sure we have it.
3405 (defvar org-indent-mode nil
3406 "Non-nil if Org-Indent mode is enabled.
3407 Use the command `org-indent-mode' to change this variable.")
3409 (eval-and-compile
3410 (org-autoload
3411 "org-indent"
3412 '(org-indent-mode)))
3414 ;; Autoload org-mobile.el
3416 (eval-and-compile
3417 (org-autoload
3418 "org-mobile"
3419 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3421 ;; Autoload archiving code
3422 ;; The stuff that is needed for cycling and tags has to be defined here.
3424 (defgroup org-archive nil
3425 "Options concerning archiving in Org-mode."
3426 :tag "Org Archive"
3427 :group 'org-structure)
3429 (defcustom org-archive-location "%s_archive::"
3430 "The location where subtrees should be archived.
3432 The value of this variable is a string, consisting of two parts,
3433 separated by a double-colon. The first part is a filename and
3434 the second part is a headline.
3436 When the filename is omitted, archiving happens in the same file.
3437 %s in the filename will be replaced by the current file
3438 name (without the directory part). Archiving to a different file
3439 is useful to keep archived entries from contributing to the
3440 Org-mode Agenda.
3442 The archived entries will be filed as subtrees of the specified
3443 headline. When the headline is omitted, the subtrees are simply
3444 filed away at the end of the file, as top-level entries. Also in
3445 the heading you can use %s to represent the file name, this can be
3446 useful when using the same archive for a number of different files.
3448 Here are a few examples:
3449 \"%s_archive::\"
3450 If the current file is Projects.org, archive in file
3451 Projects.org_archive, as top-level trees. This is the default.
3453 \"::* Archived Tasks\"
3454 Archive in the current file, under the top-level headline
3455 \"* Archived Tasks\".
3457 \"~/org/archive.org::\"
3458 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3460 \"~/org/archive.org::From %s\"
3461 Archive in file ~/org/archive.org (absolute path), under headlines
3462 \"From FILENAME\" where file name is the current file name.
3464 \"basement::** Finished Tasks\"
3465 Archive in file ./basement (relative path), as level 3 trees
3466 below the level 2 heading \"** Finished Tasks\".
3468 You may set this option on a per-file basis by adding to the buffer a
3469 line like
3471 #+ARCHIVE: basement::** Finished Tasks
3473 You may also define it locally for a subtree by setting an ARCHIVE property
3474 in the entry. If such a property is found in an entry, or anywhere up
3475 the hierarchy, it will be used."
3476 :group 'org-archive
3477 :type 'string)
3479 (defcustom org-archive-tag "ARCHIVE"
3480 "The tag that marks a subtree as archived.
3481 An archived subtree does not open during visibility cycling, and does
3482 not contribute to the agenda listings.
3483 After changing this, font-lock must be restarted in the relevant buffers to
3484 get the proper fontification."
3485 :group 'org-archive
3486 :group 'org-keywords
3487 :type 'string)
3489 (defcustom org-agenda-skip-archived-trees t
3490 "Non-nil means, the agenda will skip any items located in archived trees.
3491 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3492 variable is no longer recommended, you should leave it at the value t.
3493 Instead, use the key `v' to cycle the archives-mode in the agenda."
3494 :group 'org-archive
3495 :group 'org-agenda-skip
3496 :type 'boolean)
3498 (defcustom org-columns-skip-archived-trees t
3499 "Non-nil means, ignore archived trees when creating column view."
3500 :group 'org-archive
3501 :group 'org-properties
3502 :type 'boolean)
3504 (defcustom org-cycle-open-archived-trees nil
3505 "Non-nil means, `org-cycle' will open archived trees.
3506 An archived tree is a tree marked with the tag ARCHIVE.
3507 When nil, archived trees will stay folded. You can still open them with
3508 normal outline commands like `show-all', but not with the cycling commands."
3509 :group 'org-archive
3510 :group 'org-cycle
3511 :type 'boolean)
3513 (defcustom org-sparse-tree-open-archived-trees nil
3514 "Non-nil means sparse tree construction shows matches in archived trees.
3515 When nil, matches in these trees are highlighted, but the trees are kept in
3516 collapsed state."
3517 :group 'org-archive
3518 :group 'org-sparse-trees
3519 :type 'boolean)
3521 (defun org-cycle-hide-archived-subtrees (state)
3522 "Re-hide all archived subtrees after a visibility state change."
3523 (when (and (not org-cycle-open-archived-trees)
3524 (not (memq state '(overview folded))))
3525 (save-excursion
3526 (let* ((globalp (memq state '(contents all)))
3527 (beg (if globalp (point-min) (point)))
3528 (end (if globalp (point-max) (org-end-of-subtree t))))
3529 (org-hide-archived-subtrees beg end)
3530 (goto-char beg)
3531 (if (looking-at (concat ".*:" org-archive-tag ":"))
3532 (message "%s" (substitute-command-keys
3533 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3535 (defun org-force-cycle-archived ()
3536 "Cycle subtree even if it is archived."
3537 (interactive)
3538 (setq this-command 'org-cycle)
3539 (let ((org-cycle-open-archived-trees t))
3540 (call-interactively 'org-cycle)))
3542 (defun org-hide-archived-subtrees (beg end)
3543 "Re-hide all archived subtrees after a visibility state change."
3544 (save-excursion
3545 (let* ((re (concat ":" org-archive-tag ":")))
3546 (goto-char beg)
3547 (while (re-search-forward re end t)
3548 (and (org-on-heading-p) (org-flag-subtree t))
3549 (org-end-of-subtree t)))))
3551 (defun org-flag-subtree (flag)
3552 (save-excursion
3553 (org-back-to-heading t)
3554 (outline-end-of-heading)
3555 (outline-flag-region (point)
3556 (progn (org-end-of-subtree t) (point))
3557 flag)))
3559 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3561 (eval-and-compile
3562 (org-autoload "org-archive"
3563 '(org-add-archive-files org-archive-subtree
3564 org-archive-to-archive-sibling org-toggle-archive-tag)))
3566 ;; Autoload Column View Code
3568 (declare-function org-columns-number-to-string "org-colview")
3569 (declare-function org-columns-get-format-and-top-level "org-colview")
3570 (declare-function org-columns-compute "org-colview")
3572 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3573 '(org-columns-number-to-string org-columns-get-format-and-top-level
3574 org-columns-compute org-agenda-columns org-columns-remove-overlays
3575 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3577 ;; Autoload ID code
3579 (declare-function org-id-store-link "org-id")
3580 (declare-function org-id-locations-load "org-id")
3581 (declare-function org-id-locations-save "org-id")
3582 (defvar org-id-track-globally)
3583 (org-autoload "org-id"
3584 '(org-id-get-create org-id-new org-id-copy org-id-get
3585 org-id-get-with-outline-path-completion
3586 org-id-get-with-outline-drilling
3587 org-id-goto org-id-find org-id-store-link))
3589 ;; Autoload Plotting Code
3591 (org-autoload "org-plot"
3592 '(org-plot/gnuplot))
3594 ;;; Variables for pre-computed regular expressions, all buffer local
3596 (defvar org-drawer-regexp nil
3597 "Matches first line of a hidden block.")
3598 (make-variable-buffer-local 'org-drawer-regexp)
3599 (defvar org-todo-regexp nil
3600 "Matches any of the TODO state keywords.")
3601 (make-variable-buffer-local 'org-todo-regexp)
3602 (defvar org-not-done-regexp nil
3603 "Matches any of the TODO state keywords except the last one.")
3604 (make-variable-buffer-local 'org-not-done-regexp)
3605 (defvar org-not-done-heading-regexp nil
3606 "Matches a TODO headline that is not done.")
3607 (make-variable-buffer-local 'org-not-done-regexp)
3608 (defvar org-todo-line-regexp nil
3609 "Matches a headline and puts TODO state into group 2 if present.")
3610 (make-variable-buffer-local 'org-todo-line-regexp)
3611 (defvar org-complex-heading-regexp nil
3612 "Matches a headline and puts everything into groups:
3613 group 1: the stars
3614 group 2: The todo keyword, maybe
3615 group 3: Priority cookie
3616 group 4: True headline
3617 group 5: Tags")
3618 (make-variable-buffer-local 'org-complex-heading-regexp)
3619 (defvar org-complex-heading-regexp-format nil)
3620 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3621 (defvar org-todo-line-tags-regexp nil
3622 "Matches a headline and puts TODO state into group 2 if present.
3623 Also put tags into group 4 if tags are present.")
3624 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3625 (defvar org-nl-done-regexp nil
3626 "Matches newline followed by a headline with the DONE keyword.")
3627 (make-variable-buffer-local 'org-nl-done-regexp)
3628 (defvar org-looking-at-done-regexp nil
3629 "Matches the DONE keyword a point.")
3630 (make-variable-buffer-local 'org-looking-at-done-regexp)
3631 (defvar org-ds-keyword-length 12
3632 "Maximum length of the Deadline and SCHEDULED keywords.")
3633 (make-variable-buffer-local 'org-ds-keyword-length)
3634 (defvar org-deadline-regexp nil
3635 "Matches the DEADLINE keyword.")
3636 (make-variable-buffer-local 'org-deadline-regexp)
3637 (defvar org-deadline-time-regexp nil
3638 "Matches the DEADLINE keyword together with a time stamp.")
3639 (make-variable-buffer-local 'org-deadline-time-regexp)
3640 (defvar org-deadline-line-regexp nil
3641 "Matches the DEADLINE keyword and the rest of the line.")
3642 (make-variable-buffer-local 'org-deadline-line-regexp)
3643 (defvar org-scheduled-regexp nil
3644 "Matches the SCHEDULED keyword.")
3645 (make-variable-buffer-local 'org-scheduled-regexp)
3646 (defvar org-scheduled-time-regexp nil
3647 "Matches the SCHEDULED keyword together with a time stamp.")
3648 (make-variable-buffer-local 'org-scheduled-time-regexp)
3649 (defvar org-closed-time-regexp nil
3650 "Matches the CLOSED keyword together with a time stamp.")
3651 (make-variable-buffer-local 'org-closed-time-regexp)
3653 (defvar org-keyword-time-regexp nil
3654 "Matches any of the 4 keywords, together with the time stamp.")
3655 (make-variable-buffer-local 'org-keyword-time-regexp)
3656 (defvar org-keyword-time-not-clock-regexp nil
3657 "Matches any of the 3 keywords, together with the time stamp.")
3658 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3659 (defvar org-maybe-keyword-time-regexp nil
3660 "Matches a timestamp, possibly preceeded by a keyword.")
3661 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3662 (defvar org-planning-or-clock-line-re nil
3663 "Matches a line with planning or clock info.")
3664 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3666 (defconst org-plain-time-of-day-regexp
3667 (concat
3668 "\\(\\<[012]?[0-9]"
3669 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3670 "\\(--?"
3671 "\\(\\<[012]?[0-9]"
3672 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3673 "\\)?")
3674 "Regular expression to match a plain time or time range.
3675 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3676 groups carry important information:
3677 0 the full match
3678 1 the first time, range or not
3679 8 the second time, if it is a range.")
3681 (defconst org-plain-time-extension-regexp
3682 (concat
3683 "\\(\\<[012]?[0-9]"
3684 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3685 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3686 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3687 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3688 groups carry important information:
3689 0 the full match
3690 7 hours of duration
3691 9 minutes of duration")
3693 (defconst org-stamp-time-of-day-regexp
3694 (concat
3695 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3696 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3697 "\\(--?"
3698 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3699 "Regular expression to match a timestamp time or time range.
3700 After a match, the following groups carry important information:
3701 0 the full match
3702 1 date plus weekday, for back referencing to make sure both times are on the same day
3703 2 the first time, range or not
3704 4 the second time, if it is a range.")
3706 (defconst org-startup-options
3707 '(("fold" org-startup-folded t)
3708 ("overview" org-startup-folded t)
3709 ("nofold" org-startup-folded nil)
3710 ("showall" org-startup-folded nil)
3711 ("showeverything" org-startup-folded showeverything)
3712 ("content" org-startup-folded content)
3713 ("indent" org-startup-indented t)
3714 ("noindent" org-startup-indented nil)
3715 ("hidestars" org-hide-leading-stars t)
3716 ("showstars" org-hide-leading-stars nil)
3717 ("odd" org-odd-levels-only t)
3718 ("oddeven" org-odd-levels-only nil)
3719 ("align" org-startup-align-all-tables t)
3720 ("noalign" org-startup-align-all-tables nil)
3721 ("customtime" org-display-custom-times t)
3722 ("logdone" org-log-done time)
3723 ("lognotedone" org-log-done note)
3724 ("nologdone" org-log-done nil)
3725 ("lognoteclock-out" org-log-note-clock-out t)
3726 ("nolognoteclock-out" org-log-note-clock-out nil)
3727 ("logrepeat" org-log-repeat state)
3728 ("lognoterepeat" org-log-repeat note)
3729 ("nologrepeat" org-log-repeat nil)
3730 ("logreschedule" org-log-reschedule time)
3731 ("lognotereschedule" org-log-reschedule note)
3732 ("nologreschedule" org-log-reschedule nil)
3733 ("logredeadline" org-log-redeadline time)
3734 ("lognoteredeadline" org-log-redeadline note)
3735 ("nologredeadline" org-log-redeadline nil)
3736 ("fninline" org-footnote-define-inline t)
3737 ("nofninline" org-footnote-define-inline nil)
3738 ("fnlocal" org-footnote-section nil)
3739 ("fnauto" org-footnote-auto-label t)
3740 ("fnprompt" org-footnote-auto-label nil)
3741 ("fnconfirm" org-footnote-auto-label confirm)
3742 ("fnplain" org-footnote-auto-label plain)
3743 ("fnadjust" org-footnote-auto-adjust t)
3744 ("nofnadjust" org-footnote-auto-adjust nil)
3745 ("constcgs" constants-unit-system cgs)
3746 ("constSI" constants-unit-system SI)
3747 ("noptag" org-tag-persistent-alist nil)
3748 ("hideblocks" org-hide-block-startup t)
3749 ("nohideblocks" org-hide-block-startup nil))
3750 "Variable associated with STARTUP options for org-mode.
3751 Each element is a list of three items: The startup options as written
3752 in the #+STARTUP line, the corresponding variable, and the value to
3753 set this variable to if the option is found. An optional forth element PUSH
3754 means to push this value onto the list in the variable.")
3756 (defun org-set-regexps-and-options ()
3757 "Precompute regular expressions for current buffer."
3758 (when (org-mode-p)
3759 (org-set-local 'org-todo-kwd-alist nil)
3760 (org-set-local 'org-todo-key-alist nil)
3761 (org-set-local 'org-todo-key-trigger nil)
3762 (org-set-local 'org-todo-keywords-1 nil)
3763 (org-set-local 'org-done-keywords nil)
3764 (org-set-local 'org-todo-heads nil)
3765 (org-set-local 'org-todo-sets nil)
3766 (org-set-local 'org-todo-log-states nil)
3767 (org-set-local 'org-file-properties nil)
3768 (org-set-local 'org-file-tags nil)
3769 (let ((re (org-make-options-regexp
3770 '("CATEGORY" "TODO" "COLUMNS"
3771 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3772 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3773 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3774 (splitre "[ \t]+")
3775 kwds kws0 kwsa key log value cat arch tags const links hw dws
3776 tail sep kws1 prio props ftags drawers
3777 ext-setup-or-nil setup-contents (start 0))
3778 (save-excursion
3779 (save-restriction
3780 (widen)
3781 (goto-char (point-min))
3782 (while (or (and ext-setup-or-nil
3783 (string-match re ext-setup-or-nil start)
3784 (setq start (match-end 0)))
3785 (and (setq ext-setup-or-nil nil start 0)
3786 (re-search-forward re nil t)))
3787 (setq key (upcase (match-string 1 ext-setup-or-nil))
3788 value (org-match-string-no-properties 2 ext-setup-or-nil))
3789 (cond
3790 ((equal key "CATEGORY")
3791 (if (string-match "[ \t]+$" value)
3792 (setq value (replace-match "" t t value)))
3793 (setq cat value))
3794 ((member key '("SEQ_TODO" "TODO"))
3795 (push (cons 'sequence (org-split-string value splitre)) kwds))
3796 ((equal key "TYP_TODO")
3797 (push (cons 'type (org-split-string value splitre)) kwds))
3798 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3799 ;; general TODO-like setup
3800 (push (cons (intern (downcase (match-string 1 key)))
3801 (org-split-string value splitre)) kwds))
3802 ((equal key "TAGS")
3803 (setq tags (append tags (if tags '("\\n") nil)
3804 (org-split-string value splitre))))
3805 ((equal key "COLUMNS")
3806 (org-set-local 'org-columns-default-format value))
3807 ((equal key "LINK")
3808 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3809 (push (cons (match-string 1 value)
3810 (org-trim (match-string 2 value)))
3811 links)))
3812 ((equal key "PRIORITIES")
3813 (setq prio (org-split-string value " +")))
3814 ((equal key "PROPERTY")
3815 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3816 (push (cons (match-string 1 value) (match-string 2 value))
3817 props)))
3818 ((equal key "FILETAGS")
3819 (when (string-match "\\S-" value)
3820 (setq ftags
3821 (append
3822 ftags
3823 (apply 'append
3824 (mapcar (lambda (x) (org-split-string x ":"))
3825 (org-split-string value)))))))
3826 ((equal key "DRAWERS")
3827 (setq drawers (org-split-string value splitre)))
3828 ((equal key "CONSTANTS")
3829 (setq const (append const (org-split-string value splitre))))
3830 ((equal key "STARTUP")
3831 (let ((opts (org-split-string value splitre))
3832 l var val)
3833 (while (setq l (pop opts))
3834 (when (setq l (assoc l org-startup-options))
3835 (setq var (nth 1 l) val (nth 2 l))
3836 (if (not (nth 3 l))
3837 (set (make-local-variable var) val)
3838 (if (not (listp (symbol-value var)))
3839 (set (make-local-variable var) nil))
3840 (set (make-local-variable var) (symbol-value var))
3841 (add-to-list var val))))))
3842 ((equal key "ARCHIVE")
3843 (string-match " *$" value)
3844 (setq arch (replace-match "" t t value))
3845 (remove-text-properties 0 (length arch)
3846 '(face t fontified t) arch))
3847 ((equal key "SETUPFILE")
3848 (setq setup-contents (org-file-contents
3849 (expand-file-name
3850 (org-remove-double-quotes value))
3851 'noerror))
3852 (if (not ext-setup-or-nil)
3853 (setq ext-setup-or-nil setup-contents start 0)
3854 (setq ext-setup-or-nil
3855 (concat (substring ext-setup-or-nil 0 start)
3856 "\n" setup-contents "\n"
3857 (substring ext-setup-or-nil start)))))
3858 ))))
3859 (when cat
3860 (org-set-local 'org-category (intern cat))
3861 (push (cons "CATEGORY" cat) props))
3862 (when prio
3863 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3864 (setq prio (mapcar 'string-to-char prio))
3865 (org-set-local 'org-highest-priority (nth 0 prio))
3866 (org-set-local 'org-lowest-priority (nth 1 prio))
3867 (org-set-local 'org-default-priority (nth 2 prio)))
3868 (and props (org-set-local 'org-file-properties (nreverse props)))
3869 (and ftags (org-set-local 'org-file-tags
3870 (mapcar 'org-add-prop-inherited ftags)))
3871 (and drawers (org-set-local 'org-drawers drawers))
3872 (and arch (org-set-local 'org-archive-location arch))
3873 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3874 ;; Process the TODO keywords
3875 (unless kwds
3876 ;; Use the global values as if they had been given locally.
3877 (setq kwds (default-value 'org-todo-keywords))
3878 (if (stringp (car kwds))
3879 (setq kwds (list (cons org-todo-interpretation
3880 (default-value 'org-todo-keywords)))))
3881 (setq kwds (reverse kwds)))
3882 (setq kwds (nreverse kwds))
3883 (let (inter kws kw)
3884 (while (setq kws (pop kwds))
3885 (let ((kws (or
3886 (run-hook-with-args-until-success
3887 'org-todo-setup-filter-hook kws)
3888 kws)))
3889 (setq inter (pop kws) sep (member "|" kws)
3890 kws0 (delete "|" (copy-sequence kws))
3891 kwsa nil
3892 kws1 (mapcar
3893 (lambda (x)
3894 ;; 1 2
3895 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3896 (progn
3897 (setq kw (match-string 1 x)
3898 key (and (match-end 2) (match-string 2 x))
3899 log (org-extract-log-state-settings x))
3900 (push (cons kw (and key (string-to-char key))) kwsa)
3901 (and log (push log org-todo-log-states))
3903 (error "Invalid TODO keyword %s" x)))
3904 kws0)
3905 kwsa (if kwsa (append '((:startgroup))
3906 (nreverse kwsa)
3907 '((:endgroup))))
3908 hw (car kws1)
3909 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3910 tail (list inter hw (car dws) (org-last dws))))
3911 (add-to-list 'org-todo-heads hw 'append)
3912 (push kws1 org-todo-sets)
3913 (setq org-done-keywords (append org-done-keywords dws nil))
3914 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3915 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3916 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3917 (setq org-todo-sets (nreverse org-todo-sets)
3918 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3919 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3920 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3921 ;; Process the constants
3922 (when const
3923 (let (e cst)
3924 (while (setq e (pop const))
3925 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3926 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3927 (setq org-table-formula-constants-local cst)))
3929 ;; Process the tags.
3930 (when tags
3931 (let (e tgs)
3932 (while (setq e (pop tags))
3933 (cond
3934 ((equal e "{") (push '(:startgroup) tgs))
3935 ((equal e "}") (push '(:endgroup) tgs))
3936 ((equal e "\\n") (push '(:newline) tgs))
3937 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3938 (push (cons (match-string 1 e)
3939 (string-to-char (match-string 2 e)))
3940 tgs))
3941 (t (push (list e) tgs))))
3942 (org-set-local 'org-tag-alist nil)
3943 (while (setq e (pop tgs))
3944 (or (and (stringp (car e))
3945 (assoc (car e) org-tag-alist))
3946 (push e org-tag-alist)))))
3948 ;; Compute the regular expressions and other local variables
3949 (if (not org-done-keywords)
3950 (setq org-done-keywords (and org-todo-keywords-1
3951 (list (org-last org-todo-keywords-1)))))
3952 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3953 (length org-scheduled-string)
3954 (length org-clock-string)
3955 (length org-closed-string)))
3956 org-drawer-regexp
3957 (concat "^[ \t]*:\\("
3958 (mapconcat 'regexp-quote org-drawers "\\|")
3959 "\\):[ \t]*$")
3960 org-not-done-keywords
3961 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3962 org-todo-regexp
3963 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3964 "\\|") "\\)\\>")
3965 org-not-done-regexp
3966 (concat "\\<\\("
3967 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3968 "\\)\\>")
3969 org-not-done-heading-regexp
3970 (concat "^\\(\\*+\\)[ \t]+\\("
3971 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3972 "\\)\\>")
3973 org-todo-line-regexp
3974 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3975 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3976 "\\)\\>\\)?[ \t]*\\(.*\\)")
3977 org-complex-heading-regexp
3978 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3979 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3980 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3981 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3982 org-complex-heading-regexp-format
3983 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3984 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3985 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
3986 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3987 org-nl-done-regexp
3988 (concat "\n\\*+[ \t]+"
3989 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3990 "\\)" "\\>")
3991 org-todo-line-tags-regexp
3992 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3993 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3994 (org-re
3995 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3996 org-looking-at-done-regexp
3997 (concat "^" "\\(?:"
3998 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3999 "\\>")
4000 org-deadline-regexp (concat "\\<" org-deadline-string)
4001 org-deadline-time-regexp
4002 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4003 org-deadline-line-regexp
4004 (concat "\\<\\(" org-deadline-string "\\).*")
4005 org-scheduled-regexp
4006 (concat "\\<" org-scheduled-string)
4007 org-scheduled-time-regexp
4008 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4009 org-closed-time-regexp
4010 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4011 org-keyword-time-regexp
4012 (concat "\\<\\(" org-scheduled-string
4013 "\\|" org-deadline-string
4014 "\\|" org-closed-string
4015 "\\|" org-clock-string "\\)"
4016 " *[[<]\\([^]>]+\\)[]>]")
4017 org-keyword-time-not-clock-regexp
4018 (concat "\\<\\(" org-scheduled-string
4019 "\\|" org-deadline-string
4020 "\\|" org-closed-string
4021 "\\)"
4022 " *[[<]\\([^]>]+\\)[]>]")
4023 org-maybe-keyword-time-regexp
4024 (concat "\\(\\<\\(" org-scheduled-string
4025 "\\|" org-deadline-string
4026 "\\|" org-closed-string
4027 "\\|" org-clock-string "\\)\\)?"
4028 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4029 org-planning-or-clock-line-re
4030 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4031 "\\|" org-deadline-string
4032 "\\|" org-closed-string "\\|" org-clock-string
4033 "\\)\\>\\)")
4035 (org-compute-latex-and-specials-regexp)
4036 (org-set-font-lock-defaults))))
4038 (defun org-file-contents (file &optional noerror)
4039 "Return the contents of FILE, as a string."
4040 (if (or (not file)
4041 (not (file-readable-p file)))
4042 (if noerror
4043 (progn
4044 (message "Cannot read file %s" file)
4045 (ding) (sit-for 2)
4047 (error "Cannot read file %s" file))
4048 (with-temp-buffer
4049 (insert-file-contents file)
4050 (buffer-string))))
4052 (defun org-extract-log-state-settings (x)
4053 "Extract the log state setting from a TODO keyword string.
4054 This will extract info from a string like \"WAIT(w@/!)\"."
4055 (let (kw key log1 log2)
4056 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4057 (setq kw (match-string 1 x)
4058 key (and (match-end 2) (match-string 2 x))
4059 log1 (and (match-end 3) (match-string 3 x))
4060 log2 (and (match-end 4) (match-string 4 x)))
4061 (and (or log1 log2)
4062 (list kw
4063 (and log1 (if (equal log1 "!") 'time 'note))
4064 (and log2 (if (equal log2 "!") 'time 'note)))))))
4066 (defun org-remove-keyword-keys (list)
4067 "Remove a pair of parenthesis at the end of each string in LIST."
4068 (mapcar (lambda (x)
4069 (if (string-match "(.*)$" x)
4070 (substring x 0 (match-beginning 0))
4072 list))
4074 ;; FIXME: this could be done much better, using second characters etc.
4075 (defun org-assign-fast-keys (alist)
4076 "Assign fast keys to a keyword-key alist.
4077 Respect keys that are already there."
4078 (let (new e k c c1 c2 (char ?a))
4079 (while (setq e (pop alist))
4080 (cond
4081 ((equal e '(:startgroup)) (push e new))
4082 ((equal e '(:endgroup)) (push e new))
4083 ((equal e '(:newline)) (push e new))
4085 (setq k (car e) c2 nil)
4086 (if (cdr e)
4087 (setq c (cdr e))
4088 ;; automatically assign a character.
4089 (setq c1 (string-to-char
4090 (downcase (substring
4091 k (if (= (string-to-char k) ?@) 1 0)))))
4092 (if (or (rassoc c1 new) (rassoc c1 alist))
4093 (while (or (rassoc char new) (rassoc char alist))
4094 (setq char (1+ char)))
4095 (setq c2 c1))
4096 (setq c (or c2 char)))
4097 (push (cons k c) new))))
4098 (nreverse new)))
4100 ;;; Some variables used in various places
4102 (defvar org-window-configuration nil
4103 "Used in various places to store a window configuration.")
4104 (defvar org-selected-window nil
4105 "Used in various places to store a window configuration.")
4106 (defvar org-finish-function nil
4107 "Function to be called when `C-c C-c' is used.
4108 This is for getting out of special buffers like remember.")
4111 ;; FIXME: Occasionally check by commenting these, to make sure
4112 ;; no other functions uses these, forgetting to let-bind them.
4113 (defvar entry)
4114 (defvar last-state)
4115 (defvar date)
4117 ;; Defined somewhere in this file, but used before definition.
4118 (defvar org-html-entities)
4119 (defvar org-struct-menu)
4120 (defvar org-org-menu)
4121 (defvar org-tbl-menu)
4123 ;;;; Define the Org-mode
4125 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4126 (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."))
4129 ;; We use a before-change function to check if a table might need
4130 ;; an update.
4131 (defvar org-table-may-need-update t
4132 "Indicates that a table might need an update.
4133 This variable is set by `org-before-change-function'.
4134 `org-table-align' sets it back to nil.")
4135 (defun org-before-change-function (beg end)
4136 "Every change indicates that a table might need an update."
4137 (setq org-table-may-need-update t))
4138 (defvar org-mode-map)
4139 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4140 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4141 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4142 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4143 (defvar org-table-buffer-is-an nil)
4144 (defconst org-outline-regexp "\\*+ ")
4146 ;;;###autoload
4147 (define-derived-mode org-mode outline-mode "Org"
4148 "Outline-based notes management and organizer, alias
4149 \"Carsten's outline-mode for keeping track of everything.\"
4151 Org-mode develops organizational tasks around a NOTES file which
4152 contains information about projects as plain text. Org-mode is
4153 implemented on top of outline-mode, which is ideal to keep the content
4154 of large files well structured. It supports ToDo items, deadlines and
4155 time stamps, which magically appear in the diary listing of the Emacs
4156 calendar. Tables are easily created with a built-in table editor.
4157 Plain text URL-like links connect to websites, emails (VM), Usenet
4158 messages (Gnus), BBDB entries, and any files related to the project.
4159 For printing and sharing of notes, an Org-mode file (or a part of it)
4160 can be exported as a structured ASCII or HTML file.
4162 The following commands are available:
4164 \\{org-mode-map}"
4166 ;; Get rid of Outline menus, they are not needed
4167 ;; Need to do this here because define-derived-mode sets up
4168 ;; the keymap so late. Still, it is a waste to call this each time
4169 ;; we switch another buffer into org-mode.
4170 (if (featurep 'xemacs)
4171 (when (boundp 'outline-mode-menu-heading)
4172 ;; Assume this is Greg's port, it used easymenu
4173 (easy-menu-remove outline-mode-menu-heading)
4174 (easy-menu-remove outline-mode-menu-show)
4175 (easy-menu-remove outline-mode-menu-hide))
4176 (define-key org-mode-map [menu-bar headings] 'undefined)
4177 (define-key org-mode-map [menu-bar hide] 'undefined)
4178 (define-key org-mode-map [menu-bar show] 'undefined))
4180 (org-load-modules-maybe)
4181 (easy-menu-add org-org-menu)
4182 (easy-menu-add org-tbl-menu)
4183 (org-install-agenda-files-menu)
4184 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4185 (org-add-to-invisibility-spec '(org-cwidth))
4186 (org-add-to-invisibility-spec '(org-hide-block . t))
4187 (when (featurep 'xemacs)
4188 (org-set-local 'line-move-ignore-invisible t))
4189 (org-set-local 'outline-regexp org-outline-regexp)
4190 (org-set-local 'outline-level 'org-outline-level)
4191 (when (and org-ellipsis
4192 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4193 (fboundp 'make-glyph-code))
4194 (unless org-display-table
4195 (setq org-display-table (make-display-table)))
4196 (set-display-table-slot
4197 org-display-table 4
4198 (vconcat (mapcar
4199 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4200 org-ellipsis)))
4201 (if (stringp org-ellipsis) org-ellipsis "..."))))
4202 (setq buffer-display-table org-display-table))
4203 (org-set-regexps-and-options)
4204 (when (and org-tag-faces (not org-tags-special-faces-re))
4205 ;; tag faces set outside customize.... force initialization.
4206 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4207 ;; Calc embedded
4208 (org-set-local 'calc-embedded-open-mode "# ")
4209 (modify-syntax-entry ?# "<")
4210 (modify-syntax-entry ?@ "w")
4211 (if org-startup-truncated (setq truncate-lines t))
4212 (org-set-local 'font-lock-unfontify-region-function
4213 'org-unfontify-region)
4214 ;; Activate before-change-function
4215 (org-set-local 'org-table-may-need-update t)
4216 (org-add-hook 'before-change-functions 'org-before-change-function nil
4217 'local)
4218 ;; Check for running clock before killing a buffer
4219 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4220 ;; Paragraphs and auto-filling
4221 (org-set-autofill-regexps)
4222 (setq indent-line-function 'org-indent-line-function)
4223 (org-update-radio-target-regexp)
4224 ;; Make sure dependence stuff works reliably, even for users who set it
4225 ;; too late :-(
4226 (if org-enforce-todo-dependencies
4227 (add-hook 'org-blocker-hook
4228 'org-block-todo-from-children-or-siblings-or-parent)
4229 (remove-hook 'org-blocker-hook
4230 'org-block-todo-from-children-or-siblings-or-parent))
4231 (if org-enforce-todo-checkbox-dependencies
4232 (add-hook 'org-blocker-hook
4233 'org-block-todo-from-checkboxes)
4234 (remove-hook 'org-blocker-hook
4235 'org-block-todo-from-checkboxes))
4237 ;; Comment characters
4238 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4239 (org-set-local 'comment-padding " ")
4241 ;; Align options lines
4242 (org-set-local
4243 'align-mode-rules-list
4244 '((org-in-buffer-settings
4245 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4246 (modes . '(org-mode)))))
4248 ;; Imenu
4249 (org-set-local 'imenu-create-index-function
4250 'org-imenu-get-tree)
4252 ;; Make isearch reveal context
4253 (if (or (featurep 'xemacs)
4254 (not (boundp 'outline-isearch-open-invisible-function)))
4255 ;; Emacs 21 and XEmacs make use of the hook
4256 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4257 ;; Emacs 22 deals with this through a special variable
4258 (org-set-local 'outline-isearch-open-invisible-function
4259 (lambda (&rest ignore) (org-show-context 'isearch))))
4261 ;; If empty file that did not turn on org-mode automatically, make it to.
4262 (if (and org-insert-mode-line-in-empty-file
4263 (interactive-p)
4264 (= (point-min) (point-max)))
4265 (insert "# -*- mode: org -*-\n\n"))
4267 (unless org-inhibit-startup
4268 (when org-startup-align-all-tables
4269 (let ((bmp (buffer-modified-p)))
4270 (org-table-map-tables 'org-table-align)
4271 (set-buffer-modified-p bmp)))
4272 (when org-startup-indented
4273 (require 'org-indent)
4274 (org-indent-mode 1))
4275 (org-set-startup-visibility)))
4277 (when (fboundp 'abbrev-table-put)
4278 (abbrev-table-put org-mode-abbrev-table
4279 :parents (list text-mode-abbrev-table)))
4281 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4283 (defun org-current-time ()
4284 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4285 (if (> (car org-time-stamp-rounding-minutes) 1)
4286 (let ((r (car org-time-stamp-rounding-minutes))
4287 (time (decode-time)))
4288 (apply 'encode-time
4289 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4290 (nthcdr 2 time))))
4291 (current-time)))
4293 ;;;; Font-Lock stuff, including the activators
4295 (defvar org-mouse-map (make-sparse-keymap))
4296 (org-defkey org-mouse-map
4297 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4298 (org-defkey org-mouse-map
4299 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4300 (when org-mouse-1-follows-link
4301 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4302 (when org-tab-follows-link
4303 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4304 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4306 (require 'font-lock)
4308 (defconst org-non-link-chars "]\t\n\r<>")
4309 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4310 "shell" "elisp"))
4311 (defvar org-link-types-re nil
4312 "Matches a link that has a url-like prefix like \"http:\"")
4313 (defvar org-link-re-with-space nil
4314 "Matches a link with spaces, optional angular brackets around it.")
4315 (defvar org-link-re-with-space2 nil
4316 "Matches a link with spaces, optional angular brackets around it.")
4317 (defvar org-link-re-with-space3 nil
4318 "Matches a link with spaces, only for internal part in bracket links.")
4319 (defvar org-angle-link-re nil
4320 "Matches link with angular brackets, spaces are allowed.")
4321 (defvar org-plain-link-re nil
4322 "Matches plain link, without spaces.")
4323 (defvar org-bracket-link-regexp nil
4324 "Matches a link in double brackets.")
4325 (defvar org-bracket-link-analytic-regexp nil
4326 "Regular expression used to analyze links.
4327 Here is what the match groups contain after a match:
4328 1: http:
4329 2: http
4330 3: path
4331 4: [desc]
4332 5: desc")
4333 (defvar org-bracket-link-analytic-regexp++ nil
4334 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4335 (defvar org-any-link-re nil
4336 "Regular expression matching any link.")
4338 (defun org-make-link-regexps ()
4339 "Update the link regular expressions.
4340 This should be called after the variable `org-link-types' has changed."
4341 (setq org-link-types-re
4342 (concat
4343 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4344 org-link-re-with-space
4345 (concat
4346 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4347 "\\([^" org-non-link-chars " ]"
4348 "[^" org-non-link-chars "]*"
4349 "[^" org-non-link-chars " ]\\)>?")
4350 org-link-re-with-space2
4351 (concat
4352 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4353 "\\([^" org-non-link-chars " ]"
4354 "[^\t\n\r]*"
4355 "[^" org-non-link-chars " ]\\)>?")
4356 org-link-re-with-space3
4357 (concat
4358 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4359 "\\([^" org-non-link-chars " ]"
4360 "[^\t\n\r]*\\)")
4361 org-angle-link-re
4362 (concat
4363 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4364 "\\([^" org-non-link-chars " ]"
4365 "[^" org-non-link-chars "]*"
4366 "\\)>")
4367 org-plain-link-re
4368 (concat
4369 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4370 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4371 org-bracket-link-regexp
4372 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4373 org-bracket-link-analytic-regexp
4374 (concat
4375 "\\[\\["
4376 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4377 "\\([^]]+\\)"
4378 "\\]"
4379 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4380 "\\]")
4381 org-bracket-link-analytic-regexp++
4382 (concat
4383 "\\[\\["
4384 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4385 "\\([^]]+\\)"
4386 "\\]"
4387 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4388 "\\]")
4389 org-any-link-re
4390 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4391 org-angle-link-re "\\)\\|\\("
4392 org-plain-link-re "\\)")))
4394 (org-make-link-regexps)
4396 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4397 "Regular expression for fast time stamp matching.")
4398 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4399 "Regular expression for fast time stamp matching.")
4400 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4401 "Regular expression matching time strings for analysis.
4402 This one does not require the space after the date, so it can be used
4403 on a string that terminates immediately after the date.")
4404 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4405 "Regular expression matching time strings for analysis.")
4406 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4407 "Regular expression matching time stamps, with groups.")
4408 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4409 "Regular expression matching time stamps (also [..]), with groups.")
4410 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4411 "Regular expression matching a time stamp range.")
4412 (defconst org-tr-regexp-both
4413 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4414 "Regular expression matching a time stamp range.")
4415 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4416 org-ts-regexp "\\)?")
4417 "Regular expression matching a time stamp or time stamp range.")
4418 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4419 org-ts-regexp-both "\\)?")
4420 "Regular expression matching a time stamp or time stamp range.
4421 The time stamps may be either active or inactive.")
4423 (defvar org-emph-face nil)
4425 (defun org-do-emphasis-faces (limit)
4426 "Run through the buffer and add overlays to links."
4427 (let (rtn a)
4428 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4429 (if (not (= (char-after (match-beginning 3))
4430 (char-after (match-beginning 4))))
4431 (progn
4432 (setq rtn t)
4433 (setq a (assoc (match-string 3) org-emphasis-alist))
4434 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4435 'face
4436 (nth 1 a))
4437 (and (nth 4 a)
4438 (org-remove-flyspell-overlays-in
4439 (match-beginning 0) (match-end 0)))
4440 (add-text-properties (match-beginning 2) (match-end 2)
4441 '(font-lock-multiline t))
4442 (when org-hide-emphasis-markers
4443 (add-text-properties (match-end 4) (match-beginning 5)
4444 '(invisible org-link))
4445 (add-text-properties (match-beginning 3) (match-end 3)
4446 '(invisible org-link)))))
4447 (backward-char 1))
4448 rtn))
4450 (defun org-emphasize (&optional char)
4451 "Insert or change an emphasis, i.e. a font like bold or italic.
4452 If there is an active region, change that region to a new emphasis.
4453 If there is no region, just insert the marker characters and position
4454 the cursor between them.
4455 CHAR should be either the marker character, or the first character of the
4456 HTML tag associated with that emphasis. If CHAR is a space, the means
4457 to remove the emphasis of the selected region.
4458 If char is not given (for example in an interactive call) it
4459 will be prompted for."
4460 (interactive)
4461 (let ((eal org-emphasis-alist) e det
4462 (erc org-emphasis-regexp-components)
4463 (prompt "")
4464 (string "") beg end move tag c s)
4465 (if (org-region-active-p)
4466 (setq beg (region-beginning) end (region-end)
4467 string (buffer-substring beg end))
4468 (setq move t))
4470 (while (setq e (pop eal))
4471 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4472 c (aref tag 0))
4473 (push (cons c (string-to-char (car e))) det)
4474 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4475 (substring tag 1)))))
4476 (setq det (nreverse det))
4477 (unless char
4478 (message "%s" (concat "Emphasis marker or tag:" prompt))
4479 (setq char (read-char-exclusive)))
4480 (setq char (or (cdr (assoc char det)) char))
4481 (if (equal char ?\ )
4482 (setq s "" move nil)
4483 (unless (assoc (char-to-string char) org-emphasis-alist)
4484 (error "No such emphasis marker: \"%c\"" char))
4485 (setq s (char-to-string char)))
4486 (while (and (> (length string) 1)
4487 (equal (substring string 0 1) (substring string -1))
4488 (assoc (substring string 0 1) org-emphasis-alist))
4489 (setq string (substring string 1 -1)))
4490 (setq string (concat s string s))
4491 (if beg (delete-region beg end))
4492 (unless (or (bolp)
4493 (string-match (concat "[" (nth 0 erc) "\n]")
4494 (char-to-string (char-before (point)))))
4495 (insert " "))
4496 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4497 (char-to-string (char-after (point))))
4498 (insert " ") (backward-char 1))
4499 (insert string)
4500 (and move (backward-char 1))))
4502 (defconst org-nonsticky-props
4503 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4505 (defsubst org-rear-nonsticky-at (pos)
4506 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4508 (defun org-activate-plain-links (limit)
4509 "Run through the buffer and add overlays to links."
4510 (catch 'exit
4511 (let (f)
4512 (if (re-search-forward org-plain-link-re limit t)
4513 (progn
4514 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4515 (setq f (get-text-property (match-beginning 0) 'face))
4516 (if (or (eq f 'org-tag)
4517 (and (listp f) (memq 'org-tag f)))
4519 (add-text-properties (match-beginning 0) (match-end 0)
4520 (list 'mouse-face 'highlight
4521 'keymap org-mouse-map))
4522 (org-rear-nonsticky-at (match-end 0)))
4523 t)))))
4525 (defun org-activate-code (limit)
4526 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4527 (progn
4528 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4529 (remove-text-properties (match-beginning 0) (match-end 0)
4530 '(display t invisible t intangible t))
4531 t)))
4533 (defun org-fontify-meta-lines-and-blocks (limit)
4534 "Fontify #+ lines and blocks, in the correct ways."
4535 (let ((case-fold-search t))
4536 (if (re-search-forward
4537 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4538 limit t)
4539 (let ((beg (match-beginning 0))
4540 (beg1 (line-beginning-position 2))
4541 (dc1 (downcase (match-string 2)))
4542 (dc3 (downcase (match-string 3)))
4543 end end1 quoting)
4544 (cond
4545 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4546 ;; a single line of backend-specific content
4547 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4548 (remove-text-properties (match-beginning 0) (match-end 0)
4549 '(display t invisible t intangible t))
4550 (add-text-properties (match-beginning 1) (match-end 3)
4551 '(font-lock-fontified t face org-meta-line))
4552 (add-text-properties (match-beginning 6) (match-end 6)
4553 '(font-lock-fontified t face org-block))
4555 ((and (match-end 4) (equal dc3 "begin"))
4556 ;; Truely a block
4557 (setq quoting (member (downcase (match-string 5))
4558 org-protecting-blocks))
4559 (when (re-search-forward
4560 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4561 nil t) ;; on purpose, we look further than LIMIT
4562 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4563 (when quoting
4564 (remove-text-properties beg end
4565 '(display t invisible t intangible t)))
4566 (add-text-properties
4567 beg end
4568 '(font-lock-fontified t font-lock-multiline t))
4569 (add-text-properties beg beg1 '(face org-meta-line))
4570 (add-text-properties end1 end '(face org-meta-line))
4571 (when quoting
4572 (add-text-properties beg1 end1 '(face org-block)))
4574 ((not (member (char-after beg) '(?\ ?\t)))
4575 ;; just any other in-buffer setting, but not indented
4576 (add-text-properties
4577 beg (match-end 0)
4578 '(font-lock-fontified t face org-meta-line))
4580 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4581 "orgtbl:" "tblfm:" "tblname:"))
4582 (and (match-end 4) (equal dc3 "attr")))
4583 (add-text-properties
4584 beg (match-end 0)
4585 '(font-lock-fontified t face org-meta-line))
4587 ((member dc3 '(" " ""))
4588 (add-text-properties
4589 beg (match-end 0)
4590 '(font-lock-fontified t face font-lock-comment-face)))
4591 (t nil))))))
4593 (defun org-activate-angle-links (limit)
4594 "Run through the buffer and add overlays to links."
4595 (if (re-search-forward org-angle-link-re limit t)
4596 (progn
4597 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4598 (add-text-properties (match-beginning 0) (match-end 0)
4599 (list 'mouse-face 'highlight
4600 'keymap org-mouse-map))
4601 (org-rear-nonsticky-at (match-end 0))
4602 t)))
4604 (defun org-activate-footnote-links (limit)
4605 "Run through the buffer and add overlays to links."
4606 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4607 limit t)
4608 (progn
4609 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4610 (add-text-properties (match-beginning 2) (match-end 2)
4611 (list 'mouse-face 'highlight
4612 'keymap org-mouse-map
4613 'help-echo
4614 (if (= (point-at-bol) (match-beginning 2))
4615 "Footnote definition"
4616 "Footnote reference")
4618 (org-rear-nonsticky-at (match-end 2))
4619 t)))
4621 (defun org-activate-bracket-links (limit)
4622 "Run through the buffer and add overlays to bracketed links."
4623 (if (re-search-forward org-bracket-link-regexp limit t)
4624 (let* ((help (concat "LINK: "
4625 (org-match-string-no-properties 1)))
4626 ;; FIXME: above we should remove the escapes.
4627 ;; but that requires another match, protecting match data,
4628 ;; a lot of overhead for font-lock.
4629 (ip (org-maybe-intangible
4630 (list 'invisible 'org-link
4631 'keymap org-mouse-map 'mouse-face 'highlight
4632 'font-lock-multiline t 'help-echo help)))
4633 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4634 'font-lock-multiline t 'help-echo help)))
4635 ;; We need to remove the invisible property here. Table narrowing
4636 ;; may have made some of this invisible.
4637 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4638 (remove-text-properties (match-beginning 0) (match-end 0)
4639 '(invisible nil))
4640 (if (match-end 3)
4641 (progn
4642 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4643 (org-rear-nonsticky-at (match-beginning 3))
4644 (add-text-properties (match-beginning 3) (match-end 3) vp)
4645 (org-rear-nonsticky-at (match-end 3))
4646 (add-text-properties (match-end 3) (match-end 0) ip)
4647 (org-rear-nonsticky-at (match-end 0)))
4648 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4649 (org-rear-nonsticky-at (match-beginning 1))
4650 (add-text-properties (match-beginning 1) (match-end 1) vp)
4651 (org-rear-nonsticky-at (match-end 1))
4652 (add-text-properties (match-end 1) (match-end 0) ip)
4653 (org-rear-nonsticky-at (match-end 0)))
4654 t)))
4656 (defun org-activate-dates (limit)
4657 "Run through the buffer and add overlays to dates."
4658 (if (re-search-forward org-tsr-regexp-both limit t)
4659 (progn
4660 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4661 (add-text-properties (match-beginning 0) (match-end 0)
4662 (list 'mouse-face 'highlight
4663 'keymap org-mouse-map))
4664 (org-rear-nonsticky-at (match-end 0))
4665 (when org-display-custom-times
4666 (if (match-end 3)
4667 (org-display-custom-time (match-beginning 3) (match-end 3)))
4668 (org-display-custom-time (match-beginning 1) (match-end 1)))
4669 t)))
4671 (defvar org-target-link-regexp nil
4672 "Regular expression matching radio targets in plain text.")
4673 (make-variable-buffer-local 'org-target-link-regexp)
4674 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4675 "Regular expression matching a link target.")
4676 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4677 "Regular expression matching a radio target.")
4678 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4679 "Regular expression matching any target.")
4681 (defun org-activate-target-links (limit)
4682 "Run through the buffer and add overlays to target matches."
4683 (when org-target-link-regexp
4684 (let ((case-fold-search t))
4685 (if (re-search-forward org-target-link-regexp limit t)
4686 (progn
4687 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4688 (add-text-properties (match-beginning 0) (match-end 0)
4689 (list 'mouse-face 'highlight
4690 'keymap org-mouse-map
4691 'help-echo "Radio target link"
4692 'org-linked-text t))
4693 (org-rear-nonsticky-at (match-end 0))
4694 t)))))
4696 (defun org-update-radio-target-regexp ()
4697 "Find all radio targets in this file and update the regular expression."
4698 (interactive)
4699 (when (memq 'radio org-activate-links)
4700 (setq org-target-link-regexp
4701 (org-make-target-link-regexp (org-all-targets 'radio)))
4702 (org-restart-font-lock)))
4704 (defun org-hide-wide-columns (limit)
4705 (let (s e)
4706 (setq s (text-property-any (point) (or limit (point-max))
4707 'org-cwidth t))
4708 (when s
4709 (setq e (next-single-property-change s 'org-cwidth))
4710 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4711 (goto-char e)
4712 t)))
4714 (defvar org-latex-and-specials-regexp nil
4715 "Regular expression for highlighting export special stuff.")
4716 (defvar org-match-substring-regexp)
4717 (defvar org-match-substring-with-braces-regexp)
4719 ;; This should be with the exporter code, but we also use if for font-locking
4720 (defconst org-export-html-special-string-regexps
4721 '(("\\\\-" . "&shy;")
4722 ("---\\([^-]\\)" . "&mdash;\\1")
4723 ("--\\([^-]\\)" . "&ndash;\\1")
4724 ("\\.\\.\\." . "&hellip;"))
4725 "Regular expressions for special string conversion.")
4728 (defun org-compute-latex-and-specials-regexp ()
4729 "Compute regular expression for stuff treated specially by exporters."
4730 (if (not org-highlight-latex-fragments-and-specials)
4731 (org-set-local 'org-latex-and-specials-regexp nil)
4732 (require 'org-exp)
4733 (let*
4734 ((matchers (plist-get org-format-latex-options :matchers))
4735 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4736 org-latex-regexps)))
4737 (options (org-combine-plists (org-default-export-plist)
4738 (org-infile-export-plist)))
4739 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4740 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4741 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4742 (org-export-html-expand (plist-get options :expand-quoted-html))
4743 (org-export-with-special-strings (plist-get options :special-strings))
4744 (re-sub
4745 (cond
4746 ((equal org-export-with-sub-superscripts '{})
4747 (list org-match-substring-with-braces-regexp))
4748 (org-export-with-sub-superscripts
4749 (list org-match-substring-regexp))
4750 (t nil)))
4751 (re-latex
4752 (if org-export-with-LaTeX-fragments
4753 (mapcar (lambda (x) (nth 1 x)) latexs)))
4754 (re-macros
4755 (if org-export-with-TeX-macros
4756 (list (concat "\\\\"
4757 (regexp-opt
4758 (append (mapcar 'car org-html-entities)
4759 (if (boundp 'org-latex-entities)
4760 (mapcar (lambda (x)
4761 (or (car-safe x) x))
4762 org-latex-entities)
4763 nil))
4764 'words))) ; FIXME
4766 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4767 (re-special (if org-export-with-special-strings
4768 (mapcar (lambda (x) (car x))
4769 org-export-html-special-string-regexps)))
4770 (re-rest
4771 (delq nil
4772 (list
4773 (if org-export-html-expand "@<[^>\n]+>")
4774 ))))
4775 (org-set-local
4776 'org-latex-and-specials-regexp
4777 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4778 re-rest) "\\|")))))
4780 (defun org-do-latex-and-special-faces (limit)
4781 "Run through the buffer and add overlays to links."
4782 (when org-latex-and-specials-regexp
4783 (let (rtn d)
4784 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4785 limit t))
4786 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4787 'face))
4788 '(org-code org-verbatim underline)))
4789 (progn
4790 (setq rtn t
4791 d (cond ((member (char-after (1+ (match-beginning 0)))
4792 '(?_ ?^)) 1)
4793 (t 0)))
4794 (font-lock-prepend-text-property
4795 (+ d (match-beginning 0)) (match-end 0)
4796 'face 'org-latex-and-export-specials)
4797 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4798 '(font-lock-multiline t)))))
4799 rtn)))
4801 (defun org-restart-font-lock ()
4802 "Restart font-lock-mode, to force refontification."
4803 (when (and (boundp 'font-lock-mode) font-lock-mode)
4804 (font-lock-mode -1)
4805 (font-lock-mode 1)))
4807 (defun org-all-targets (&optional radio)
4808 "Return a list of all targets in this file.
4809 With optional argument RADIO, only find radio targets."
4810 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4811 rtn)
4812 (save-excursion
4813 (goto-char (point-min))
4814 (while (re-search-forward re nil t)
4815 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4816 rtn)))
4818 (defun org-make-target-link-regexp (targets)
4819 "Make regular expression matching all strings in TARGETS.
4820 The regular expression finds the targets also if there is a line break
4821 between words."
4822 (and targets
4823 (concat
4824 "\\<\\("
4825 (mapconcat
4826 (lambda (x)
4827 (while (string-match " +" x)
4828 (setq x (replace-match "\\s-+" t t x)))
4830 targets
4831 "\\|")
4832 "\\)\\>")))
4834 (defun org-activate-tags (limit)
4835 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4836 (progn
4837 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4838 (add-text-properties (match-beginning 1) (match-end 1)
4839 (list 'mouse-face 'highlight
4840 'keymap org-mouse-map))
4841 (org-rear-nonsticky-at (match-end 1))
4842 t)))
4844 (defun org-outline-level ()
4845 "Compute the outline level of the heading at point.
4846 This function assumes that the cursor is at the beginning of a line matched
4847 by outline-regexp. Otherwise it returns garbage.
4848 If this is called at a normal headline, the level is the number of stars.
4849 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4850 For plain list items, if they are matched by `outline-regexp', this returns
4851 1000 plus the line indentation."
4852 (save-excursion
4853 (looking-at outline-regexp)
4854 (if (match-beginning 1)
4855 (+ (org-get-string-indentation (match-string 1)) 1000)
4856 (1- (- (match-end 0) (match-beginning 0))))))
4858 (defvar org-font-lock-keywords nil)
4860 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4861 "Regular expression matching a property line.")
4863 (defvar org-font-lock-hook nil
4864 "Functions to be called for special font lock stuff.")
4866 (defun org-font-lock-hook (limit)
4867 (run-hook-with-args 'org-font-lock-hook limit))
4869 (defun org-set-font-lock-defaults ()
4870 (let* ((em org-fontify-emphasized-text)
4871 (lk org-activate-links)
4872 (org-font-lock-extra-keywords
4873 (list
4874 ;; Call the hook
4875 '(org-font-lock-hook)
4876 ;; Headlines
4877 `(,(if org-fontify-whole-heading-line
4878 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4879 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4880 (1 (org-get-level-face 1))
4881 (2 (org-get-level-face 2))
4882 (3 (org-get-level-face 3)))
4883 ;; Table lines
4884 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4885 (1 'org-table t))
4886 ;; Table internals
4887 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4888 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4889 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4890 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4891 ;; Drawers
4892 (list org-drawer-regexp '(0 'org-special-keyword t))
4893 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4894 ;; Properties
4895 (list org-property-re
4896 '(1 'org-special-keyword t)
4897 '(3 'org-property-value t))
4898 ;; Links
4899 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4900 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4901 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4902 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4903 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4904 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4905 (if (memq 'footnote lk) '(org-activate-footnote-links
4906 (2 'org-footnote t)))
4907 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4908 '(org-hide-wide-columns (0 nil append))
4909 ;; TODO lines
4910 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4911 '(1 (org-get-todo-face 1) t))
4912 ;; DONE
4913 (if org-fontify-done-headline
4914 (list (concat "^[*]+ +\\<\\("
4915 (mapconcat 'regexp-quote org-done-keywords "\\|")
4916 "\\)\\(.*\\)")
4917 '(2 'org-headline-done t))
4918 nil)
4919 ;; Priorities
4920 '(org-font-lock-add-priority-faces)
4921 ;; Tags
4922 '(org-font-lock-add-tag-faces)
4923 ;; Special keywords
4924 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4925 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4926 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4927 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4928 ;; Emphasis
4929 (if em
4930 (if (featurep 'xemacs)
4931 '(org-do-emphasis-faces (0 nil append))
4932 '(org-do-emphasis-faces)))
4933 ;; Checkboxes
4934 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4935 2 'org-checkbox prepend)
4936 (if org-provide-checkbox-statistics
4937 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4938 (0 (org-get-checkbox-statistics-face) t)))
4939 ;; Description list items
4940 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4941 2 'bold prepend)
4942 ;; ARCHIVEd headings
4943 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4944 '(1 'org-archived prepend))
4945 ;; Specials
4946 '(org-do-latex-and-special-faces)
4947 ;; Code
4948 '(org-activate-code (1 'org-code t))
4949 ;; COMMENT
4950 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4951 "\\|" org-quote-string "\\)\\>")
4952 '(1 'org-special-keyword t))
4953 '("^#.*" (0 'font-lock-comment-face t))
4954 ;; Blocks and meta lines
4955 '(org-fontify-meta-lines-and-blocks)
4957 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4958 ;; Now set the full font-lock-keywords
4959 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4960 (org-set-local 'font-lock-defaults
4961 '(org-font-lock-keywords t nil nil backward-paragraph))
4962 (kill-local-variable 'font-lock-keywords) nil))
4964 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4965 "Fontify string S like in Org-mode"
4966 (with-temp-buffer
4967 (insert s)
4968 (let ((org-odd-levels-only odd-levels))
4969 (org-mode)
4970 (font-lock-fontify-buffer)
4971 (buffer-string))))
4973 (defvar org-m nil)
4974 (defvar org-l nil)
4975 (defvar org-f nil)
4976 (defun org-get-level-face (n)
4977 "Get the right face for match N in font-lock matching of headlines."
4978 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4979 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4980 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4981 (cond
4982 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4983 ((eq n 2) org-f)
4984 (t (if org-level-color-stars-only nil org-f))))
4986 (defun org-get-todo-face (kwd)
4987 "Get the right face for a TODO keyword KWD.
4988 If KWD is a number, get the corresponding match group."
4989 (if (numberp kwd) (setq kwd (match-string kwd)))
4990 (or (cdr (assoc kwd org-todo-keyword-faces))
4991 (and (member kwd org-done-keywords) 'org-done)
4992 'org-todo))
4994 (defun org-font-lock-add-tag-faces (limit)
4995 "Add the special tag faces."
4996 (when (and org-tag-faces org-tags-special-faces-re)
4997 (while (re-search-forward org-tags-special-faces-re limit t)
4998 (add-text-properties (match-beginning 1) (match-end 1)
4999 (list 'face (org-get-tag-face 1)
5000 'font-lock-fontified t))
5001 (backward-char 1))))
5003 (defun org-font-lock-add-priority-faces (limit)
5004 "Add the special priority faces."
5005 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5006 (add-text-properties
5007 (match-beginning 0) (match-end 0)
5008 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
5009 org-priority-faces))
5010 'org-special-keyword)
5011 'font-lock-fontified t))))
5013 (defun org-get-tag-face (kwd)
5014 "Get the right face for a TODO keyword KWD.
5015 If KWD is a number, get the corresponding match group."
5016 (if (numberp kwd) (setq kwd (match-string kwd)))
5017 (or (cdr (assoc kwd org-tag-faces))
5018 'org-tag))
5020 (defun org-unfontify-region (beg end &optional maybe_loudly)
5021 "Remove fontification and activation overlays from links."
5022 (font-lock-default-unfontify-region beg end)
5023 (let* ((buffer-undo-list t)
5024 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5025 (inhibit-modification-hooks t)
5026 deactivate-mark buffer-file-name buffer-file-truename)
5027 (remove-text-properties
5028 beg end
5029 (if org-indent-mode
5030 ;; also remove line-prefix and wrap-prefix properties
5031 '(mouse-face t keymap t org-linked-text t
5032 invisible t intangible t
5033 line-prefix t wrap-prefix t
5034 org-no-flyspell t)
5035 '(mouse-face t keymap t org-linked-text t
5036 invisible t intangible t
5037 org-no-flyspell t)))))
5039 ;;;; Visibility cycling, including org-goto and indirect buffer
5041 ;;; Cycling
5043 (defvar org-cycle-global-status nil)
5044 (make-variable-buffer-local 'org-cycle-global-status)
5045 (defvar org-cycle-subtree-status nil)
5046 (make-variable-buffer-local 'org-cycle-subtree-status)
5048 ;;;###autoload
5050 (defvar org-inlinetask-min-level)
5052 (defun org-cycle (&optional arg)
5053 "TAB-action and visibility cycling for Org-mode.
5055 This is the command invoked in Org-mode by the TAB key. Its main purpose
5056 is outline visibility cycling, but it also invokes other actions
5057 in special contexts.
5059 - When this function is called with a prefix argument, rotate the entire
5060 buffer through 3 states (global cycling)
5061 1. OVERVIEW: Show only top-level headlines.
5062 2. CONTENTS: Show all headlines of all levels, but no body text.
5063 3. SHOW ALL: Show everything.
5064 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5065 determined by the variable `org-startup-folded', and by any VISIBILITY
5066 properties in the buffer.
5067 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5068 including any drawers.
5070 - When inside a table, re-align the table and move to the next field.
5072 - When point is at the beginning of a headline, rotate the subtree started
5073 by this line through 3 different states (local cycling)
5074 1. FOLDED: Only the main headline is shown.
5075 2. CHILDREN: The main headline and the direct children are shown.
5076 From this state, you can move to one of the children
5077 and zoom in further.
5078 3. SUBTREE: Show the entire subtree, including body text.
5079 If there is no subtree, switch directly from CHILDREN to FOLDED.
5081 - When there is a numeric prefix, go up to a heading with level ARG, do
5082 a `show-subtree' and return to the previous cursor position. If ARG
5083 is negative, go up that many levels.
5085 - When point is not at the beginning of a headline, execute the global
5086 binding for TAB, which is re-indenting the line. See the option
5087 `org-cycle-emulate-tab' for details.
5089 - Special case: if point is at the beginning of the buffer and there is
5090 no headline in line 1, this function will act as if called with prefix arg.
5091 But only if also the variable `org-cycle-global-at-bob' is t."
5092 (interactive "P")
5093 (org-load-modules-maybe)
5094 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5095 (and org-cycle-level-after-item/entry-creation
5096 (or (org-cycle-level)
5097 (org-cycle-item-indentation))))
5098 (let* ((limit-level
5099 (or org-cycle-max-level
5100 (and (boundp 'org-inlinetask-min-level)
5101 org-inlinetask-min-level
5102 (1- org-inlinetask-min-level))))
5103 (nstars (and limit-level
5104 (if org-odd-levels-only
5105 (and limit-level (1- (* limit-level 2)))
5106 limit-level)))
5107 (outline-regexp
5108 (cond
5109 ((not (org-mode-p)) outline-regexp)
5110 ((or (eq org-cycle-include-plain-lists 'integrate)
5111 (and org-cycle-include-plain-lists (org-at-item-p)))
5112 (concat "\\(?:\\*"
5113 (if nstars (format "\\{1,%d\\}" nstars) "+")
5114 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5115 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5116 (bob-special (and org-cycle-global-at-bob (bobp)
5117 (not (looking-at outline-regexp))))
5118 (org-cycle-hook
5119 (if bob-special
5120 (delq 'org-optimize-window-after-visibility-change
5121 (copy-sequence org-cycle-hook))
5122 org-cycle-hook))
5123 (pos (point)))
5125 (if (or bob-special (equal arg '(4)))
5126 ;; special case: use global cycling
5127 (setq arg t))
5129 (cond
5131 ((equal arg '(16))
5132 (org-set-startup-visibility)
5133 (message "Startup visibility, plus VISIBILITY properties"))
5135 ((equal arg '(64))
5136 (show-all)
5137 (message "Entire buffer visible, including drawers"))
5139 ((org-at-table-p 'any)
5140 ;; Enter the table or move to the next field in the table
5141 (or (org-table-recognize-table.el)
5142 (progn
5143 (if arg (org-table-edit-field t)
5144 (org-table-justify-field-maybe)
5145 (call-interactively 'org-table-next-field)))))
5147 ((run-hook-with-args-until-success
5148 'org-tab-after-check-for-table-hook))
5150 ((eq arg t) ;; Global cycling
5151 (org-cycle-internal-global))
5153 ((and org-drawers org-drawer-regexp
5154 (save-excursion
5155 (beginning-of-line 1)
5156 (looking-at org-drawer-regexp)))
5157 ;; Toggle block visibility
5158 (org-flag-drawer
5159 (not (get-char-property (match-end 0) 'invisible))))
5161 ((integerp arg)
5162 ;; Show-subtree, ARG levels up from here.
5163 (save-excursion
5164 (org-back-to-heading)
5165 (outline-up-heading (if (< arg 0) (- arg)
5166 (- (funcall outline-level) arg)))
5167 (org-show-subtree)))
5169 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5170 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5172 (org-cycle-internal-local))
5174 ;; TAB emulation and template completion
5175 (buffer-read-only (org-back-to-heading))
5177 ((run-hook-with-args-until-success
5178 'org-tab-after-check-for-cycling-hook))
5180 ((org-try-structure-completion))
5182 ((org-try-cdlatex-tab))
5184 ((run-hook-with-args-until-success
5185 'org-tab-before-tab-emulation-hook))
5187 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5188 (or (not (bolp))
5189 (not (looking-at outline-regexp))))
5190 (call-interactively (global-key-binding "\t")))
5192 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5193 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5194 (or (and (eq org-cycle-emulate-tab 'white)
5195 (= (match-end 0) (point-at-eol)))
5196 (and (eq org-cycle-emulate-tab 'whitestart)
5197 (>= (match-end 0) pos))))
5199 (eq org-cycle-emulate-tab t))
5200 (call-interactively (global-key-binding "\t")))
5202 (t (save-excursion
5203 (org-back-to-heading)
5204 (org-cycle)))))))
5206 (defun org-cycle-internal-global ()
5207 "Do the global cycling action."
5208 (cond
5209 ((and (eq last-command this-command)
5210 (eq org-cycle-global-status 'overview))
5211 ;; We just created the overview - now do table of contents
5212 ;; This can be slow in very large buffers, so indicate action
5213 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5214 (message "CONTENTS...")
5215 (org-content)
5216 (message "CONTENTS...done")
5217 (setq org-cycle-global-status 'contents)
5218 (run-hook-with-args 'org-cycle-hook 'contents))
5220 ((and (eq last-command this-command)
5221 (eq org-cycle-global-status 'contents))
5222 ;; We just showed the table of contents - now show everything
5223 (run-hook-with-args 'org-pre-cycle-hook 'all)
5224 (show-all)
5225 (message "SHOW ALL")
5226 (setq org-cycle-global-status 'all)
5227 (run-hook-with-args 'org-cycle-hook 'all))
5230 ;; Default action: go to overview
5231 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5232 (org-overview)
5233 (message "OVERVIEW")
5234 (setq org-cycle-global-status 'overview)
5235 (run-hook-with-args 'org-cycle-hook 'overview))))
5237 (defun org-cycle-internal-local ()
5238 "Do the local cycling action."
5239 (org-back-to-heading)
5240 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5241 ;; First, some boundaries
5242 (save-excursion
5243 (org-back-to-heading)
5244 (setq level (funcall outline-level))
5245 (save-excursion
5246 (beginning-of-line 2)
5247 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5248 ; XEmacs does not have `next-single-char-property-change'
5249 ; I'm not sure about Emacs 21.
5250 (while (and (not (eobp)) ;; this is like `next-line'
5251 (get-char-property (1- (point)) 'invisible))
5252 (beginning-of-line 2))
5253 (while (and (not (eobp)) ;; this is like `next-line'
5254 (get-char-property (1- (point)) 'invisible))
5255 (goto-char (next-single-char-property-change (point) 'invisible))
5256 ;;;??? (or (bolp) (beginning-of-line 2))))
5257 (and (eolp) (beginning-of-line 2))))
5258 (setq eol (point)))
5259 (outline-end-of-heading) (setq eoh (point))
5260 (save-excursion
5261 (outline-next-heading)
5262 (setq has-children (and (org-at-heading-p t)
5263 (> (funcall outline-level) level))))
5264 (org-end-of-subtree t)
5265 (unless (eobp)
5266 (skip-chars-forward " \t\n")
5267 (beginning-of-line 1) ; in case this is an item
5269 (setq eos (if (eobp) (point) (1- (point)))))
5270 ;; Find out what to do next and set `this-command'
5271 (cond
5272 ((= eos eoh)
5273 ;; Nothing is hidden behind this heading
5274 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5275 (message "EMPTY ENTRY")
5276 (setq org-cycle-subtree-status nil)
5277 (save-excursion
5278 (goto-char eos)
5279 (outline-next-heading)
5280 (if (org-invisible-p) (org-flag-heading nil))))
5281 ((and (or (>= eol eos)
5282 (not (string-match "\\S-" (buffer-substring eol eos))))
5283 (or has-children
5284 (not (setq children-skipped
5285 org-cycle-skip-children-state-if-no-children))))
5286 ;; Entire subtree is hidden in one line: children view
5287 (run-hook-with-args 'org-pre-cycle-hook 'children)
5288 (org-show-entry)
5289 (show-children)
5290 (message "CHILDREN")
5291 (save-excursion
5292 (goto-char eos)
5293 (outline-next-heading)
5294 (if (org-invisible-p) (org-flag-heading nil)))
5295 (setq org-cycle-subtree-status 'children)
5296 (run-hook-with-args 'org-cycle-hook 'children))
5297 ((or children-skipped
5298 (and (eq last-command this-command)
5299 (eq org-cycle-subtree-status 'children)))
5300 ;; We just showed the children, or no children are there,
5301 ;; now show everything.
5302 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5303 (org-show-subtree)
5304 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5305 (setq org-cycle-subtree-status 'subtree)
5306 (run-hook-with-args 'org-cycle-hook 'subtree))
5308 ;; Default action: hide the subtree.
5309 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5310 (hide-subtree)
5311 (message "FOLDED")
5312 (setq org-cycle-subtree-status 'folded)
5313 (run-hook-with-args 'org-cycle-hook 'folded)))))
5315 ;;;###autoload
5316 (defun org-global-cycle (&optional arg)
5317 "Cycle the global visibility. For details see `org-cycle'.
5318 With C-u prefix arg, switch to startup visibility.
5319 With a numeric prefix, show all headlines up to that level."
5320 (interactive "P")
5321 (let ((org-cycle-include-plain-lists
5322 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5323 (cond
5324 ((integerp arg)
5325 (show-all)
5326 (hide-sublevels arg)
5327 (setq org-cycle-global-status 'contents))
5328 ((equal arg '(4))
5329 (org-set-startup-visibility)
5330 (message "Startup visibility, plus VISIBILITY properties."))
5332 (org-cycle '(4))))))
5334 (defun org-set-startup-visibility ()
5335 "Set the visibility required by startup options and properties."
5336 (cond
5337 ((eq org-startup-folded t)
5338 (org-cycle '(4)))
5339 ((eq org-startup-folded 'content)
5340 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5341 (org-cycle '(4)) (org-cycle '(4)))))
5342 (unless (eq org-startup-folded 'showeverything)
5343 (if org-hide-block-startup (org-hide-block-all))
5344 (org-set-visibility-according-to-property 'no-cleanup)
5345 (org-cycle-hide-archived-subtrees 'all)
5346 (org-cycle-hide-drawers 'all)
5347 (org-cycle-show-empty-lines 'all)))
5349 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5350 "Switch subtree visibilities according to :VISIBILITY: property."
5351 (interactive)
5352 (let (org-show-entry-below state)
5353 (save-excursion
5354 (goto-char (point-min))
5355 (while (re-search-forward
5356 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5357 nil t)
5358 (setq state (match-string 1))
5359 (save-excursion
5360 (org-back-to-heading t)
5361 (hide-subtree)
5362 (org-reveal)
5363 (cond
5364 ((equal state '("fold" "folded"))
5365 (hide-subtree))
5366 ((equal state "children")
5367 (org-show-hidden-entry)
5368 (show-children))
5369 ((equal state "content")
5370 (save-excursion
5371 (save-restriction
5372 (org-narrow-to-subtree)
5373 (org-content))))
5374 ((member state '("all" "showall"))
5375 (show-subtree)))))
5376 (unless no-cleanup
5377 (org-cycle-hide-archived-subtrees 'all)
5378 (org-cycle-hide-drawers 'all)
5379 (org-cycle-show-empty-lines 'all)))))
5381 (defun org-overview ()
5382 "Switch to overview mode, showing only top-level headlines.
5383 Really, this shows all headlines with level equal or greater than the level
5384 of the first headline in the buffer. This is important, because if the
5385 first headline is not level one, then (hide-sublevels 1) gives confusing
5386 results."
5387 (interactive)
5388 (let ((level (save-excursion
5389 (goto-char (point-min))
5390 (if (re-search-forward (concat "^" outline-regexp) nil t)
5391 (progn
5392 (goto-char (match-beginning 0))
5393 (funcall outline-level))))))
5394 (and level (hide-sublevels level))))
5396 (defun org-content (&optional arg)
5397 "Show all headlines in the buffer, like a table of contents.
5398 With numerical argument N, show content up to level N."
5399 (interactive "P")
5400 (save-excursion
5401 ;; Visit all headings and show their offspring
5402 (and (integerp arg) (org-overview))
5403 (goto-char (point-max))
5404 (catch 'exit
5405 (while (and (progn (condition-case nil
5406 (outline-previous-visible-heading 1)
5407 (error (goto-char (point-min))))
5409 (looking-at outline-regexp))
5410 (if (integerp arg)
5411 (show-children (1- arg))
5412 (show-branches))
5413 (if (bobp) (throw 'exit nil))))))
5416 (defun org-optimize-window-after-visibility-change (state)
5417 "Adjust the window after a change in outline visibility.
5418 This function is the default value of the hook `org-cycle-hook'."
5419 (when (get-buffer-window (current-buffer))
5420 (cond
5421 ((eq state 'content) nil)
5422 ((eq state 'all) nil)
5423 ((eq state 'folded) nil)
5424 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5425 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5427 (defun org-remove-empty-overlays-at (pos)
5428 "Remove outline overlays that do not contain non-white stuff."
5429 (mapc
5430 (lambda (o)
5431 (and (eq 'outline (org-overlay-get o 'invisible))
5432 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5433 (org-overlay-end o))))
5434 (org-delete-overlay o)))
5435 (org-overlays-at pos)))
5437 (defun org-clean-visibility-after-subtree-move ()
5438 "Fix visibility issues after moving a subtree."
5439 ;; First, find a reasonable region to look at:
5440 ;; Start two siblings above, end three below
5441 (let* ((beg (save-excursion
5442 (and (org-get-last-sibling)
5443 (org-get-last-sibling))
5444 (point)))
5445 (end (save-excursion
5446 (and (org-get-next-sibling)
5447 (org-get-next-sibling)
5448 (org-get-next-sibling))
5449 (if (org-at-heading-p)
5450 (point-at-eol)
5451 (point))))
5452 (level (looking-at "\\*+"))
5453 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5454 (save-excursion
5455 (save-restriction
5456 (narrow-to-region beg end)
5457 (when re
5458 ;; Properly fold already folded siblings
5459 (goto-char (point-min))
5460 (while (re-search-forward re nil t)
5461 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5462 (hide-entry))))
5463 (org-cycle-show-empty-lines 'overview)
5464 (org-cycle-hide-drawers 'overview)))))
5466 (defun org-cycle-show-empty-lines (state)
5467 "Show empty lines above all visible headlines.
5468 The region to be covered depends on STATE when called through
5469 `org-cycle-hook'. Lisp program can use t for STATE to get the
5470 entire buffer covered. Note that an empty line is only shown if there
5471 are at least `org-cycle-separator-lines' empty lines before the headline."
5472 (when (not (= org-cycle-separator-lines 0))
5473 (save-excursion
5474 (let* ((n (abs org-cycle-separator-lines))
5475 (re (cond
5476 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5477 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5478 (t (let ((ns (number-to-string (- n 2))))
5479 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5480 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5481 beg end b e)
5482 (cond
5483 ((memq state '(overview contents t))
5484 (setq beg (point-min) end (point-max)))
5485 ((memq state '(children folded))
5486 (setq beg (point) end (progn (org-end-of-subtree t t)
5487 (beginning-of-line 2)
5488 (point)))))
5489 (when beg
5490 (goto-char beg)
5491 (while (re-search-forward re end t)
5492 (unless (get-char-property (match-end 1) 'invisible)
5493 (setq e (match-end 1))
5494 (if (< org-cycle-separator-lines 0)
5495 (setq b (save-excursion
5496 (goto-char (match-beginning 0))
5497 (org-back-over-empty-lines)
5498 (if (save-excursion
5499 (goto-char (max (point-min) (1- (point))))
5500 (org-on-heading-p))
5501 (1- (point))
5502 (point))))
5503 (setq b (match-beginning 1)))
5504 (outline-flag-region b e nil)))))))
5505 ;; Never hide empty lines at the end of the file.
5506 (save-excursion
5507 (goto-char (point-max))
5508 (outline-previous-heading)
5509 (outline-end-of-heading)
5510 (if (and (looking-at "[ \t\n]+")
5511 (= (match-end 0) (point-max)))
5512 (outline-flag-region (point) (match-end 0) nil))))
5514 (defun org-show-empty-lines-in-parent ()
5515 "Move to the parent and re-show empty lines before visible headlines."
5516 (save-excursion
5517 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5518 (org-cycle-show-empty-lines context))))
5520 (defun org-files-list ()
5521 "Return `org-agenda-files' list, plus all open org-mode files.
5522 This is useful for operations that need to scan all of a user's
5523 open and agenda-wise Org files."
5524 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5525 (dolist (buf (buffer-list))
5526 (with-current-buffer buf
5527 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5528 (let ((file (expand-file-name (buffer-file-name))))
5529 (unless (member file files)
5530 (push file files))))))
5531 files))
5533 (defsubst org-entry-beginning-position ()
5534 "Return the beginning position of the current entry."
5535 (save-excursion (outline-back-to-heading t) (point)))
5537 (defsubst org-entry-end-position ()
5538 "Return the end position of the current entry."
5539 (save-excursion (outline-next-heading) (point)))
5541 (defun org-cycle-hide-drawers (state)
5542 "Re-hide all drawers after a visibility state change."
5543 (when (and (org-mode-p)
5544 (not (memq state '(overview folded contents))))
5545 (save-excursion
5546 (let* ((globalp (memq state '(contents all)))
5547 (beg (if globalp (point-min) (point)))
5548 (end (if globalp (point-max)
5549 (if (eq state 'children)
5550 (save-excursion (outline-next-heading) (point))
5551 (org-end-of-subtree t)))))
5552 (goto-char beg)
5553 (while (re-search-forward org-drawer-regexp end t)
5554 (org-flag-drawer t))))))
5556 (defun org-flag-drawer (flag)
5557 (save-excursion
5558 (beginning-of-line 1)
5559 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5560 (let ((b (match-end 0))
5561 (outline-regexp org-outline-regexp))
5562 (if (re-search-forward
5563 "^[ \t]*:END:"
5564 (save-excursion (outline-next-heading) (point)) t)
5565 (outline-flag-region b (point-at-eol) flag)
5566 (error ":END: line missing at position %s" b))))))
5568 (defun org-subtree-end-visible-p ()
5569 "Is the end of the current subtree visible?"
5570 (pos-visible-in-window-p
5571 (save-excursion (org-end-of-subtree t) (point))))
5573 (defun org-first-headline-recenter (&optional N)
5574 "Move cursor to the first headline and recenter the headline.
5575 Optional argument N means, put the headline into the Nth line of the window."
5576 (goto-char (point-min))
5577 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5578 (beginning-of-line)
5579 (recenter (prefix-numeric-value N))))
5581 ;;; Folding of blocks
5583 (defconst org-block-regexp
5585 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5586 "Regular expression for hiding blocks.")
5588 (defvar org-hide-block-overlays nil
5589 "Overlays hiding blocks.")
5590 (make-variable-buffer-local 'org-hide-block-overlays)
5592 (defun org-block-map (function &optional start end)
5593 "Call func at the head of all source blocks in the current
5594 buffer. Optional arguments START and END can be used to limit
5595 the range."
5596 (let ((start (or start (point-min)))
5597 (end (or end (point-max))))
5598 (save-excursion
5599 (goto-char start)
5600 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5601 (save-excursion
5602 (save-match-data
5603 (goto-char (match-beginning 0))
5604 (funcall function)))))))
5606 (defun org-hide-block-toggle-all ()
5607 "Toggle the visibility of all blocks in the current buffer."
5608 (org-block-map #'org-hide-block-toggle))
5610 (defun org-hide-block-all ()
5611 "Fold all blocks in the current buffer."
5612 (interactive)
5613 (org-show-block-all)
5614 (org-block-map #'org-hide-block-toggle-maybe))
5616 (defun org-show-block-all ()
5617 "Unfold all blocks in the current buffer."
5618 (mapc 'org-delete-overlay org-hide-block-overlays)
5619 (setq org-hide-block-overlays nil))
5621 (defun org-hide-block-toggle-maybe ()
5622 "Toggle visibility of block at point."
5623 (interactive)
5624 (let ((case-fold-search t))
5625 (if (save-excursion
5626 (beginning-of-line 1)
5627 (looking-at org-block-regexp))
5628 (progn (org-hide-block-toggle)
5629 t) ;; to signal that we took action
5630 nil))) ;; to signal that we did not
5632 (defun org-hide-block-toggle (&optional force)
5633 "Toggle the visibility of the current block."
5634 (interactive)
5635 (save-excursion
5636 (beginning-of-line)
5637 (if (re-search-forward org-block-regexp nil t)
5638 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5639 (end (match-end 0)) ;; end of entire body
5641 (if (memq t (mapcar (lambda (overlay)
5642 (eq (org-overlay-get overlay 'invisible)
5643 'org-hide-block))
5644 (org-overlays-at start)))
5645 (if (or (not force) (eq force 'off))
5646 (mapc (lambda (ov)
5647 (when (member ov org-hide-block-overlays)
5648 (setq org-hide-block-overlays
5649 (delq ov org-hide-block-overlays)))
5650 (when (eq (org-overlay-get ov 'invisible)
5651 'org-hide-block)
5652 (org-delete-overlay ov)))
5653 (org-overlays-at start)))
5654 (setq ov (org-make-overlay start end))
5655 (org-overlay-put ov 'invisible 'org-hide-block)
5656 ;; make the block accessible to isearch
5657 (org-overlay-put
5658 ov 'isearch-open-invisible
5659 (lambda (ov)
5660 (when (member ov org-hide-block-overlays)
5661 (setq org-hide-block-overlays
5662 (delq ov org-hide-block-overlays)))
5663 (when (eq (org-overlay-get ov 'invisible)
5664 'org-hide-block)
5665 (org-delete-overlay ov))))
5666 (push ov org-hide-block-overlays)))
5667 (error "Not looking at a source block"))))
5669 ;; org-tab-after-check-for-cycling-hook
5670 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5671 ;; Remove overlays when changing major mode
5672 (add-hook 'org-mode-hook
5673 (lambda () (org-add-hook 'change-major-mode-hook
5674 'org-show-block-all 'append 'local)))
5676 ;;; Org-goto
5678 (defvar org-goto-window-configuration nil)
5679 (defvar org-goto-marker nil)
5680 (defvar org-goto-map
5681 (let ((map (make-sparse-keymap)))
5682 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5683 (while (setq cmd (pop cmds))
5684 (substitute-key-definition cmd cmd map global-map)))
5685 (suppress-keymap map)
5686 (org-defkey map "\C-m" 'org-goto-ret)
5687 (org-defkey map [(return)] 'org-goto-ret)
5688 (org-defkey map [(left)] 'org-goto-left)
5689 (org-defkey map [(right)] 'org-goto-right)
5690 (org-defkey map [(control ?g)] 'org-goto-quit)
5691 (org-defkey map "\C-i" 'org-cycle)
5692 (org-defkey map [(tab)] 'org-cycle)
5693 (org-defkey map [(down)] 'outline-next-visible-heading)
5694 (org-defkey map [(up)] 'outline-previous-visible-heading)
5695 (if org-goto-auto-isearch
5696 (if (fboundp 'define-key-after)
5697 (define-key-after map [t] 'org-goto-local-auto-isearch)
5698 nil)
5699 (org-defkey map "q" 'org-goto-quit)
5700 (org-defkey map "n" 'outline-next-visible-heading)
5701 (org-defkey map "p" 'outline-previous-visible-heading)
5702 (org-defkey map "f" 'outline-forward-same-level)
5703 (org-defkey map "b" 'outline-backward-same-level)
5704 (org-defkey map "u" 'outline-up-heading))
5705 (org-defkey map "/" 'org-occur)
5706 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5707 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5708 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5709 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5710 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5711 map))
5713 (defconst org-goto-help
5714 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5715 RET=jump to location [Q]uit and return to previous location
5716 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5718 (defvar org-goto-start-pos) ; dynamically scoped parameter
5720 ;; FIXME: Docstring does not mention both interfaces
5721 (defun org-goto (&optional alternative-interface)
5722 "Look up a different location in the current file, keeping current visibility.
5724 When you want look-up or go to a different location in a document, the
5725 fastest way is often to fold the entire buffer and then dive into the tree.
5726 This method has the disadvantage, that the previous location will be folded,
5727 which may not be what you want.
5729 This command works around this by showing a copy of the current buffer
5730 in an indirect buffer, in overview mode. You can dive into the tree in
5731 that copy, use org-occur and incremental search to find a location.
5732 When pressing RET or `Q', the command returns to the original buffer in
5733 which the visibility is still unchanged. After RET is will also jump to
5734 the location selected in the indirect buffer and expose the
5735 the headline hierarchy above."
5736 (interactive "P")
5737 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5738 (org-refile-use-outline-path t)
5739 (org-refile-target-verify-function nil)
5740 (interface
5741 (if (not alternative-interface)
5742 org-goto-interface
5743 (if (eq org-goto-interface 'outline)
5744 'outline-path-completion
5745 'outline)))
5746 (org-goto-start-pos (point))
5747 (selected-point
5748 (if (eq interface 'outline)
5749 (car (org-get-location (current-buffer) org-goto-help))
5750 (nth 3 (org-refile-get-location "Goto: ")))))
5751 (if selected-point
5752 (progn
5753 (org-mark-ring-push org-goto-start-pos)
5754 (goto-char selected-point)
5755 (if (or (org-invisible-p) (org-invisible-p2))
5756 (org-show-context 'org-goto)))
5757 (message "Quit"))))
5759 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5760 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5761 (defvar org-goto-local-auto-isearch-map) ; defined below
5763 (defun org-get-location (buf help)
5764 "Let the user select a location in the Org-mode buffer BUF.
5765 This function uses a recursive edit. It returns the selected position
5766 or nil."
5767 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5768 (isearch-hide-immediately nil)
5769 (isearch-search-fun-function
5770 (lambda () 'org-goto-local-search-headings))
5771 (org-goto-selected-point org-goto-exit-command))
5772 (save-excursion
5773 (save-window-excursion
5774 (delete-other-windows)
5775 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5776 (switch-to-buffer
5777 (condition-case nil
5778 (make-indirect-buffer (current-buffer) "*org-goto*")
5779 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5780 (with-output-to-temp-buffer "*Help*"
5781 (princ help))
5782 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5783 (setq buffer-read-only nil)
5784 (let ((org-startup-truncated t)
5785 (org-startup-folded nil)
5786 (org-startup-align-all-tables nil))
5787 (org-mode)
5788 (org-overview))
5789 (setq buffer-read-only t)
5790 (if (and (boundp 'org-goto-start-pos)
5791 (integer-or-marker-p org-goto-start-pos))
5792 (let ((org-show-hierarchy-above t)
5793 (org-show-siblings t)
5794 (org-show-following-heading t))
5795 (goto-char org-goto-start-pos)
5796 (and (org-invisible-p) (org-show-context)))
5797 (goto-char (point-min)))
5798 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5799 (message "Select location and press RET")
5800 (use-local-map org-goto-map)
5801 (recursive-edit)
5803 (kill-buffer "*org-goto*")
5804 (cons org-goto-selected-point org-goto-exit-command)))
5806 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5807 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5808 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5809 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5811 (defun org-goto-local-search-headings (string bound noerror)
5812 "Search and make sure that any matches are in headlines."
5813 (catch 'return
5814 (while (if isearch-forward
5815 (search-forward string bound noerror)
5816 (search-backward string bound noerror))
5817 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5818 (and (member :headline context)
5819 (not (member :tags context))))
5820 (throw 'return (point))))))
5822 (defun org-goto-local-auto-isearch ()
5823 "Start isearch."
5824 (interactive)
5825 (goto-char (point-min))
5826 (let ((keys (this-command-keys)))
5827 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5828 (isearch-mode t)
5829 (isearch-process-search-char (string-to-char keys)))))
5831 (defun org-goto-ret (&optional arg)
5832 "Finish `org-goto' by going to the new location."
5833 (interactive "P")
5834 (setq org-goto-selected-point (point)
5835 org-goto-exit-command 'return)
5836 (throw 'exit nil))
5838 (defun org-goto-left ()
5839 "Finish `org-goto' by going to the new location."
5840 (interactive)
5841 (if (org-on-heading-p)
5842 (progn
5843 (beginning-of-line 1)
5844 (setq org-goto-selected-point (point)
5845 org-goto-exit-command 'left)
5846 (throw 'exit nil))
5847 (error "Not on a heading")))
5849 (defun org-goto-right ()
5850 "Finish `org-goto' by going to the new location."
5851 (interactive)
5852 (if (org-on-heading-p)
5853 (progn
5854 (setq org-goto-selected-point (point)
5855 org-goto-exit-command 'right)
5856 (throw 'exit nil))
5857 (error "Not on a heading")))
5859 (defun org-goto-quit ()
5860 "Finish `org-goto' without cursor motion."
5861 (interactive)
5862 (setq org-goto-selected-point nil)
5863 (setq org-goto-exit-command 'quit)
5864 (throw 'exit nil))
5866 ;;; Indirect buffer display of subtrees
5868 (defvar org-indirect-dedicated-frame nil
5869 "This is the frame being used for indirect tree display.")
5870 (defvar org-last-indirect-buffer nil)
5872 (defun org-tree-to-indirect-buffer (&optional arg)
5873 "Create indirect buffer and narrow it to current subtree.
5874 With numerical prefix ARG, go up to this level and then take that tree.
5875 If ARG is negative, go up that many levels.
5876 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5877 indirect buffer previously made with this command, to avoid proliferation of
5878 indirect buffers. However, when you call the command with a `C-u' prefix, or
5879 when `org-indirect-buffer-display' is `new-frame', the last buffer
5880 is kept so that you can work with several indirect buffers at the same time.
5881 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5882 requests that a new frame be made for the new buffer, so that the dedicated
5883 frame is not changed."
5884 (interactive "P")
5885 (let ((cbuf (current-buffer))
5886 (cwin (selected-window))
5887 (pos (point))
5888 beg end level heading ibuf)
5889 (save-excursion
5890 (org-back-to-heading t)
5891 (when (numberp arg)
5892 (setq level (org-outline-level))
5893 (if (< arg 0) (setq arg (+ level arg)))
5894 (while (> (setq level (org-outline-level)) arg)
5895 (outline-up-heading 1 t)))
5896 (setq beg (point)
5897 heading (org-get-heading))
5898 (org-end-of-subtree t t) (setq end (point)))
5899 (if (and (buffer-live-p org-last-indirect-buffer)
5900 (not (eq org-indirect-buffer-display 'new-frame))
5901 (not arg))
5902 (kill-buffer org-last-indirect-buffer))
5903 (setq ibuf (org-get-indirect-buffer cbuf)
5904 org-last-indirect-buffer ibuf)
5905 (cond
5906 ((or (eq org-indirect-buffer-display 'new-frame)
5907 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5908 (select-frame (make-frame))
5909 (delete-other-windows)
5910 (switch-to-buffer ibuf)
5911 (org-set-frame-title heading))
5912 ((eq org-indirect-buffer-display 'dedicated-frame)
5913 (raise-frame
5914 (select-frame (or (and org-indirect-dedicated-frame
5915 (frame-live-p org-indirect-dedicated-frame)
5916 org-indirect-dedicated-frame)
5917 (setq org-indirect-dedicated-frame (make-frame)))))
5918 (delete-other-windows)
5919 (switch-to-buffer ibuf)
5920 (org-set-frame-title (concat "Indirect: " heading)))
5921 ((eq org-indirect-buffer-display 'current-window)
5922 (switch-to-buffer ibuf))
5923 ((eq org-indirect-buffer-display 'other-window)
5924 (pop-to-buffer ibuf))
5925 (t (error "Invalid value")))
5926 (if (featurep 'xemacs)
5927 (save-excursion (org-mode) (turn-on-font-lock)))
5928 (narrow-to-region beg end)
5929 (show-all)
5930 (goto-char pos)
5931 (and (window-live-p cwin) (select-window cwin))))
5933 (defun org-get-indirect-buffer (&optional buffer)
5934 (setq buffer (or buffer (current-buffer)))
5935 (let ((n 1) (base (buffer-name buffer)) bname)
5936 (while (buffer-live-p
5937 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5938 (setq n (1+ n)))
5939 (condition-case nil
5940 (make-indirect-buffer buffer bname 'clone)
5941 (error (make-indirect-buffer buffer bname)))))
5943 (defun org-set-frame-title (title)
5944 "Set the title of the current frame to the string TITLE."
5945 ;; FIXME: how to name a single frame in XEmacs???
5946 (unless (featurep 'xemacs)
5947 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5949 ;;;; Structure editing
5951 ;;; Inserting headlines
5953 (defun org-previous-line-empty-p ()
5954 (save-excursion
5955 (and (not (bobp))
5956 (or (beginning-of-line 0) t)
5957 (save-match-data
5958 (looking-at "[ \t]*$")))))
5960 (defun org-insert-heading (&optional force-heading)
5961 "Insert a new heading or item with same depth at point.
5962 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5963 If point is at the beginning of a headline, insert a sibling before the
5964 current headline. If point is not at the beginning, do not split the line,
5965 but create the new headline after the current line."
5966 (interactive "P")
5967 (if (= (buffer-size) 0)
5968 (insert "\n* ")
5969 (when (or force-heading (not (org-insert-item)))
5970 (let* ((empty-line-p nil)
5971 (head (save-excursion
5972 (condition-case nil
5973 (progn
5974 (org-back-to-heading)
5975 (setq empty-line-p (org-previous-line-empty-p))
5976 (match-string 0))
5977 (error "*"))))
5978 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5979 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5980 pos hide-previous previous-pos)
5981 (cond
5982 ((and (org-on-heading-p) (bolp)
5983 (or (bobp)
5984 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5985 ;; insert before the current line
5986 (open-line (if blank 2 1)))
5987 ((and (bolp)
5988 (not org-insert-heading-respect-content)
5989 (or (bobp)
5990 (save-excursion
5991 (backward-char 1) (not (org-invisible-p)))))
5992 ;; insert right here
5993 nil)
5995 ;; somewhere in the line
5996 (save-excursion
5997 (setq previous-pos (point-at-bol))
5998 (end-of-line)
5999 (setq hide-previous (org-invisible-p)))
6000 (and org-insert-heading-respect-content (org-show-subtree))
6001 (let ((split
6002 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6003 (save-excursion
6004 (let ((p (point)))
6005 (goto-char (point-at-bol))
6006 (and (looking-at org-complex-heading-regexp)
6007 (> p (match-beginning 4)))))))
6008 tags pos)
6009 (cond
6010 (org-insert-heading-respect-content
6011 (org-end-of-subtree nil t)
6012 (or (bolp) (newline))
6013 (or (org-previous-line-empty-p)
6014 (and blank (newline)))
6015 (open-line 1))
6016 ((org-on-heading-p)
6017 (when hide-previous
6018 (show-children)
6019 (org-show-entry))
6020 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6021 (setq tags (and (match-end 2) (match-string 2)))
6022 (and (match-end 1)
6023 (delete-region (match-beginning 1) (match-end 1)))
6024 (setq pos (point-at-bol))
6025 (or split (end-of-line 1))
6026 (delete-horizontal-space)
6027 (newline (if blank 2 1))
6028 (when tags
6029 (save-excursion
6030 (goto-char pos)
6031 (end-of-line 1)
6032 (insert " " tags)
6033 (org-set-tags nil 'align))))
6035 (or split (end-of-line 1))
6036 (newline (if blank 2 1)))))))
6037 (insert head) (just-one-space)
6038 (setq pos (point))
6039 (end-of-line 1)
6040 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6041 (when (and org-insert-heading-respect-content hide-previous)
6042 (save-excursion
6043 (goto-char previous-pos)
6044 (hide-subtree)))
6045 (run-hooks 'org-insert-heading-hook)))))
6047 (defun org-get-heading (&optional no-tags)
6048 "Return the heading of the current entry, without the stars."
6049 (save-excursion
6050 (org-back-to-heading t)
6051 (if (looking-at
6052 (if no-tags
6053 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6054 "\\*+[ \t]+\\([^\r\n]*\\)"))
6055 (match-string 1) "")))
6057 (defun org-heading-components ()
6058 "Return the components of the current heading.
6059 This is a list with the following elements:
6060 - the level as an integer
6061 - the reduced level, different if `org-odd-levels-only' is set.
6062 - the TODO keyword, or nil
6063 - the priority character, like ?A, or nil if no priority is given
6064 - the headline text itself, or the tags string if no headline text
6065 - the tags string, or nil."
6066 (save-excursion
6067 (org-back-to-heading t)
6068 (if (looking-at org-complex-heading-regexp)
6069 (list (length (match-string 1))
6070 (org-reduced-level (length (match-string 1)))
6071 (org-match-string-no-properties 2)
6072 (and (match-end 3) (aref (match-string 3) 2))
6073 (org-match-string-no-properties 4)
6074 (org-match-string-no-properties 5)))))
6076 (defun org-get-entry ()
6077 "Get the entry text, after heading, entire subtree."
6078 (save-excursion
6079 (org-back-to-heading t)
6080 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6082 (defun org-insert-heading-after-current ()
6083 "Insert a new heading with same level as current, after current subtree."
6084 (interactive)
6085 (org-back-to-heading)
6086 (org-insert-heading)
6087 (org-move-subtree-down)
6088 (end-of-line 1))
6090 (defun org-insert-heading-respect-content ()
6091 (interactive)
6092 (let ((org-insert-heading-respect-content t))
6093 (org-insert-heading t)))
6095 (defun org-insert-todo-heading-respect-content (&optional force-state)
6096 (interactive "P")
6097 (let ((org-insert-heading-respect-content t))
6098 (org-insert-todo-heading force-state t)))
6100 (defun org-insert-todo-heading (arg &optional force-heading)
6101 "Insert a new heading with the same level and TODO state as current heading.
6102 If the heading has no TODO state, or if the state is DONE, use the first
6103 state (TODO by default). Also with prefix arg, force first state."
6104 (interactive "P")
6105 (when (or force-heading (not (org-insert-item 'checkbox)))
6106 (org-insert-heading force-heading)
6107 (save-excursion
6108 (org-back-to-heading)
6109 (outline-previous-heading)
6110 (looking-at org-todo-line-regexp))
6111 (let*
6112 ((new-mark-x
6113 (if (or arg
6114 (not (match-beginning 2))
6115 (member (match-string 2) org-done-keywords))
6116 (car org-todo-keywords-1)
6117 (match-string 2)))
6118 (new-mark
6120 (run-hook-with-args-until-success
6121 'org-todo-get-default-hook new-mark-x nil)
6122 new-mark-x)))
6123 (beginning-of-line 1)
6124 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6125 (if org-treat-insert-todo-heading-as-state-change
6126 (org-todo new-mark)
6127 (insert new-mark " "))))
6128 (when org-provide-todo-statistics
6129 (org-update-parent-todo-statistics))))
6131 (defun org-insert-subheading (arg)
6132 "Insert a new subheading and demote it.
6133 Works for outline headings and for plain lists alike."
6134 (interactive "P")
6135 (org-insert-heading arg)
6136 (cond
6137 ((org-on-heading-p) (org-do-demote))
6138 ((org-at-item-p) (org-indent-item 1))))
6140 (defun org-insert-todo-subheading (arg)
6141 "Insert a new subheading with TODO keyword or checkbox and demote it.
6142 Works for outline headings and for plain lists alike."
6143 (interactive "P")
6144 (org-insert-todo-heading arg)
6145 (cond
6146 ((org-on-heading-p) (org-do-demote))
6147 ((org-at-item-p) (org-indent-item 1))))
6149 ;;; Promotion and Demotion
6151 (defvar org-after-demote-entry-hook nil
6152 "Hook run after an entry has been demoted.
6153 The cursor will be at the beginning of the entry.
6154 When a subtree is being demoted, the hook will be called for each node.")
6156 (defvar org-after-promote-entry-hook nil
6157 "Hook run after an entry has been promoted.
6158 The cursor will be at the beginning of the entry.
6159 When a subtree is being promoted, the hook will be called for each node.")
6161 (defun org-promote-subtree ()
6162 "Promote the entire subtree.
6163 See also `org-promote'."
6164 (interactive)
6165 (save-excursion
6166 (org-map-tree 'org-promote))
6167 (org-fix-position-after-promote))
6169 (defun org-demote-subtree ()
6170 "Demote the entire subtree. See `org-demote'.
6171 See also `org-promote'."
6172 (interactive)
6173 (save-excursion
6174 (org-map-tree 'org-demote))
6175 (org-fix-position-after-promote))
6178 (defun org-do-promote ()
6179 "Promote the current heading higher up the tree.
6180 If the region is active in `transient-mark-mode', promote all headings
6181 in the region."
6182 (interactive)
6183 (save-excursion
6184 (if (org-region-active-p)
6185 (org-map-region 'org-promote (region-beginning) (region-end))
6186 (org-promote)))
6187 (org-fix-position-after-promote))
6189 (defun org-do-demote ()
6190 "Demote the current heading lower down the tree.
6191 If the region is active in `transient-mark-mode', demote all headings
6192 in the region."
6193 (interactive)
6194 (save-excursion
6195 (if (org-region-active-p)
6196 (org-map-region 'org-demote (region-beginning) (region-end))
6197 (org-demote)))
6198 (org-fix-position-after-promote))
6200 (defun org-fix-position-after-promote ()
6201 "Make sure that after pro/demotion cursor position is right."
6202 (let ((pos (point)))
6203 (when (save-excursion
6204 (beginning-of-line 1)
6205 (looking-at org-todo-line-regexp)
6206 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6207 (cond ((eobp) (insert " "))
6208 ((eolp) (insert " "))
6209 ((equal (char-after) ?\ ) (forward-char 1))))))
6211 (defun org-current-level ()
6212 "Return the level of the current entry, or nil if before the first headline.
6213 The level is the number of stars at the beginning of the headline."
6214 (save-excursion
6215 (condition-case nil
6216 (progn
6217 (org-back-to-heading t)
6218 (funcall outline-level))
6219 (error nil))))
6221 (defun org-reduced-level (l)
6222 "Compute the effective level of a heading.
6223 This takes into account the setting of `org-odd-levels-only'."
6224 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6226 (defun org-get-valid-level (level &optional change)
6227 "Rectify a level change under the influence of `org-odd-levels-only'
6228 LEVEL is a current level, CHANGE is by how much the level should be
6229 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6230 even level numbers will become the next higher odd number."
6231 (if org-odd-levels-only
6232 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6233 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6234 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6235 (max 1 (+ level (or change 0)))))
6237 (if (boundp 'define-obsolete-function-alias)
6238 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6239 (define-obsolete-function-alias 'org-get-legal-level
6240 'org-get-valid-level)
6241 (define-obsolete-function-alias 'org-get-legal-level
6242 'org-get-valid-level "23.1")))
6244 (defun org-promote ()
6245 "Promote the current heading higher up the tree.
6246 If the region is active in `transient-mark-mode', promote all headings
6247 in the region."
6248 (org-back-to-heading t)
6249 (let* ((level (save-match-data (funcall outline-level)))
6250 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6251 (diff (abs (- level (length up-head) -1))))
6252 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6253 (replace-match up-head nil t)
6254 ;; Fixup tag positioning
6255 (and org-auto-align-tags (org-set-tags nil t))
6256 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6257 (run-hooks 'org-after-promote-entry-hook)))
6259 (defun org-demote ()
6260 "Demote the current heading lower down the tree.
6261 If the region is active in `transient-mark-mode', demote all headings
6262 in the region."
6263 (org-back-to-heading t)
6264 (let* ((level (save-match-data (funcall outline-level)))
6265 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6266 (diff (abs (- level (length down-head) -1))))
6267 (replace-match down-head nil t)
6268 ;; Fixup tag positioning
6269 (and org-auto-align-tags (org-set-tags nil t))
6270 (if org-adapt-indentation (org-fixup-indentation diff))
6271 (run-hooks 'org-after-demote-entry-hook)))
6273 (defvar org-tab-ind-state nil)
6275 (defun org-cycle-level ()
6276 (let ((org-adapt-indentation nil))
6277 (when (and (looking-at "[ \t]*$")
6278 (looking-back
6279 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6280 (setq this-command 'org-cycle-level)
6281 (if (eq last-command 'org-cycle-level)
6282 (condition-case nil
6283 (progn (org-do-promote)
6284 (if (equal org-tab-ind-state (org-current-level))
6285 (org-do-promote)))
6286 (error
6287 (progn
6288 (save-excursion
6289 (beginning-of-line 1)
6290 (and (looking-at "\\*+")
6291 (replace-match
6292 (make-string org-tab-ind-state ?*))))
6293 (setq this-command 'org-cycle))))
6294 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6295 (org-do-demote))
6296 t)))
6298 (defun org-map-tree (fun)
6299 "Call FUN for every heading underneath the current one."
6300 (org-back-to-heading)
6301 (let ((level (funcall outline-level)))
6302 (save-excursion
6303 (funcall fun)
6304 (while (and (progn
6305 (outline-next-heading)
6306 (> (funcall outline-level) level))
6307 (not (eobp)))
6308 (funcall fun)))))
6310 (defun org-map-region (fun beg end)
6311 "Call FUN for every heading between BEG and END."
6312 (let ((org-ignore-region t))
6313 (save-excursion
6314 (setq end (copy-marker end))
6315 (goto-char beg)
6316 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6317 (< (point) end))
6318 (funcall fun))
6319 (while (and (progn
6320 (outline-next-heading)
6321 (< (point) end))
6322 (not (eobp)))
6323 (funcall fun)))))
6325 (defun org-fixup-indentation (diff)
6326 "Change the indentation in the current entry by DIFF
6327 However, if any line in the current entry has no indentation, or if it
6328 would end up with no indentation after the change, nothing at all is done."
6329 (save-excursion
6330 (let ((end (save-excursion (outline-next-heading)
6331 (point-marker)))
6332 (prohibit (if (> diff 0)
6333 "^\\S-"
6334 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6335 col)
6336 (unless (save-excursion (end-of-line 1)
6337 (re-search-forward prohibit end t))
6338 (while (and (< (point) end)
6339 (re-search-forward "^[ \t]+" end t))
6340 (goto-char (match-end 0))
6341 (setq col (current-column))
6342 (if (< diff 0) (replace-match ""))
6343 (org-indent-to-column (+ diff col))))
6344 (move-marker end nil))))
6346 (defun org-convert-to-odd-levels ()
6347 "Convert an org-mode file with all levels allowed to one with odd levels.
6348 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6349 level 5 etc."
6350 (interactive)
6351 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6352 (let ((outline-regexp org-outline-regexp)
6353 (outline-level 'org-outline-level)
6354 (org-odd-levels-only nil) n)
6355 (save-excursion
6356 (goto-char (point-min))
6357 (while (re-search-forward "^\\*\\*+ " nil t)
6358 (setq n (- (length (match-string 0)) 2))
6359 (while (>= (setq n (1- n)) 0)
6360 (org-demote))
6361 (end-of-line 1))))))
6363 (defun org-convert-to-oddeven-levels ()
6364 "Convert an org-mode file with only odd levels to one with odd and even levels.
6365 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6366 section with an even level, conversion would destroy the structure of the file. An error
6367 is signaled in this case."
6368 (interactive)
6369 (goto-char (point-min))
6370 ;; First check if there are no even levels
6371 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6372 (org-show-context t)
6373 (error "Not all levels are odd in this file. Conversion not possible"))
6374 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6375 (let ((outline-regexp org-outline-regexp)
6376 (outline-level 'org-outline-level)
6377 (org-odd-levels-only nil) n)
6378 (save-excursion
6379 (goto-char (point-min))
6380 (while (re-search-forward "^\\*\\*+ " nil t)
6381 (setq n (/ (1- (length (match-string 0))) 2))
6382 (while (>= (setq n (1- n)) 0)
6383 (org-promote))
6384 (end-of-line 1))))))
6386 (defun org-tr-level (n)
6387 "Make N odd if required."
6388 (if org-odd-levels-only (1+ (/ n 2)) n))
6390 ;;; Vertical tree motion, cutting and pasting of subtrees
6392 (defun org-move-subtree-up (&optional arg)
6393 "Move the current subtree up past ARG headlines of the same level."
6394 (interactive "p")
6395 (org-move-subtree-down (- (prefix-numeric-value arg))))
6397 (defun org-move-subtree-down (&optional arg)
6398 "Move the current subtree down past ARG headlines of the same level."
6399 (interactive "p")
6400 (setq arg (prefix-numeric-value arg))
6401 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6402 'org-get-last-sibling))
6403 (ins-point (make-marker))
6404 (cnt (abs arg))
6405 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6406 ;; Select the tree
6407 (org-back-to-heading)
6408 (setq beg0 (point))
6409 (save-excursion
6410 (setq ne-beg (org-back-over-empty-lines))
6411 (setq beg (point)))
6412 (save-match-data
6413 (save-excursion (outline-end-of-heading)
6414 (setq folded (org-invisible-p)))
6415 (outline-end-of-subtree))
6416 (outline-next-heading)
6417 (setq ne-end (org-back-over-empty-lines))
6418 (setq end (point))
6419 (goto-char beg0)
6420 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6421 ;; include less whitespace
6422 (save-excursion
6423 (goto-char beg)
6424 (forward-line (- ne-beg ne-end))
6425 (setq beg (point))))
6426 ;; Find insertion point, with error handling
6427 (while (> cnt 0)
6428 (or (and (funcall movfunc) (looking-at outline-regexp))
6429 (progn (goto-char beg0)
6430 (error "Cannot move past superior level or buffer limit")))
6431 (setq cnt (1- cnt)))
6432 (if (> arg 0)
6433 ;; Moving forward - still need to move over subtree
6434 (progn (org-end-of-subtree t t)
6435 (save-excursion
6436 (org-back-over-empty-lines)
6437 (or (bolp) (newline)))))
6438 (setq ne-ins (org-back-over-empty-lines))
6439 (move-marker ins-point (point))
6440 (setq txt (buffer-substring beg end))
6441 (org-save-markers-in-region beg end)
6442 (delete-region beg end)
6443 (org-remove-empty-overlays-at beg)
6444 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6445 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6446 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6447 (let ((bbb (point)))
6448 (insert-before-markers txt)
6449 (org-reinstall-markers-in-region bbb)
6450 (move-marker ins-point bbb))
6451 (or (bolp) (insert "\n"))
6452 (setq ins-end (point))
6453 (goto-char ins-point)
6454 (org-skip-whitespace)
6455 (when (and (< arg 0)
6456 (org-first-sibling-p)
6457 (> ne-ins ne-beg))
6458 ;; Move whitespace back to beginning
6459 (save-excursion
6460 (goto-char ins-end)
6461 (let ((kill-whole-line t))
6462 (kill-line (- ne-ins ne-beg)) (point)))
6463 (insert (make-string (- ne-ins ne-beg) ?\n)))
6464 (move-marker ins-point nil)
6465 (if folded
6466 (hide-subtree)
6467 (org-show-entry)
6468 (show-children)
6469 (org-cycle-hide-drawers 'children))
6470 (org-clean-visibility-after-subtree-move)))
6472 (defvar org-subtree-clip ""
6473 "Clipboard for cut and paste of subtrees.
6474 This is actually only a copy of the kill, because we use the normal kill
6475 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6477 (defvar org-subtree-clip-folded nil
6478 "Was the last copied subtree folded?
6479 This is used to fold the tree back after pasting.")
6481 (defun org-cut-subtree (&optional n)
6482 "Cut the current subtree into the clipboard.
6483 With prefix arg N, cut this many sequential subtrees.
6484 This is a short-hand for marking the subtree and then cutting it."
6485 (interactive "p")
6486 (org-copy-subtree n 'cut))
6488 (defun org-copy-subtree (&optional n cut force-store-markers)
6489 "Cut the current subtree into the clipboard.
6490 With prefix arg N, cut this many sequential subtrees.
6491 This is a short-hand for marking the subtree and then copying it.
6492 If CUT is non-nil, actually cut the subtree.
6493 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6494 of some markers in the region, even if CUT is non-nil. This is
6495 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6496 (interactive "p")
6497 (let (beg end folded (beg0 (point)))
6498 (if (interactive-p)
6499 (org-back-to-heading nil) ; take what looks like a subtree
6500 (org-back-to-heading t)) ; take what is really there
6501 (org-back-over-empty-lines)
6502 (setq beg (point))
6503 (skip-chars-forward " \t\r\n")
6504 (save-match-data
6505 (save-excursion (outline-end-of-heading)
6506 (setq folded (org-invisible-p)))
6507 (condition-case nil
6508 (org-forward-same-level (1- n) t)
6509 (error nil))
6510 (org-end-of-subtree t t))
6511 (org-back-over-empty-lines)
6512 (setq end (point))
6513 (goto-char beg0)
6514 (when (> end beg)
6515 (setq org-subtree-clip-folded folded)
6516 (when (or cut force-store-markers)
6517 (org-save-markers-in-region beg end))
6518 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6519 (setq org-subtree-clip (current-kill 0))
6520 (message "%s: Subtree(s) with %d characters"
6521 (if cut "Cut" "Copied")
6522 (length org-subtree-clip)))))
6524 (defun org-paste-subtree (&optional level tree for-yank)
6525 "Paste the clipboard as a subtree, with modification of headline level.
6526 The entire subtree is promoted or demoted in order to match a new headline
6527 level.
6529 If the cursor is at the beginning of a headline, the same level as
6530 that headline is used to paste the tree
6532 If not, the new level is derived from the *visible* headings
6533 before and after the insertion point, and taken to be the inferior headline
6534 level of the two. So if the previous visible heading is level 3 and the
6535 next is level 4 (or vice versa), level 4 will be used for insertion.
6536 This makes sure that the subtree remains an independent subtree and does
6537 not swallow low level entries.
6539 You can also force a different level, either by using a numeric prefix
6540 argument, or by inserting the heading marker by hand. For example, if the
6541 cursor is after \"*****\", then the tree will be shifted to level 5.
6543 If optional TREE is given, use this text instead of the kill ring.
6545 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6546 move back over whitespace before inserting, and move point to the end of
6547 the inserted text when done."
6548 (interactive "P")
6549 (setq tree (or tree (and kill-ring (current-kill 0))))
6550 (unless (org-kill-is-subtree-p tree)
6551 (error "%s"
6552 (substitute-command-keys
6553 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6554 (let* ((visp (not (org-invisible-p)))
6555 (txt tree)
6556 (^re (concat "^\\(" outline-regexp "\\)"))
6557 (re (concat "\\(" outline-regexp "\\)"))
6558 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6560 (old-level (if (string-match ^re txt)
6561 (- (match-end 0) (match-beginning 0) 1)
6562 -1))
6563 (force-level (cond (level (prefix-numeric-value level))
6564 ((and (looking-at "[ \t]*$")
6565 (string-match
6566 ^re_ (buffer-substring
6567 (point-at-bol) (point))))
6568 (- (match-end 1) (match-beginning 1)))
6569 ((and (bolp)
6570 (looking-at org-outline-regexp))
6571 (- (match-end 0) (point) 1))
6572 (t nil)))
6573 (previous-level (save-excursion
6574 (condition-case nil
6575 (progn
6576 (outline-previous-visible-heading 1)
6577 (if (looking-at re)
6578 (- (match-end 0) (match-beginning 0) 1)
6580 (error 1))))
6581 (next-level (save-excursion
6582 (condition-case nil
6583 (progn
6584 (or (looking-at outline-regexp)
6585 (outline-next-visible-heading 1))
6586 (if (looking-at re)
6587 (- (match-end 0) (match-beginning 0) 1)
6589 (error 1))))
6590 (new-level (or force-level (max previous-level next-level)))
6591 (shift (if (or (= old-level -1)
6592 (= new-level -1)
6593 (= old-level new-level))
6595 (- new-level old-level)))
6596 (delta (if (> shift 0) -1 1))
6597 (func (if (> shift 0) 'org-demote 'org-promote))
6598 (org-odd-levels-only nil)
6599 beg end newend)
6600 ;; Remove the forced level indicator
6601 (if force-level
6602 (delete-region (point-at-bol) (point)))
6603 ;; Paste
6604 (beginning-of-line 1)
6605 (unless for-yank (org-back-over-empty-lines))
6606 (setq beg (point))
6607 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6608 (insert-before-markers txt)
6609 (unless (string-match "\n\\'" txt) (insert "\n"))
6610 (setq newend (point))
6611 (org-reinstall-markers-in-region beg)
6612 (setq end (point))
6613 (goto-char beg)
6614 (skip-chars-forward " \t\n\r")
6615 (setq beg (point))
6616 (if (and (org-invisible-p) visp)
6617 (save-excursion (outline-show-heading)))
6618 ;; Shift if necessary
6619 (unless (= shift 0)
6620 (save-restriction
6621 (narrow-to-region beg end)
6622 (while (not (= shift 0))
6623 (org-map-region func (point-min) (point-max))
6624 (setq shift (+ delta shift)))
6625 (goto-char (point-min))
6626 (setq newend (point-max))))
6627 (when (or (interactive-p) for-yank)
6628 (message "Clipboard pasted as level %d subtree" new-level))
6629 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6630 kill-ring
6631 (eq org-subtree-clip (current-kill 0))
6632 org-subtree-clip-folded)
6633 ;; The tree was folded before it was killed/copied
6634 (hide-subtree))
6635 (and for-yank (goto-char newend))))
6637 (defun org-kill-is-subtree-p (&optional txt)
6638 "Check if the current kill is an outline subtree, or a set of trees.
6639 Returns nil if kill does not start with a headline, or if the first
6640 headline level is not the largest headline level in the tree.
6641 So this will actually accept several entries of equal levels as well,
6642 which is OK for `org-paste-subtree'.
6643 If optional TXT is given, check this string instead of the current kill."
6644 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6645 (start-level (and kill
6646 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6647 org-outline-regexp "\\)")
6648 kill)
6649 (- (match-end 2) (match-beginning 2) 1)))
6650 (re (concat "^" org-outline-regexp))
6651 (start (1+ (or (match-beginning 2) -1))))
6652 (if (not start-level)
6653 (progn
6654 nil) ;; does not even start with a heading
6655 (catch 'exit
6656 (while (setq start (string-match re kill (1+ start)))
6657 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6658 (throw 'exit nil)))
6659 t))))
6661 (defvar org-markers-to-move nil
6662 "Markers that should be moved with a cut-and-paste operation.
6663 Those markers are stored together with their positions relative to
6664 the start of the region.")
6666 (defun org-save-markers-in-region (beg end)
6667 "Check markers in region.
6668 If these markers are between BEG and END, record their position relative
6669 to BEG, so that after moving the block of text, we can put the markers back
6670 into place.
6671 This function gets called just before an entry or tree gets cut from the
6672 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6673 called immediately, to move the markers with the entries."
6674 (setq org-markers-to-move nil)
6675 (when (featurep 'org-clock)
6676 (org-clock-save-markers-for-cut-and-paste beg end))
6677 (when (featurep 'org-agenda)
6678 (org-agenda-save-markers-for-cut-and-paste beg end)))
6680 (defun org-check-and-save-marker (marker beg end)
6681 "Check if MARKER is between BEG and END.
6682 If yes, remember the marker and the distance to BEG."
6683 (when (and (marker-buffer marker)
6684 (equal (marker-buffer marker) (current-buffer)))
6685 (if (and (>= marker beg) (< marker end))
6686 (push (cons marker (- marker beg)) org-markers-to-move))))
6688 (defun org-reinstall-markers-in-region (beg)
6689 "Move all remembered markers to their position relative to BEG."
6690 (mapc (lambda (x)
6691 (move-marker (car x) (+ beg (cdr x))))
6692 org-markers-to-move)
6693 (setq org-markers-to-move nil))
6695 (defun org-narrow-to-subtree ()
6696 "Narrow buffer to the current subtree."
6697 (interactive)
6698 (save-excursion
6699 (save-match-data
6700 (narrow-to-region
6701 (progn (org-back-to-heading t) (point))
6702 (progn (org-end-of-subtree t t) (point))))))
6704 (defun org-clone-subtree-with-time-shift (n &optional shift)
6705 "Clone the task (subtree) at point N times.
6706 The clones will be inserted as siblings.
6708 In interactive use, the user will be prompted for the number of clones
6709 to be produced, and for a time SHIFT, which may be a repeater as used
6710 in time stamps, for example `+3d'.
6712 When a valid repeater is given and the entry contains any time stamps,
6713 the clones will become a sequence in time, with time stamps in the
6714 subtree shifted for each clone produced. If SHIFT is nil or the
6715 empty string, time stamps will be left alone.
6717 If the original subtree did contain time stamps with a repeater,
6718 the following will happen:
6719 - the repeater will be removed in each clone
6720 - an additional clone will be produced, with the current, unshifted
6721 date(s) in the entry.
6722 - the original entry will be placed *after* all the clones, with
6723 repeater intact.
6724 - the start days in the repeater in the original entry will be shifted
6725 to past the last clone.
6726 I this way you can spell out a number of instances of a repeating task,
6727 and still retain the repeater to cover future instances of the task."
6728 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6729 (let (beg end template task
6730 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6731 (if (not (and (integerp n) (> n 0)))
6732 (error "Invalid number of replications %s" n))
6733 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6734 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6735 shift)))
6736 (error "Invalid shift specification %s" shift))
6737 (when doshift
6738 (setq shift-n (string-to-number (match-string 1 shift))
6739 shift-what (cdr (assoc (match-string 2 shift)
6740 '(("d" . day) ("w" . week)
6741 ("m" . month) ("y" . year))))))
6742 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6743 (setq nmin 1 nmax n)
6744 (org-back-to-heading t)
6745 (setq beg (point))
6746 (org-end-of-subtree t t)
6747 (or (bolp) (insert "\n"))
6748 (setq end (point))
6749 (setq template (buffer-substring beg end))
6750 (when (and doshift
6751 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6752 (delete-region beg end)
6753 (setq end beg)
6754 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6755 (goto-char end)
6756 (loop for n from nmin to nmax do
6757 (if (not doshift)
6758 (setq task template)
6759 (with-temp-buffer
6760 (insert template)
6761 (org-mode)
6762 (goto-char (point-min))
6763 (while (re-search-forward org-ts-regexp-both nil t)
6764 (org-timestamp-change (* n shift-n) shift-what))
6765 (unless (= n n-no-remove)
6766 (goto-char (point-min))
6767 (while (re-search-forward org-ts-regexp nil t)
6768 (save-excursion
6769 (goto-char (match-beginning 0))
6770 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6771 (delete-region (match-beginning 1) (match-end 1))))))
6772 (setq task (buffer-string))))
6773 (insert task))
6774 (goto-char beg)))
6776 ;;; Outline Sorting
6778 (defun org-sort (with-case)
6779 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6780 Optional argument WITH-CASE means sort case-sensitively.
6781 With a double prefix argument, also remove duplicate entries."
6782 (interactive "P")
6783 (if (org-at-table-p)
6784 (org-call-with-arg 'org-table-sort-lines with-case)
6785 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6787 (defun org-sort-remove-invisible (s)
6788 (remove-text-properties 0 (length s) org-rm-props s)
6789 (while (string-match org-bracket-link-regexp s)
6790 (setq s (replace-match (if (match-end 2)
6791 (match-string 3 s)
6792 (match-string 1 s)) t t s)))
6795 (defvar org-priority-regexp) ; defined later in the file
6797 (defvar org-after-sorting-entries-or-items-hook nil
6798 "Hook that is run after a bunch of entries or items have been sorted.
6799 When children are sorted, the cursor is in the parent line when this
6800 hook gets called. When a region or a plain list is sorted, the cursor
6801 will be in the first entry of the sorted region/list.")
6803 (defun org-sort-entries-or-items
6804 (&optional with-case sorting-type getkey-func compare-func property)
6805 "Sort entries on a certain level of an outline tree, or plain list items.
6806 If there is an active region, the entries in the region are sorted.
6807 Else, if the cursor is before the first entry, sort the top-level items.
6808 Else, the children of the entry at point are sorted.
6809 If the cursor is at the first item in a plain list, the list items will be
6810 sorted.
6812 Sorting can be alphabetically, numerically, by date/time as given by
6813 a time stamp, by a property or by priority.
6815 The command prompts for the sorting type unless it has been given to the
6816 function through the SORTING-TYPE argument, which needs to a character,
6817 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6818 precise meaning of each character:
6820 n Numerically, by converting the beginning of the entry/item to a number.
6821 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6822 t By date/time, either the first active time stamp in the entry, or, if
6823 none exist, by the first inactive one.
6824 In items, only the first line will be checked.
6825 s By the scheduled date/time.
6826 d By deadline date/time.
6827 c By creation time, which is assumed to be the first inactive time stamp
6828 at the beginning of a line.
6829 p By priority according to the cookie.
6830 r By the value of a property.
6832 Capital letters will reverse the sort order.
6834 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6835 called with point at the beginning of the record. It must return either
6836 a string or a number that should serve as the sorting key for that record.
6838 Comparing entries ignores case by default. However, with an optional argument
6839 WITH-CASE, the sorting considers case as well."
6840 (interactive "P")
6841 (let ((case-func (if with-case 'identity 'downcase))
6842 start beg end stars re re2
6843 txt what tmp plain-list-p)
6844 ;; Find beginning and end of region to sort
6845 (cond
6846 ((org-region-active-p)
6847 ;; we will sort the region
6848 (setq end (region-end)
6849 what "region")
6850 (goto-char (region-beginning))
6851 (if (not (org-on-heading-p)) (outline-next-heading))
6852 (setq start (point)))
6853 ((org-at-item-p)
6854 ;; we will sort this plain list
6855 (org-beginning-of-item-list) (setq start (point))
6856 (org-end-of-item-list) (setq end (point))
6857 (goto-char start)
6858 (setq plain-list-p t
6859 what "plain list"))
6860 ((or (org-on-heading-p)
6861 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6862 ;; we will sort the children of the current headline
6863 (org-back-to-heading)
6864 (setq start (point)
6865 end (progn (org-end-of-subtree t t)
6866 (org-back-over-empty-lines)
6867 (point))
6868 what "children")
6869 (goto-char start)
6870 (show-subtree)
6871 (outline-next-heading))
6873 ;; we will sort the top-level entries in this file
6874 (goto-char (point-min))
6875 (or (org-on-heading-p) (outline-next-heading))
6876 (setq start (point) end (point-max) what "top-level")
6877 (goto-char start)
6878 (show-all)))
6880 (setq beg (point))
6881 (if (>= beg end) (error "Nothing to sort"))
6883 (unless plain-list-p
6884 (looking-at "\\(\\*+\\)")
6885 (setq stars (match-string 1)
6886 re (concat "^" (regexp-quote stars) " +")
6887 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6888 txt (buffer-substring beg end))
6889 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6890 (if (and (not (equal stars "*")) (string-match re2 txt))
6891 (error "Region to sort contains a level above the first entry")))
6893 (unless sorting-type
6894 (message
6895 (if plain-list-p
6896 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6897 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6898 [t]ime [s]cheduled [d]eadline [c]reated
6899 A/N/T/S/D/C/P/O/F means reversed:")
6900 what)
6901 (setq sorting-type (read-char-exclusive))
6903 (and (= (downcase sorting-type) ?f)
6904 (setq getkey-func
6905 (org-icompleting-read "Sort using function: "
6906 obarray 'fboundp t nil nil))
6907 (setq getkey-func (intern getkey-func)))
6909 (and (= (downcase sorting-type) ?r)
6910 (setq property
6911 (org-icompleting-read "Property: "
6912 (mapcar 'list (org-buffer-property-keys t))
6913 nil t))))
6915 (message "Sorting entries...")
6917 (save-restriction
6918 (narrow-to-region start end)
6920 (let ((dcst (downcase sorting-type))
6921 (case-fold-search nil)
6922 (now (current-time)))
6923 (sort-subr
6924 (/= dcst sorting-type)
6925 ;; This function moves to the beginning character of the "record" to
6926 ;; be sorted.
6927 (if plain-list-p
6928 (lambda nil
6929 (if (org-at-item-p) t (goto-char (point-max))))
6930 (lambda nil
6931 (if (re-search-forward re nil t)
6932 (goto-char (match-beginning 0))
6933 (goto-char (point-max)))))
6934 ;; This function moves to the last character of the "record" being
6935 ;; sorted.
6936 (if plain-list-p
6937 'org-end-of-item
6938 (lambda nil
6939 (save-match-data
6940 (condition-case nil
6941 (outline-forward-same-level 1)
6942 (error
6943 (goto-char (point-max)))))))
6945 ;; This function returns the value that gets sorted against.
6946 (if plain-list-p
6947 (lambda nil
6948 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6949 (cond
6950 ((= dcst ?n)
6951 (string-to-number (buffer-substring (match-end 0)
6952 (point-at-eol))))
6953 ((= dcst ?a)
6954 (buffer-substring (match-end 0) (point-at-eol)))
6955 ((= dcst ?t)
6956 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6957 (re-search-forward org-ts-regexp-both
6958 (point-at-eol) t))
6959 (org-time-string-to-seconds (match-string 0))
6960 (org-float-time now)))
6961 ((= dcst ?f)
6962 (if getkey-func
6963 (progn
6964 (setq tmp (funcall getkey-func))
6965 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6966 tmp)
6967 (error "Invalid key function `%s'" getkey-func)))
6968 (t (error "Invalid sorting type `%c'" sorting-type)))))
6969 (lambda nil
6970 (cond
6971 ((= dcst ?n)
6972 (if (looking-at org-complex-heading-regexp)
6973 (string-to-number (match-string 4))
6974 nil))
6975 ((= dcst ?a)
6976 (if (looking-at org-complex-heading-regexp)
6977 (funcall case-func (match-string 4))
6978 nil))
6979 ((= dcst ?t)
6980 (let ((end (save-excursion (outline-next-heading) (point))))
6981 (if (or (re-search-forward org-ts-regexp end t)
6982 (re-search-forward org-ts-regexp-both end t))
6983 (org-time-string-to-seconds (match-string 0))
6984 (org-float-time now))))
6985 ((= dcst ?c)
6986 (let ((end (save-excursion (outline-next-heading) (point))))
6987 (if (re-search-forward
6988 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6989 end t)
6990 (org-time-string-to-seconds (match-string 0))
6991 (org-float-time now))))
6992 ((= dcst ?s)
6993 (let ((end (save-excursion (outline-next-heading) (point))))
6994 (if (re-search-forward org-scheduled-time-regexp end t)
6995 (org-time-string-to-seconds (match-string 1))
6996 (org-float-time now))))
6997 ((= dcst ?d)
6998 (let ((end (save-excursion (outline-next-heading) (point))))
6999 (if (re-search-forward org-deadline-time-regexp end t)
7000 (org-time-string-to-seconds (match-string 1))
7001 (org-float-time now))))
7002 ((= dcst ?p)
7003 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7004 (string-to-char (match-string 2))
7005 org-default-priority))
7006 ((= dcst ?r)
7007 (or (org-entry-get nil property) ""))
7008 ((= dcst ?o)
7009 (if (looking-at org-complex-heading-regexp)
7010 (- 9999 (length (member (match-string 2)
7011 org-todo-keywords-1)))))
7012 ((= dcst ?f)
7013 (if getkey-func
7014 (progn
7015 (setq tmp (funcall getkey-func))
7016 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7017 tmp)
7018 (error "Invalid key function `%s'" getkey-func)))
7019 (t (error "Invalid sorting type `%c'" sorting-type)))))
7021 (cond
7022 ((= dcst ?a) 'string<)
7023 ((= dcst ?f) compare-func)
7024 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7025 (t nil)))))
7026 (run-hooks 'org-after-sorting-entries-or-items-hook)
7027 (message "Sorting entries...done")))
7029 (defun org-do-sort (table what &optional with-case sorting-type)
7030 "Sort TABLE of WHAT according to SORTING-TYPE.
7031 The user will be prompted for the SORTING-TYPE if the call to this
7032 function does not specify it. WHAT is only for the prompt, to indicate
7033 what is being sorted. The sorting key will be extracted from
7034 the car of the elements of the table.
7035 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7036 (unless sorting-type
7037 (message
7038 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7039 what)
7040 (setq sorting-type (read-char-exclusive)))
7041 (let ((dcst (downcase sorting-type))
7042 extractfun comparefun)
7043 ;; Define the appropriate functions
7044 (cond
7045 ((= dcst ?n)
7046 (setq extractfun 'string-to-number
7047 comparefun (if (= dcst sorting-type) '< '>)))
7048 ((= dcst ?a)
7049 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7050 (lambda(x) (downcase (org-sort-remove-invisible x))))
7051 comparefun (if (= dcst sorting-type)
7052 'string<
7053 (lambda (a b) (and (not (string< a b))
7054 (not (string= a b)))))))
7055 ((= dcst ?t)
7056 (setq extractfun
7057 (lambda (x)
7058 (if (or (string-match org-ts-regexp x)
7059 (string-match org-ts-regexp-both x))
7060 (org-float-time
7061 (org-time-string-to-time (match-string 0 x)))
7063 comparefun (if (= dcst sorting-type) '< '>)))
7064 (t (error "Invalid sorting type `%c'" sorting-type)))
7066 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7067 table)
7068 (lambda (a b) (funcall comparefun (car a) (car b))))))
7071 ;;; The orgstruct minor mode
7073 ;; Define a minor mode which can be used in other modes in order to
7074 ;; integrate the org-mode structure editing commands.
7076 ;; This is really a hack, because the org-mode structure commands use
7077 ;; keys which normally belong to the major mode. Here is how it
7078 ;; works: The minor mode defines all the keys necessary to operate the
7079 ;; structure commands, but wraps the commands into a function which
7080 ;; tests if the cursor is currently at a headline or a plain list
7081 ;; item. If that is the case, the structure command is used,
7082 ;; temporarily setting many Org-mode variables like regular
7083 ;; expressions for filling etc. However, when any of those keys is
7084 ;; used at a different location, function uses `key-binding' to look
7085 ;; up if the key has an associated command in another currently active
7086 ;; keymap (minor modes, major mode, global), and executes that
7087 ;; command. There might be problems if any of the keys is otherwise
7088 ;; used as a prefix key.
7090 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7091 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7092 ;; addresses this by checking explicitly for both bindings.
7094 (defvar orgstruct-mode-map (make-sparse-keymap)
7095 "Keymap for the minor `orgstruct-mode'.")
7097 (defvar org-local-vars nil
7098 "List of local variables, for use by `orgstruct-mode'")
7100 ;;;###autoload
7101 (define-minor-mode orgstruct-mode
7102 "Toggle the minor more `orgstruct-mode'.
7103 This mode is for using Org-mode structure commands in other modes.
7104 The following key behave as if Org-mode was active, if the cursor
7105 is on a headline, or on a plain list item (both in the definition
7106 of Org-mode).
7108 M-up Move entry/item up
7109 M-down Move entry/item down
7110 M-left Promote
7111 M-right Demote
7112 M-S-up Move entry/item up
7113 M-S-down Move entry/item down
7114 M-S-left Promote subtree
7115 M-S-right Demote subtree
7116 M-q Fill paragraph and items like in Org-mode
7117 C-c ^ Sort entries
7118 C-c - Cycle list bullet
7119 TAB Cycle item visibility
7120 M-RET Insert new heading/item
7121 S-M-RET Insert new TODO heading / Checkbox item
7122 C-c C-c Set tags / toggle checkbox"
7123 nil " OrgStruct" nil
7124 (org-load-modules-maybe)
7125 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7127 ;;;###autoload
7128 (defun turn-on-orgstruct ()
7129 "Unconditionally turn on `orgstruct-mode'."
7130 (orgstruct-mode 1))
7132 (defun orgstruct++-mode (&optional arg)
7133 "Toggle `orgstruct-mode', the enhanced version of it.
7134 In addition to setting orgstruct-mode, this also exports all indentation
7135 and autofilling variables from org-mode into the buffer. It will also
7136 recognize item context in multiline items.
7137 Note that turning off orgstruct-mode will *not* remove the
7138 indentation/paragraph settings. This can only be done by refreshing the
7139 major mode, for example with \\[normal-mode]."
7140 (interactive "P")
7141 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7142 (if (< arg 1)
7143 (orgstruct-mode -1)
7144 (orgstruct-mode 1)
7145 (let (var val)
7146 (mapc
7147 (lambda (x)
7148 (when (string-match
7149 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7150 (symbol-name (car x)))
7151 (setq var (car x) val (nth 1 x))
7152 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7153 org-local-vars)
7154 (org-set-local 'orgstruct-is-++ t))))
7156 (defvar orgstruct-is-++ nil
7157 "Is orgstruct-mode in ++ version in the current-buffer?")
7158 (make-variable-buffer-local 'orgstruct-is-++)
7160 ;;;###autoload
7161 (defun turn-on-orgstruct++ ()
7162 "Unconditionally turn on `orgstruct++-mode'."
7163 (orgstruct++-mode 1))
7165 (defun orgstruct-error ()
7166 "Error when there is no default binding for a structure key."
7167 (interactive)
7168 (error "This key has no function outside structure elements"))
7170 (defun orgstruct-setup ()
7171 "Setup orgstruct keymaps."
7172 (let ((nfunc 0)
7173 (bindings
7174 (list
7175 '([(meta up)] org-metaup)
7176 '([(meta down)] org-metadown)
7177 '([(meta left)] org-metaleft)
7178 '([(meta right)] org-metaright)
7179 '([(meta shift up)] org-shiftmetaup)
7180 '([(meta shift down)] org-shiftmetadown)
7181 '([(meta shift left)] org-shiftmetaleft)
7182 '([(meta shift right)] org-shiftmetaright)
7183 '([?\e (up)] org-metaup)
7184 '([?\e (down)] org-metadown)
7185 '([?\e (left)] org-metaleft)
7186 '([?\e (right)] org-metaright)
7187 '([?\e (shift up)] org-shiftmetaup)
7188 '([?\e (shift down)] org-shiftmetadown)
7189 '([?\e (shift left)] org-shiftmetaleft)
7190 '([?\e (shift right)] org-shiftmetaright)
7191 '([(shift up)] org-shiftup)
7192 '([(shift down)] org-shiftdown)
7193 '([(shift left)] org-shiftleft)
7194 '([(shift right)] org-shiftright)
7195 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7196 '("\M-q" fill-paragraph)
7197 '("\C-c^" org-sort)
7198 '("\C-c-" org-cycle-list-bullet)))
7199 elt key fun cmd)
7200 (while (setq elt (pop bindings))
7201 (setq nfunc (1+ nfunc))
7202 (setq key (org-key (car elt))
7203 fun (nth 1 elt)
7204 cmd (orgstruct-make-binding fun nfunc key))
7205 (org-defkey orgstruct-mode-map key cmd))
7207 ;; Special treatment needed for TAB and RET
7208 (org-defkey orgstruct-mode-map [(tab)]
7209 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7210 (org-defkey orgstruct-mode-map "\C-i"
7211 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7213 (org-defkey orgstruct-mode-map "\M-\C-m"
7214 (orgstruct-make-binding 'org-insert-heading 105
7215 "\M-\C-m" [(meta return)]))
7216 (org-defkey orgstruct-mode-map [(meta return)]
7217 (orgstruct-make-binding 'org-insert-heading 106
7218 [(meta return)] "\M-\C-m"))
7220 (org-defkey orgstruct-mode-map [(shift meta return)]
7221 (orgstruct-make-binding 'org-insert-todo-heading 107
7222 [(meta return)] "\M-\C-m"))
7224 (org-defkey orgstruct-mode-map "\e\C-m"
7225 (orgstruct-make-binding 'org-insert-heading 108
7226 "\e\C-m" [?\e (return)]))
7227 (org-defkey orgstruct-mode-map [?\e (return)]
7228 (orgstruct-make-binding 'org-insert-heading 109
7229 [?\e (return)] "\e\C-m"))
7230 (org-defkey orgstruct-mode-map [?\e (shift return)]
7231 (orgstruct-make-binding 'org-insert-todo-heading 110
7232 [?\e (return)] "\e\C-m"))
7234 (unless org-local-vars
7235 (setq org-local-vars (org-get-local-variables)))
7239 (defun orgstruct-make-binding (fun n &rest keys)
7240 "Create a function for binding in the structure minor mode.
7241 FUN is the command to call inside a table. N is used to create a unique
7242 command name. KEYS are keys that should be checked in for a command
7243 to execute outside of tables."
7244 (eval
7245 (list 'defun
7246 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7247 '(arg)
7248 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7249 "Outside of structure, run the binding of `"
7250 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7251 "'.")
7252 '(interactive "p")
7253 (list 'if
7254 `(org-context-p 'headline 'item
7255 (and orgstruct-is-++
7256 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7257 'item-body))
7258 (list 'org-run-like-in-org-mode (list 'quote fun))
7259 (list 'let '(orgstruct-mode)
7260 (list 'call-interactively
7261 (append '(or)
7262 (mapcar (lambda (k)
7263 (list 'key-binding k))
7264 keys)
7265 '('orgstruct-error))))))))
7267 (defun org-context-p (&rest contexts)
7268 "Check if local context is any of CONTEXTS.
7269 Possible values in the list of contexts are `table', `headline', and `item'."
7270 (let ((pos (point)))
7271 (goto-char (point-at-bol))
7272 (prog1 (or (and (memq 'table contexts)
7273 (looking-at "[ \t]*|"))
7274 (and (memq 'headline contexts)
7275 ;;????????? (looking-at "\\*+"))
7276 (looking-at outline-regexp))
7277 (and (memq 'item contexts)
7278 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7279 (and (memq 'item-body contexts)
7280 (org-in-item-p)))
7281 (goto-char pos))))
7283 (defun org-get-local-variables ()
7284 "Return a list of all local variables in an org-mode buffer."
7285 (let (varlist)
7286 (with-current-buffer (get-buffer-create "*Org tmp*")
7287 (erase-buffer)
7288 (org-mode)
7289 (setq varlist (buffer-local-variables)))
7290 (kill-buffer "*Org tmp*")
7291 (delq nil
7292 (mapcar
7293 (lambda (x)
7294 (setq x
7295 (if (symbolp x)
7296 (list x)
7297 (list (car x) (list 'quote (cdr x)))))
7298 (if (string-match
7299 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7300 (symbol-name (car x)))
7301 x nil))
7302 varlist))))
7304 ;;;###autoload
7305 (defun org-run-like-in-org-mode (cmd)
7306 "Run a command, pretending that the current buffer is in Org-mode.
7307 This will temporarily bind local variables that are typically bound in
7308 Org-mode to the values they have in Org-mode, and then interactively
7309 call CMD."
7310 (org-load-modules-maybe)
7311 (unless org-local-vars
7312 (setq org-local-vars (org-get-local-variables)))
7313 (eval (list 'let org-local-vars
7314 (list 'call-interactively (list 'quote cmd)))))
7316 ;;;; Archiving
7318 (defun org-get-category (&optional pos)
7319 "Get the category applying to position POS."
7320 (get-text-property (or pos (point)) 'org-category))
7322 (defun org-refresh-category-properties ()
7323 "Refresh category text properties in the buffer."
7324 (let ((def-cat (cond
7325 ((null org-category)
7326 (if buffer-file-name
7327 (file-name-sans-extension
7328 (file-name-nondirectory buffer-file-name))
7329 "???"))
7330 ((symbolp org-category) (symbol-name org-category))
7331 (t org-category)))
7332 beg end cat pos optionp)
7333 (org-unmodified
7334 (save-excursion
7335 (save-restriction
7336 (widen)
7337 (goto-char (point-min))
7338 (put-text-property (point) (point-max) 'org-category def-cat)
7339 (while (re-search-forward
7340 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7341 (setq pos (match-end 0)
7342 optionp (equal (char-after (match-beginning 0)) ?#)
7343 cat (org-trim (match-string 2)))
7344 (if optionp
7345 (setq beg (point-at-bol) end (point-max))
7346 (org-back-to-heading t)
7347 (setq beg (point) end (org-end-of-subtree t t)))
7348 (put-text-property beg end 'org-category cat)
7349 (goto-char pos)))))))
7352 ;;;; Link Stuff
7354 ;;; Link abbreviations
7356 (defun org-link-expand-abbrev (link)
7357 "Apply replacements as defined in `org-link-abbrev-alist."
7358 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7359 (let* ((key (match-string 1 link))
7360 (as (or (assoc key org-link-abbrev-alist-local)
7361 (assoc key org-link-abbrev-alist)))
7362 (tag (and (match-end 2) (match-string 3 link)))
7363 rpl)
7364 (if (not as)
7365 link
7366 (setq rpl (cdr as))
7367 (cond
7368 ((symbolp rpl) (funcall rpl tag))
7369 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7370 ((string-match "%h" rpl)
7371 (replace-match (url-hexify-string (or tag "")) t t rpl))
7372 (t (concat rpl tag)))))
7373 link))
7375 ;;; Storing and inserting links
7377 (defvar org-insert-link-history nil
7378 "Minibuffer history for links inserted with `org-insert-link'.")
7380 (defvar org-stored-links nil
7381 "Contains the links stored with `org-store-link'.")
7383 (defvar org-store-link-plist nil
7384 "Plist with info about the most recently link created with `org-store-link'.")
7386 (defvar org-link-protocols nil
7387 "Link protocols added to Org-mode using `org-add-link-type'.")
7389 (defvar org-store-link-functions nil
7390 "List of functions that are called to create and store a link.
7391 Each function will be called in turn until one returns a non-nil
7392 value. Each function should check if it is responsible for creating
7393 this link (for example by looking at the major mode).
7394 If not, it must exit and return nil.
7395 If yes, it should return a non-nil value after a calling
7396 `org-store-link-props' with a list of properties and values.
7397 Special properties are:
7399 :type The link prefix. like \"http\". This must be given.
7400 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7401 This is obligatory as well.
7402 :description Optional default description for the second pair
7403 of brackets in an Org-mode link. The user can still change
7404 this when inserting this link into an Org-mode buffer.
7406 In addition to these, any additional properties can be specified
7407 and then used in remember templates.")
7409 (defun org-add-link-type (type &optional follow export)
7410 "Add TYPE to the list of `org-link-types'.
7411 Re-compute all regular expressions depending on `org-link-types'
7413 FOLLOW and EXPORT are two functions.
7415 FOLLOW should take the link path as the single argument and do whatever
7416 is necessary to follow the link, for example find a file or display
7417 a mail message.
7419 EXPORT should format the link path for export to one of the export formats.
7420 It should be a function accepting three arguments:
7422 path the path of the link, the text after the prefix (like \"http:\")
7423 desc the description of the link, if any, nil if there was no description
7424 format the export format, a symbol like `html' or `latex'.
7426 The function may use the FORMAT information to return different values
7427 depending on the format. The return value will be put literally into
7428 the exported file.
7429 Org-mode has a built-in default for exporting links. If you are happy with
7430 this default, there is no need to define an export function for the link
7431 type. For a simple example of an export function, see `org-bbdb.el'."
7432 (add-to-list 'org-link-types type t)
7433 (org-make-link-regexps)
7434 (if (assoc type org-link-protocols)
7435 (setcdr (assoc type org-link-protocols) (list follow export))
7436 (push (list type follow export) org-link-protocols)))
7438 (defvar org-agenda-buffer-name)
7440 ;;;###autoload
7441 (defun org-store-link (arg)
7442 "\\<org-mode-map>Store an org-link to the current location.
7443 This link is added to `org-stored-links' and can later be inserted
7444 into an org-buffer with \\[org-insert-link].
7446 For some link types, a prefix arg is interpreted:
7447 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7448 For file links, arg negates `org-context-in-file-links'."
7449 (interactive "P")
7450 (org-load-modules-maybe)
7451 (setq org-store-link-plist nil) ; reset
7452 (let ((outline-regexp (org-get-limited-outline-regexp))
7453 link cpltxt desc description search txt custom-id)
7454 (cond
7456 ((run-hook-with-args-until-success 'org-store-link-functions)
7457 (setq link (plist-get org-store-link-plist :link)
7458 desc (or (plist-get org-store-link-plist :description) link)))
7460 ((equal (buffer-name) "*Org Edit Src Example*")
7461 (let (label gc)
7462 (while (or (not label)
7463 (save-excursion
7464 (save-restriction
7465 (widen)
7466 (goto-char (point-min))
7467 (re-search-forward
7468 (regexp-quote (format org-coderef-label-format label))
7469 nil t))))
7470 (when label (message "Label exists already") (sit-for 2))
7471 (setq label (read-string "Code line label: " label)))
7472 (end-of-line 1)
7473 (setq link (format org-coderef-label-format label))
7474 (setq gc (- 79 (length link)))
7475 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7476 (insert link)
7477 (setq link (concat "(" label ")") desc nil)))
7479 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7480 ;; We are in the agenda, link to referenced location
7481 (let ((m (or (get-text-property (point) 'org-hd-marker)
7482 (get-text-property (point) 'org-marker))))
7483 (when m
7484 (org-with-point-at m
7485 (call-interactively 'org-store-link)))))
7487 ((eq major-mode 'calendar-mode)
7488 (let ((cd (calendar-cursor-to-date)))
7489 (setq link
7490 (format-time-string
7491 (car org-time-stamp-formats)
7492 (apply 'encode-time
7493 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7494 nil nil nil))))
7495 (org-store-link-props :type "calendar" :date cd)))
7497 ((eq major-mode 'w3-mode)
7498 (setq cpltxt (if (and (buffer-name)
7499 (not (string-match "Untitled" (buffer-name))))
7500 (buffer-name)
7501 (url-view-url t))
7502 link (org-make-link (url-view-url t)))
7503 (org-store-link-props :type "w3" :url (url-view-url t)))
7505 ((eq major-mode 'w3m-mode)
7506 (setq cpltxt (or w3m-current-title w3m-current-url)
7507 link (org-make-link w3m-current-url))
7508 (org-store-link-props :type "w3m" :url (url-view-url t)))
7510 ((setq search (run-hook-with-args-until-success
7511 'org-create-file-search-functions))
7512 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7513 "::" search))
7514 (setq cpltxt (or description link)))
7516 ((eq major-mode 'image-mode)
7517 (setq cpltxt (concat "file:"
7518 (abbreviate-file-name buffer-file-name))
7519 link (org-make-link cpltxt))
7520 (org-store-link-props :type "image" :file buffer-file-name))
7522 ((eq major-mode 'dired-mode)
7523 ;; link to the file in the current line
7524 (setq cpltxt (concat "file:"
7525 (abbreviate-file-name
7526 (expand-file-name
7527 (dired-get-filename nil t))))
7528 link (org-make-link cpltxt)))
7530 ((and buffer-file-name (org-mode-p))
7531 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7532 (cond
7533 ((org-in-regexp "<<\\(.*?\\)>>")
7534 (setq cpltxt
7535 (concat "file:"
7536 (abbreviate-file-name buffer-file-name)
7537 "::" (match-string 1))
7538 link (org-make-link cpltxt)))
7539 ((and (featurep 'org-id)
7540 (or (eq org-link-to-org-use-id t)
7541 (and (eq org-link-to-org-use-id 'create-if-interactive)
7542 (interactive-p))
7543 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7544 (interactive-p)
7545 (not custom-id))
7546 (and org-link-to-org-use-id
7547 (condition-case nil
7548 (org-entry-get nil "ID")
7549 (error nil)))))
7550 ;; We can make a link using the ID.
7551 (setq link (condition-case nil
7552 (prog1 (org-id-store-link)
7553 (setq desc (plist-get org-store-link-plist
7554 :description)))
7555 (error
7556 ;; probably before first headline, link to file only
7557 (concat "file:"
7558 (abbreviate-file-name buffer-file-name))))))
7560 ;; Just link to current headline
7561 (setq cpltxt (concat "file:"
7562 (abbreviate-file-name buffer-file-name)))
7563 ;; Add a context search string
7564 (when (org-xor org-context-in-file-links arg)
7565 (setq txt (cond
7566 ((org-on-heading-p) nil)
7567 ((org-region-active-p)
7568 (buffer-substring (region-beginning) (region-end)))
7569 (t nil)))
7570 (when (or (null txt) (string-match "\\S-" txt))
7571 (setq cpltxt
7572 (concat cpltxt "::"
7573 (condition-case nil
7574 (org-make-org-heading-search-string txt)
7575 (error "")))
7576 desc (or (nth 4 (ignore-errors
7577 (org-heading-components))) "NONE"))))
7578 (if (string-match "::\\'" cpltxt)
7579 (setq cpltxt (substring cpltxt 0 -2)))
7580 (setq link (org-make-link cpltxt)))))
7582 ((buffer-file-name (buffer-base-buffer))
7583 ;; Just link to this file here.
7584 (setq cpltxt (concat "file:"
7585 (abbreviate-file-name
7586 (buffer-file-name (buffer-base-buffer)))))
7587 ;; Add a context string
7588 (when (org-xor org-context-in-file-links arg)
7589 (setq txt (if (org-region-active-p)
7590 (buffer-substring (region-beginning) (region-end))
7591 (buffer-substring (point-at-bol) (point-at-eol))))
7592 ;; Only use search option if there is some text.
7593 (when (string-match "\\S-" txt)
7594 (setq cpltxt
7595 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7596 desc "NONE")))
7597 (setq link (org-make-link cpltxt)))
7599 ((interactive-p)
7600 (error "Cannot link to a buffer which is not visiting a file"))
7602 (t (setq link nil)))
7604 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7605 (setq link (or link cpltxt)
7606 desc (or desc cpltxt))
7607 (if (equal desc "NONE") (setq desc nil))
7609 (if (and (or (interactive-p) executing-kbd-macro) link)
7610 (progn
7611 (setq org-stored-links
7612 (cons (list link desc) org-stored-links))
7613 (message "Stored: %s" (or desc link))
7614 (when custom-id
7615 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7616 "::#" custom-id))
7617 (setq org-stored-links
7618 (cons (list link desc) org-stored-links))))
7619 (and link (org-make-link-string link desc)))))
7621 (defun org-store-link-props (&rest plist)
7622 "Store link properties, extract names and addresses."
7623 (let (x adr)
7624 (when (setq x (plist-get plist :from))
7625 (setq adr (mail-extract-address-components x))
7626 (setq plist (plist-put plist :fromname (car adr)))
7627 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7628 (when (setq x (plist-get plist :to))
7629 (setq adr (mail-extract-address-components x))
7630 (setq plist (plist-put plist :toname (car adr)))
7631 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7632 (let ((from (plist-get plist :from))
7633 (to (plist-get plist :to)))
7634 (when (and from to org-from-is-user-regexp)
7635 (setq plist
7636 (plist-put plist :fromto
7637 (if (string-match org-from-is-user-regexp from)
7638 (concat "to %t")
7639 (concat "from %f"))))))
7640 (setq org-store-link-plist plist))
7642 (defun org-add-link-props (&rest plist)
7643 "Add these properties to the link property list."
7644 (let (key value)
7645 (while plist
7646 (setq key (pop plist) value (pop plist))
7647 (setq org-store-link-plist
7648 (plist-put org-store-link-plist key value)))))
7650 (defun org-email-link-description (&optional fmt)
7651 "Return the description part of an email link.
7652 This takes information from `org-store-link-plist' and formats it
7653 according to FMT (default from `org-email-link-description-format')."
7654 (setq fmt (or fmt org-email-link-description-format))
7655 (let* ((p org-store-link-plist)
7656 (to (plist-get p :toaddress))
7657 (from (plist-get p :fromaddress))
7658 (table
7659 (list
7660 (cons "%c" (plist-get p :fromto))
7661 (cons "%F" (plist-get p :from))
7662 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7663 (cons "%T" (plist-get p :to))
7664 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7665 (cons "%s" (plist-get p :subject))
7666 (cons "%m" (plist-get p :message-id)))))
7667 (when (string-match "%c" fmt)
7668 ;; Check if the user wrote this message
7669 (if (and org-from-is-user-regexp from to
7670 (save-match-data (string-match org-from-is-user-regexp from)))
7671 (setq fmt (replace-match "to %t" t t fmt))
7672 (setq fmt (replace-match "from %f" t t fmt))))
7673 (org-replace-escapes fmt table)))
7675 (defun org-make-org-heading-search-string (&optional string heading)
7676 "Make search string for STRING or current headline."
7677 (interactive)
7678 (let ((s (or string (org-get-heading))))
7679 (unless (and string (not heading))
7680 ;; We are using a headline, clean up garbage in there.
7681 (if (string-match org-todo-regexp s)
7682 (setq s (replace-match "" t t s)))
7683 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7684 (setq s (replace-match "" t t s)))
7685 (setq s (org-trim s))
7686 (if (string-match (concat "^\\(" org-quote-string "\\|"
7687 org-comment-string "\\)") s)
7688 (setq s (replace-match "" t t s)))
7689 (while (string-match org-ts-regexp s)
7690 (setq s (replace-match "" t t s))))
7691 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7692 (setq s (replace-match " " t t s)))
7693 (or string (setq s (concat "*" s))) ; Add * for headlines
7694 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7696 (defun org-make-link (&rest strings)
7697 "Concatenate STRINGS."
7698 (apply 'concat strings))
7700 (defun org-make-link-string (link &optional description)
7701 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7702 (unless (string-match "\\S-" link)
7703 (error "Empty link"))
7704 (when (stringp description)
7705 ;; Remove brackets from the description, they are fatal.
7706 (while (string-match "\\[" description)
7707 (setq description (replace-match "{" t t description)))
7708 (while (string-match "\\]" description)
7709 (setq description (replace-match "}" t t description))))
7710 (when (equal (org-link-escape link) description)
7711 ;; No description needed, it is identical
7712 (setq description nil))
7713 (when (and (not description)
7714 (not (equal link (org-link-escape link))))
7715 (setq description (org-extract-attributes link)))
7716 (concat "[[" (org-link-escape link) "]"
7717 (if description (concat "[" description "]") "")
7718 "]"))
7720 (defconst org-link-escape-chars
7721 '((?\ . "%20")
7722 (?\[ . "%5B")
7723 (?\] . "%5D")
7724 (?\340 . "%E0") ; `a
7725 (?\342 . "%E2") ; ^a
7726 (?\347 . "%E7") ; ,c
7727 (?\350 . "%E8") ; `e
7728 (?\351 . "%E9") ; 'e
7729 (?\352 . "%EA") ; ^e
7730 (?\356 . "%EE") ; ^i
7731 (?\364 . "%F4") ; ^o
7732 (?\371 . "%F9") ; `u
7733 (?\373 . "%FB") ; ^u
7734 (?\; . "%3B")
7735 (?? . "%3F")
7736 (?= . "%3D")
7737 (?+ . "%2B")
7739 "Association list of escapes for some characters problematic in links.
7740 This is the list that is used for internal purposes.")
7742 (defvar org-url-encoding-use-url-hexify nil)
7744 (defconst org-link-escape-chars-browser
7745 '((?\ . "%20")) ; 32 for the SPC char
7746 "Association list of escapes for some characters problematic in links.
7747 This is the list that is used before handing over to the browser.")
7749 (defun org-link-escape (text &optional table)
7750 "Escape characters in TEXT that are problematic for links."
7751 (if org-url-encoding-use-url-hexify
7752 (url-hexify-string text)
7753 (setq table (or table org-link-escape-chars))
7754 (when text
7755 (let ((re (mapconcat (lambda (x) (regexp-quote
7756 (char-to-string (car x))))
7757 table "\\|")))
7758 (while (string-match re text)
7759 (setq text
7760 (replace-match
7761 (cdr (assoc (string-to-char (match-string 0 text))
7762 table))
7763 t t text)))
7764 text))))
7766 (defun org-link-unescape (text &optional table)
7767 "Reverse the action of `org-link-escape'."
7768 (if org-url-encoding-use-url-hexify
7769 (url-unhex-string text)
7770 (setq table (or table org-link-escape-chars))
7771 (when text
7772 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7773 table "\\|")))
7774 (while (string-match re text)
7775 (setq text
7776 (replace-match
7777 (char-to-string (car (rassoc (match-string 0 text) table)))
7778 t t text)))
7779 text))))
7781 (defun org-xor (a b)
7782 "Exclusive or."
7783 (if a (not b) b))
7785 (defun org-fixup-message-id-for-http (s)
7786 "Replace special characters in a message id, so it can be used in an http query."
7787 (while (string-match "<" s)
7788 (setq s (replace-match "%3C" t t s)))
7789 (while (string-match ">" s)
7790 (setq s (replace-match "%3E" t t s)))
7791 (while (string-match "@" s)
7792 (setq s (replace-match "%40" t t s)))
7795 ;;;###autoload
7796 (defun org-insert-link-global ()
7797 "Insert a link like Org-mode does.
7798 This command can be called in any mode to insert a link in Org-mode syntax."
7799 (interactive)
7800 (org-load-modules-maybe)
7801 (org-run-like-in-org-mode 'org-insert-link))
7803 (defun org-insert-link (&optional complete-file link-location)
7804 "Insert a link. At the prompt, enter the link.
7806 Completion can be used to insert any of the link protocol prefixes like
7807 http or ftp in use.
7809 The history can be used to select a link previously stored with
7810 `org-store-link'. When the empty string is entered (i.e. if you just
7811 press RET at the prompt), the link defaults to the most recently
7812 stored link. As SPC triggers completion in the minibuffer, you need to
7813 use M-SPC or C-q SPC to force the insertion of a space character.
7815 You will also be prompted for a description, and if one is given, it will
7816 be displayed in the buffer instead of the link.
7818 If there is already a link at point, this command will allow you to edit link
7819 and description parts.
7821 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7822 be selected using completion. The path to the file will be relative to the
7823 current directory if the file is in the current directory or a subdirectory.
7824 Otherwise, the link will be the absolute path as completed in the minibuffer
7825 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7826 option `org-link-file-path-type'.
7828 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7829 the current directory or below.
7831 With three \\[universal-argument] prefixes, negate the meaning of
7832 `org-keep-stored-link-after-insertion'.
7834 If `org-make-link-description-function' is non-nil, this function will be
7835 called with the link target, and the result will be the default
7836 link description.
7838 If the LINK-LOCATION parameter is non-nil, this value will be
7839 used as the link location instead of reading one interactively."
7840 (interactive "P")
7841 (let* ((wcf (current-window-configuration))
7842 (region (if (org-region-active-p)
7843 (buffer-substring (region-beginning) (region-end))))
7844 (remove (and region (list (region-beginning) (region-end))))
7845 (desc region)
7846 tmphist ; byte-compile incorrectly complains about this
7847 (link link-location)
7848 entry file all-prefixes)
7849 (cond
7850 (link-location) ; specified by arg, just use it.
7851 ((org-in-regexp org-bracket-link-regexp 1)
7852 ;; We do have a link at point, and we are going to edit it.
7853 (setq remove (list (match-beginning 0) (match-end 0)))
7854 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7855 (setq link (read-string "Link: "
7856 (org-link-unescape
7857 (org-match-string-no-properties 1)))))
7858 ((or (org-in-regexp org-angle-link-re)
7859 (org-in-regexp org-plain-link-re))
7860 ;; Convert to bracket link
7861 (setq remove (list (match-beginning 0) (match-end 0))
7862 link (read-string "Link: "
7863 (org-remove-angle-brackets (match-string 0)))))
7864 ((member complete-file '((4) (16)))
7865 ;; Completing read for file names.
7866 (setq link (org-file-complete-link complete-file)))
7868 ;; Read link, with completion for stored links.
7869 (with-output-to-temp-buffer "*Org Links*"
7870 (princ "Insert a link.
7871 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7872 (when org-stored-links
7873 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7874 (princ (mapconcat
7875 (lambda (x)
7876 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7877 (reverse org-stored-links) "\n"))))
7878 (let ((cw (selected-window)))
7879 (select-window (get-buffer-window "*Org Links*"))
7880 (setq truncate-lines t)
7881 (unless (pos-visible-in-window-p (point-max))
7882 (org-fit-window-to-buffer))
7883 (and (window-live-p cw) (select-window cw)))
7884 ;; Fake a link history, containing the stored links.
7885 (setq tmphist (append (mapcar 'car org-stored-links)
7886 org-insert-link-history))
7887 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7888 (mapcar 'car org-link-abbrev-alist)
7889 org-link-types))
7890 (unwind-protect
7891 (progn
7892 (setq link
7893 (let ((org-completion-use-ido nil)
7894 (org-completion-use-iswitchb nil))
7895 (org-completing-read
7896 "Link: "
7897 (append
7898 (mapcar (lambda (x) (list (concat x ":")))
7899 all-prefixes)
7900 (mapcar 'car org-stored-links))
7901 nil nil nil
7902 'tmphist
7903 (car (car org-stored-links)))))
7904 (if (or (member link all-prefixes)
7905 (and (equal ":" (substring link -1))
7906 (member (substring link 0 -1) all-prefixes)
7907 (setq link (substring link 0 -1))))
7908 (setq link (org-link-try-special-completion link))))
7909 (set-window-configuration wcf)
7910 (kill-buffer "*Org Links*"))
7911 (setq entry (assoc link org-stored-links))
7912 (or entry (push link org-insert-link-history))
7913 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7914 (not org-keep-stored-link-after-insertion))
7915 (setq org-stored-links (delq (assoc link org-stored-links)
7916 org-stored-links)))
7917 (setq desc (or desc (nth 1 entry)))))
7919 (if (string-match org-plain-link-re link)
7920 ;; URL-like link, normalize the use of angular brackets.
7921 (setq link (org-make-link (org-remove-angle-brackets link))))
7923 ;; Check if we are linking to the current file with a search option
7924 ;; If yes, simplify the link by using only the search option.
7925 (when (and buffer-file-name
7926 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7927 (let* ((path (match-string 1 link))
7928 (case-fold-search nil)
7929 (search (match-string 2 link)))
7930 (save-match-data
7931 (if (equal (file-truename buffer-file-name) (file-truename path))
7932 ;; We are linking to this same file, with a search option
7933 (setq link search)))))
7935 ;; Check if we can/should use a relative path. If yes, simplify the link
7936 (when (string-match "^file:\\(.*\\)" link)
7937 (let* ((path (match-string 1 link))
7938 (origpath path)
7939 (case-fold-search nil))
7940 (cond
7941 ((or (eq org-link-file-path-type 'absolute)
7942 (equal complete-file '(16)))
7943 (setq path (abbreviate-file-name (expand-file-name path))))
7944 ((eq org-link-file-path-type 'noabbrev)
7945 (setq path (expand-file-name path)))
7946 ((eq org-link-file-path-type 'relative)
7947 (setq path (file-relative-name path)))
7949 (save-match-data
7950 (if (string-match (concat "^" (regexp-quote
7951 (file-name-as-directory
7952 (expand-file-name "."))))
7953 (expand-file-name path))
7954 ;; We are linking a file with relative path name.
7955 (setq path (substring (expand-file-name path)
7956 (match-end 0)))
7957 (setq path (abbreviate-file-name (expand-file-name path)))))))
7958 (setq link (concat "file:" path))
7959 (if (equal desc origpath)
7960 (setq desc path))))
7962 (if org-make-link-description-function
7963 (setq desc (funcall org-make-link-description-function link desc)))
7965 (setq desc (read-string "Description: " desc))
7966 (unless (string-match "\\S-" desc) (setq desc nil))
7967 (if remove (apply 'delete-region remove))
7968 (insert (org-make-link-string link desc))))
7970 (defun org-link-try-special-completion (type)
7971 "If there is completion support for link type TYPE, offer it."
7972 (let ((fun (intern (concat "org-" type "-complete-link"))))
7973 (if (functionp fun)
7974 (funcall fun)
7975 (read-string "Link (no completion support): " (concat type ":")))))
7977 (defun org-file-complete-link (&optional arg)
7978 "Create a file link using completion."
7979 (let (file link)
7980 (setq file (read-file-name "File: "))
7981 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7982 (pwd1 (file-name-as-directory (abbreviate-file-name
7983 (expand-file-name ".")))))
7984 (cond
7985 ((equal arg '(16))
7986 (setq link (org-make-link
7987 "file:"
7988 (abbreviate-file-name (expand-file-name file)))))
7989 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7990 (setq link (org-make-link "file:" (match-string 1 file))))
7991 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7992 (expand-file-name file))
7993 (setq link (org-make-link
7994 "file:" (match-string 1 (expand-file-name file)))))
7995 (t (setq link (org-make-link "file:" file)))))
7996 link))
7998 (defun org-completing-read (&rest args)
7999 "Completing-read with SPACE being a normal character."
8000 (let ((minibuffer-local-completion-map
8001 (copy-keymap minibuffer-local-completion-map)))
8002 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8003 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8004 (apply 'org-icompleting-read args)))
8006 (defun org-completing-read-no-i (&rest args)
8007 (let (org-completion-use-ido org-completion-use-iswitchb)
8008 (apply 'org-completing-read args)))
8010 (defun org-iswitchb-completing-read (prompt choices &rest args)
8011 "Use iswitch as a completing-read replacement to choose from choices.
8012 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8013 from."
8014 (let* ((iswitchb-use-virtual-buffers nil)
8015 (iswitchb-make-buflist-hook
8016 (lambda ()
8017 (setq iswitchb-temp-buflist choices))))
8018 (iswitchb-read-buffer prompt)))
8020 (defun org-icompleting-read (&rest args)
8021 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8022 (org-without-partial-completion
8023 (if (and org-completion-use-ido
8024 (fboundp 'ido-completing-read)
8025 (boundp 'ido-mode) ido-mode
8026 (listp (second args)))
8027 (let ((ido-enter-matching-directory nil))
8028 (apply 'ido-completing-read (concat (car args))
8029 (if (consp (car (nth 1 args)))
8030 (mapcar (lambda (x) (car x)) (nth 1 args))
8031 (nth 1 args))
8032 (cddr args)))
8033 (if (and org-completion-use-iswitchb
8034 (boundp 'iswitchb-mode) iswitchb-mode
8035 (listp (second args)))
8036 (apply 'org-iswitchb-completing-read (concat (car args))
8037 (if (consp (car (nth 1 args)))
8038 (mapcar (lambda (x) (car x)) (nth 1 args))
8039 (nth 1 args))
8040 (cddr args))
8041 (apply 'completing-read args)))))
8043 (defun org-extract-attributes (s)
8044 "Extract the attributes cookie from a string and set as text property."
8045 (let (a attr (start 0) key value)
8046 (save-match-data
8047 (when (string-match "{{\\([^}]+\\)}}$" s)
8048 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8049 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8050 (setq key (match-string 1 a) value (match-string 2 a)
8051 start (match-end 0)
8052 attr (plist-put attr (intern key) value))))
8053 (org-add-props s nil 'org-attr attr))
8056 (defun org-extract-attributes-from-string (tag)
8057 (let (key value attr)
8058 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8059 (setq key (match-string 1 tag) value (match-string 2 tag)
8060 tag (replace-match "" t t tag)
8061 attr (plist-put attr (intern key) value)))
8062 (cons tag attr)))
8064 (defun org-attributes-to-string (plist)
8065 "Format a property list into an HTML attribute list."
8066 (let ((s "") key value)
8067 (while plist
8068 (setq key (pop plist) value (pop plist))
8069 (and value
8070 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8073 ;;; Opening/following a link
8075 (defvar org-link-search-failed nil)
8077 (defun org-next-link ()
8078 "Move forward to the next link.
8079 If the link is in hidden text, expose it."
8080 (interactive)
8081 (when (and org-link-search-failed (eq this-command last-command))
8082 (goto-char (point-min))
8083 (message "Link search wrapped back to beginning of buffer"))
8084 (setq org-link-search-failed nil)
8085 (let* ((pos (point))
8086 (ct (org-context))
8087 (a (assoc :link ct)))
8088 (if a (goto-char (nth 2 a)))
8089 (if (re-search-forward org-any-link-re nil t)
8090 (progn
8091 (goto-char (match-beginning 0))
8092 (if (org-invisible-p) (org-show-context)))
8093 (goto-char pos)
8094 (setq org-link-search-failed t)
8095 (error "No further link found"))))
8097 (defun org-previous-link ()
8098 "Move backward to the previous link.
8099 If the link is in hidden text, expose it."
8100 (interactive)
8101 (when (and org-link-search-failed (eq this-command last-command))
8102 (goto-char (point-max))
8103 (message "Link search wrapped back to end of buffer"))
8104 (setq org-link-search-failed nil)
8105 (let* ((pos (point))
8106 (ct (org-context))
8107 (a (assoc :link ct)))
8108 (if a (goto-char (nth 1 a)))
8109 (if (re-search-backward org-any-link-re nil t)
8110 (progn
8111 (goto-char (match-beginning 0))
8112 (if (org-invisible-p) (org-show-context)))
8113 (goto-char pos)
8114 (setq org-link-search-failed t)
8115 (error "No further link found"))))
8117 (defun org-translate-link (s)
8118 "Translate a link string if a translation function has been defined."
8119 (if (and org-link-translation-function
8120 (fboundp org-link-translation-function)
8121 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8122 (progn
8123 (setq s (funcall org-link-translation-function
8124 (match-string 1) (match-string 2)))
8125 (concat (car s) ":" (cdr s)))
8128 (defun org-translate-link-from-planner (type path)
8129 "Translate a link from Emacs Planner syntax so that Org can follow it.
8130 This is still an experimental function, your mileage may vary."
8131 (cond
8132 ((member type '("http" "https" "news" "ftp"))
8133 ;; standard Internet links are the same.
8134 nil)
8135 ((and (equal type "irc") (string-match "^//" path))
8136 ;; Planner has two / at the beginning of an irc link, we have 1.
8137 ;; We should have zero, actually....
8138 (setq path (substring path 1)))
8139 ((and (equal type "lisp") (string-match "^/" path))
8140 ;; Planner has a slash, we do not.
8141 (setq type "elisp" path (substring path 1)))
8142 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8143 ;; A typical message link. Planner has the id after the final slash,
8144 ;; we separate it with a hash mark
8145 (setq path (concat (match-string 1 path) "#"
8146 (org-remove-angle-brackets (match-string 2 path)))))
8148 (cons type path))
8150 (defun org-find-file-at-mouse (ev)
8151 "Open file link or URL at mouse."
8152 (interactive "e")
8153 (mouse-set-point ev)
8154 (org-open-at-point 'in-emacs))
8156 (defun org-open-at-mouse (ev)
8157 "Open file link or URL at mouse."
8158 (interactive "e")
8159 (mouse-set-point ev)
8160 (if (eq major-mode 'org-agenda-mode)
8161 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8162 (org-open-at-point))
8164 (defvar org-window-config-before-follow-link nil
8165 "The window configuration before following a link.
8166 This is saved in case the need arises to restore it.")
8168 (defvar org-open-link-marker (make-marker)
8169 "Marker pointing to the location where `org-open-at-point; was called.")
8171 ;;;###autoload
8172 (defun org-open-at-point-global ()
8173 "Follow a link like Org-mode does.
8174 This command can be called in any mode to follow a link that has
8175 Org-mode syntax."
8176 (interactive)
8177 (org-run-like-in-org-mode 'org-open-at-point))
8179 ;;;###autoload
8180 (defun org-open-link-from-string (s &optional arg reference-buffer)
8181 "Open a link in the string S, as if it was in Org-mode."
8182 (interactive "sLink: \nP")
8183 (let ((reference-buffer (or reference-buffer (current-buffer))))
8184 (with-temp-buffer
8185 (let ((org-inhibit-startup t))
8186 (org-mode)
8187 (insert s)
8188 (goto-char (point-min))
8189 (org-open-at-point arg reference-buffer)))))
8191 (defun org-open-at-point (&optional in-emacs reference-buffer)
8192 "Open link at or after point.
8193 If there is no link at point, this function will search forward up to
8194 the end of the current line.
8195 Normally, files will be opened by an appropriate application. If the
8196 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8197 With a double prefix argument, try to open outside of Emacs, in the
8198 application the system uses for this file type."
8199 (interactive "P")
8200 (org-load-modules-maybe)
8201 (move-marker org-open-link-marker (point))
8202 (setq org-window-config-before-follow-link (current-window-configuration))
8203 (org-remove-occur-highlights nil nil t)
8204 (cond
8205 ((and (org-on-heading-p)
8206 (not (org-in-regexp
8207 (concat org-plain-link-re "\\|"
8208 org-bracket-link-regexp "\\|"
8209 org-angle-link-re "\\|"
8210 "[ \t]:[^ \t\n]+:[ \t]*$"))))
8211 (or (org-offer-links-in-entry in-emacs)
8212 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8213 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8214 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8215 (org-footnote-action))
8217 (let (type path link line search (pos (point)))
8218 (catch 'match
8219 (save-excursion
8220 (skip-chars-forward "^]\n\r")
8221 (when (org-in-regexp org-bracket-link-regexp)
8222 (setq link (org-extract-attributes
8223 (org-link-unescape (org-match-string-no-properties 1))))
8224 (while (string-match " *\n *" link)
8225 (setq link (replace-match " " t t link)))
8226 (setq link (org-link-expand-abbrev link))
8227 (cond
8228 ((or (file-name-absolute-p link)
8229 (string-match "^\\.\\.?/" link))
8230 (setq type "file" path link))
8231 ((string-match org-link-re-with-space3 link)
8232 (setq type (match-string 1 link) path (match-string 2 link)))
8233 (t (setq type "thisfile" path link)))
8234 (throw 'match t)))
8236 (when (get-text-property (point) 'org-linked-text)
8237 (setq type "thisfile"
8238 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8239 (1+ (point)) (point))
8240 path (buffer-substring
8241 (previous-single-property-change pos 'org-linked-text)
8242 (next-single-property-change pos 'org-linked-text)))
8243 (throw 'match t))
8245 (save-excursion
8246 (when (or (org-in-regexp org-angle-link-re)
8247 (org-in-regexp org-plain-link-re))
8248 (setq type (match-string 1) path (match-string 2))
8249 (throw 'match t)))
8250 (save-excursion
8251 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8252 (setq type "tags"
8253 path (match-string 1))
8254 (while (string-match ":" path)
8255 (setq path (replace-match "+" t t path)))
8256 (throw 'match t)))
8257 (when (org-in-regexp "<\\([^><\n]+\\)>")
8258 (setq type "tree-match"
8259 path (match-string 1))
8260 (throw 'match t)))
8261 (unless path
8262 (error "No link found"))
8264 ;; switch back to reference buffer
8265 ;; needed when if called in a temporary buffer through
8266 ;; org-open-link-from-string
8267 (with-current-buffer (or reference-buffer (current-buffer))
8269 ;; Remove any trailing spaces in path
8270 (if (string-match " +\\'" path)
8271 (setq path (replace-match "" t t path)))
8272 (if (and org-link-translation-function
8273 (fboundp org-link-translation-function))
8274 ;; Check if we need to translate the link
8275 (let ((tmp (funcall org-link-translation-function type path)))
8276 (setq type (car tmp) path (cdr tmp))))
8278 (cond
8280 ((assoc type org-link-protocols)
8281 (funcall (nth 1 (assoc type org-link-protocols)) path))
8283 ((equal type "mailto")
8284 (let ((cmd (car org-link-mailto-program))
8285 (args (cdr org-link-mailto-program)) args1
8286 (address path) (subject "") a)
8287 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8288 (setq address (match-string 1 path)
8289 subject (org-link-escape (match-string 2 path))))
8290 (while args
8291 (cond
8292 ((not (stringp (car args))) (push (pop args) args1))
8293 (t (setq a (pop args))
8294 (if (string-match "%a" a)
8295 (setq a (replace-match address t t a)))
8296 (if (string-match "%s" a)
8297 (setq a (replace-match subject t t a)))
8298 (push a args1))))
8299 (apply cmd (nreverse args1))))
8301 ((member type '("http" "https" "ftp" "news"))
8302 (browse-url (concat type ":" (org-link-escape
8303 path org-link-escape-chars-browser))))
8305 ((member type '("message"))
8306 (browse-url (concat type ":" path)))
8308 ((string= type "tags")
8309 (org-tags-view in-emacs path))
8310 ((string= type "thisfile")
8311 (if in-emacs
8312 (switch-to-buffer-other-window
8313 (org-get-buffer-for-internal-link (current-buffer)))
8314 (org-mark-ring-push))
8315 (let ((cmd `(org-link-search
8316 ,path
8317 ,(cond ((equal in-emacs '(4)) 'occur)
8318 ((equal in-emacs '(16)) 'org-occur)
8319 (t nil))
8320 ,pos)))
8321 (condition-case nil (eval cmd)
8322 (error (progn (widen) (eval cmd))))))
8324 ((string= type "tree-match")
8325 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8327 ((string= type "file")
8328 (if (string-match "::\\([0-9]+\\)\\'" path)
8329 (setq line (string-to-number (match-string 1 path))
8330 path (substring path 0 (match-beginning 0)))
8331 (if (string-match "::\\(.+\\)\\'" path)
8332 (setq search (match-string 1 path)
8333 path (substring path 0 (match-beginning 0)))))
8334 (if (string-match "[*?{]" (file-name-nondirectory path))
8335 (dired path)
8336 (org-open-file path in-emacs line search)))
8338 ((string= type "news")
8339 (require 'org-gnus)
8340 (org-gnus-follow-link path))
8342 ((string= type "shell")
8343 (let ((cmd path))
8344 (if (or (not org-confirm-shell-link-function)
8345 (funcall org-confirm-shell-link-function
8346 (format "Execute \"%s\" in shell? "
8347 (org-add-props cmd nil
8348 'face 'org-warning))))
8349 (progn
8350 (message "Executing %s" cmd)
8351 (shell-command cmd))
8352 (error "Abort"))))
8354 ((string= type "elisp")
8355 (let ((cmd path))
8356 (if (or (not org-confirm-elisp-link-function)
8357 (funcall org-confirm-elisp-link-function
8358 (format "Execute \"%s\" as elisp? "
8359 (org-add-props cmd nil
8360 'face 'org-warning))))
8361 (message "%s => %s" cmd
8362 (if (equal (string-to-char cmd) ?\()
8363 (eval (read cmd))
8364 (call-interactively (read cmd))))
8365 (error "Abort"))))
8368 (browse-url-at-point)))))))
8369 (move-marker org-open-link-marker nil)
8370 (run-hook-with-args 'org-follow-link-hook))
8372 (defun org-offer-links-in-entry (&optional nth zero)
8373 "Offer links in the current entry and follow the selected link.
8374 If there is only one link, follow it immediately as well.
8375 If NTH is an integer, immediately pick the NTH link found.
8376 If ZERO is a string, check also this string for a link, and if
8377 there is one, offer it as link number zero."
8378 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8379 "\\(" org-angle-link-re "\\)\\|"
8380 "\\(" org-plain-link-re "\\)"))
8381 (cnt ?0)
8382 (in-emacs (if (integerp nth) nil nth))
8383 have-zero end links link c)
8384 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8385 (push (match-string 0 zero) links)
8386 (setq cnt (1- cnt) have-zero t))
8387 (save-excursion
8388 (org-back-to-heading t)
8389 (setq end (save-excursion (outline-next-heading) (point)))
8390 (while (re-search-forward re end t)
8391 (push (match-string 0) links))
8392 (setq links (org-uniquify (reverse links))))
8394 (cond
8395 ((null links)
8396 (message "No links"))
8397 ((equal (length links) 1)
8398 (setq link (car links)))
8399 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8400 (setq link (nth (if have-zero nth (1- nth)) links)))
8401 (t ; we have to select a link
8402 (save-excursion
8403 (save-window-excursion
8404 (delete-other-windows)
8405 (with-output-to-temp-buffer "*Select Link*"
8406 (mapc (lambda (l)
8407 (if (not (string-match org-bracket-link-regexp l))
8408 (princ (format "[%c] %s\n" (incf cnt)
8409 (org-remove-angle-brackets l)))
8410 (if (match-end 3)
8411 (princ (format "[%c] %s (%s)\n" (incf cnt)
8412 (match-string 3 l) (match-string 1 l)))
8413 (princ (format "[%c] %s\n" (incf cnt)
8414 (match-string 1 l))))))
8415 links))
8416 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8417 (message "Select link to open:")
8418 (setq c (read-char-exclusive))
8419 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8420 (when (equal c ?q) (error "Abort"))
8421 (setq nth (- c ?0))
8422 (if have-zero (setq nth (1+ nth)))
8423 (unless (and (integerp nth) (>= (length links) nth))
8424 (error "Invalid link selection"))
8425 (setq link (nth (1- nth) links))))
8426 (if link
8427 (progn (org-open-link-from-string link in-emacs (current-buffer)) t)
8428 nil)))
8430 ;;;; Time estimates
8432 (defun org-get-effort (&optional pom)
8433 "Get the effort estimate for the current entry."
8434 (org-entry-get pom org-effort-property))
8436 ;;; File search
8438 (defvar org-create-file-search-functions nil
8439 "List of functions to construct the right search string for a file link.
8440 These functions are called in turn with point at the location to
8441 which the link should point.
8443 A function in the hook should first test if it would like to
8444 handle this file type, for example by checking the major-mode or
8445 the file extension. If it decides not to handle this file, it
8446 should just return nil to give other functions a chance. If it
8447 does handle the file, it must return the search string to be used
8448 when following the link. The search string will be part of the
8449 file link, given after a double colon, and `org-open-at-point'
8450 will automatically search for it. If special measures must be
8451 taken to make the search successful, another function should be
8452 added to the companion hook `org-execute-file-search-functions',
8453 which see.
8455 A function in this hook may also use `setq' to set the variable
8456 `description' to provide a suggestion for the descriptive text to
8457 be used for this link when it gets inserted into an Org-mode
8458 buffer with \\[org-insert-link].")
8460 (defvar org-execute-file-search-functions nil
8461 "List of functions to execute a file search triggered by a link.
8463 Functions added to this hook must accept a single argument, the
8464 search string that was part of the file link, the part after the
8465 double colon. The function must first check if it would like to
8466 handle this search, for example by checking the major-mode or the
8467 file extension. If it decides not to handle this search, it
8468 should just return nil to give other functions a chance. If it
8469 does handle the search, it must return a non-nil value to keep
8470 other functions from trying.
8472 Each function can access the current prefix argument through the
8473 variable `current-prefix-argument'. Note that a single prefix is
8474 used to force opening a link in Emacs, so it may be good to only
8475 use a numeric or double prefix to guide the search function.
8477 In case this is needed, a function in this hook can also restore
8478 the window configuration before `org-open-at-point' was called using:
8480 (set-window-configuration org-window-config-before-follow-link)")
8482 (defun org-link-search (s &optional type avoid-pos)
8483 "Search for a link search option.
8484 If S is surrounded by forward slashes, it is interpreted as a
8485 regular expression. In org-mode files, this will create an `org-occur'
8486 sparse tree. In ordinary files, `occur' will be used to list matches.
8487 If the current buffer is in `dired-mode', grep will be used to search
8488 in all files. If AVOID-POS is given, ignore matches near that position."
8489 (let ((case-fold-search t)
8490 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8491 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8492 (append '(("") (" ") ("\t") ("\n"))
8493 org-emphasis-alist)
8494 "\\|") "\\)"))
8495 (pos (point))
8496 (pre nil) (post nil)
8497 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8498 (cond
8499 ;; First check if there are any special
8500 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8501 ;; Now try the builtin stuff
8502 ((and (equal (string-to-char s0) ?#)
8503 (> (length s0) 1)
8504 (save-excursion
8505 (goto-char (point-min))
8506 (and
8507 (re-search-forward
8508 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8509 (setq type 'dedicated
8510 pos (match-beginning 0))))
8511 ;; There is an exact target for this
8512 (goto-char pos)
8513 (org-back-to-heading t)))
8514 ((save-excursion
8515 (goto-char (point-min))
8516 (and
8517 (re-search-forward
8518 (concat "<<" (regexp-quote s0) ">>") nil t)
8519 (setq type 'dedicated
8520 pos (match-beginning 0))))
8521 ;; There is an exact target for this
8522 (goto-char pos))
8523 ((and (string-match "^(\\(.*\\))$" s0)
8524 (save-excursion
8525 (goto-char (point-min))
8526 (and
8527 (re-search-forward
8528 (concat "[^[]" (regexp-quote
8529 (format org-coderef-label-format
8530 (match-string 1 s0))))
8531 nil t)
8532 (setq type 'dedicated
8533 pos (1+ (match-beginning 0))))))
8534 ;; There is a coderef target for this
8535 (goto-char pos))
8536 ((string-match "^/\\(.*\\)/$" s)
8537 ;; A regular expression
8538 (cond
8539 ((org-mode-p)
8540 (org-occur (match-string 1 s)))
8541 ;;((eq major-mode 'dired-mode)
8542 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8543 (t (org-do-occur (match-string 1 s)))))
8545 ;; A normal search strings
8546 (when (equal (string-to-char s) ?*)
8547 ;; Anchor on headlines, post may include tags.
8548 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8549 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8550 s (substring s 1)))
8551 (remove-text-properties
8552 0 (length s)
8553 '(face nil mouse-face nil keymap nil fontified nil) s)
8554 ;; Make a series of regular expressions to find a match
8555 (setq words (org-split-string s "[ \n\r\t]+")
8557 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8558 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8559 "\\)" markers)
8560 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8561 re2a (concat "[ \t\r\n]" re2a_)
8562 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8563 re4 (concat "[^a-zA-Z_]" re4_)
8565 re1 (concat pre re2 post)
8566 re3 (concat pre (if pre re4_ re4) post)
8567 re5 (concat pre ".*" re4)
8568 re2 (concat pre re2)
8569 re2a (concat pre (if pre re2a_ re2a))
8570 re4 (concat pre (if pre re4_ re4))
8571 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8572 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8573 re5 "\\)"
8575 (cond
8576 ((eq type 'org-occur) (org-occur reall))
8577 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8578 (t (goto-char (point-min))
8579 (setq type 'fuzzy)
8580 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8581 (org-search-not-self 1 re1 nil t)
8582 (org-search-not-self 1 re2 nil t)
8583 (org-search-not-self 1 re2a nil t)
8584 (org-search-not-self 1 re3 nil t)
8585 (org-search-not-self 1 re4 nil t)
8586 (org-search-not-self 1 re5 nil t)
8588 (goto-char (match-beginning 1))
8589 (goto-char pos)
8590 (error "No match")))))
8592 ;; Normal string-search
8593 (goto-char (point-min))
8594 (if (search-forward s nil t)
8595 (goto-char (match-beginning 0))
8596 (error "No match"))))
8597 (and (org-mode-p) (org-show-context 'link-search))
8598 type))
8600 (defun org-search-not-self (group &rest args)
8601 "Execute `re-search-forward', but only accept matches that do not
8602 enclose the position of `org-open-link-marker'."
8603 (let ((m org-open-link-marker))
8604 (catch 'exit
8605 (while (apply 're-search-forward args)
8606 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8607 (goto-char (match-end group))
8608 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8609 (> (match-beginning 0) (marker-position m))
8610 (< (match-end 0) (marker-position m)))
8611 (save-match-data
8612 (or (not (org-in-regexp
8613 org-bracket-link-analytic-regexp 1))
8614 (not (match-end 4)) ; no description
8615 (and (<= (match-beginning 4) (point))
8616 (>= (match-end 4) (point))))))
8617 (throw 'exit (point))))))))
8619 (defun org-get-buffer-for-internal-link (buffer)
8620 "Return a buffer to be used for displaying the link target of internal links."
8621 (cond
8622 ((not org-display-internal-link-with-indirect-buffer)
8623 buffer)
8624 ((string-match "(Clone)$" (buffer-name buffer))
8625 (message "Buffer is already a clone, not making another one")
8626 ;; we also do not modify visibility in this case
8627 buffer)
8628 (t ; make a new indirect buffer for displaying the link
8629 (let* ((bn (buffer-name buffer))
8630 (ibn (concat bn "(Clone)"))
8631 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8632 (with-current-buffer ib (org-overview))
8633 ib))))
8635 (defun org-do-occur (regexp &optional cleanup)
8636 "Call the Emacs command `occur'.
8637 If CLEANUP is non-nil, remove the printout of the regular expression
8638 in the *Occur* buffer. This is useful if the regex is long and not useful
8639 to read."
8640 (occur regexp)
8641 (when cleanup
8642 (let ((cwin (selected-window)) win beg end)
8643 (when (setq win (get-buffer-window "*Occur*"))
8644 (select-window win))
8645 (goto-char (point-min))
8646 (when (re-search-forward "match[a-z]+" nil t)
8647 (setq beg (match-end 0))
8648 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8649 (setq end (1- (match-beginning 0)))))
8650 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8651 (goto-char (point-min))
8652 (select-window cwin))))
8654 ;;; The mark ring for links jumps
8656 (defvar org-mark-ring nil
8657 "Mark ring for positions before jumps in Org-mode.")
8658 (defvar org-mark-ring-last-goto nil
8659 "Last position in the mark ring used to go back.")
8660 ;; Fill and close the ring
8661 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8662 (loop for i from 1 to org-mark-ring-length do
8663 (push (make-marker) org-mark-ring))
8664 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8665 org-mark-ring)
8667 (defun org-mark-ring-push (&optional pos buffer)
8668 "Put the current position or POS into the mark ring and rotate it."
8669 (interactive)
8670 (setq pos (or pos (point)))
8671 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8672 (move-marker (car org-mark-ring)
8673 (or pos (point))
8674 (or buffer (current-buffer)))
8675 (message "%s"
8676 (substitute-command-keys
8677 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8679 (defun org-mark-ring-goto (&optional n)
8680 "Jump to the previous position in the mark ring.
8681 With prefix arg N, jump back that many stored positions. When
8682 called several times in succession, walk through the entire ring.
8683 Org-mode commands jumping to a different position in the current file,
8684 or to another Org-mode file, automatically push the old position
8685 onto the ring."
8686 (interactive "p")
8687 (let (p m)
8688 (if (eq last-command this-command)
8689 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8690 (setq p org-mark-ring))
8691 (setq org-mark-ring-last-goto p)
8692 (setq m (car p))
8693 (switch-to-buffer (marker-buffer m))
8694 (goto-char m)
8695 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8697 (defun org-remove-angle-brackets (s)
8698 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8699 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8701 (defun org-add-angle-brackets (s)
8702 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8703 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8705 (defun org-remove-double-quotes (s)
8706 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8707 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8710 ;;; Following specific links
8712 (defun org-follow-timestamp-link ()
8713 (cond
8714 ((org-at-date-range-p t)
8715 (let ((org-agenda-start-on-weekday)
8716 (t1 (match-string 1))
8717 (t2 (match-string 2)))
8718 (setq t1 (time-to-days (org-time-string-to-time t1))
8719 t2 (time-to-days (org-time-string-to-time t2)))
8720 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8721 ((org-at-timestamp-p t)
8722 (org-agenda-list nil (time-to-days (org-time-string-to-time
8723 (substring (match-string 1) 0 10)))
8725 (t (error "This should not happen"))))
8728 ;;; Following file links
8729 (defvar org-wait nil)
8730 (defun org-open-file (path &optional in-emacs line search)
8731 "Open the file at PATH.
8732 First, this expands any special file name abbreviations. Then the
8733 configuration variable `org-file-apps' is checked if it contains an
8734 entry for this file type, and if yes, the corresponding command is launched.
8736 If no application is found, Emacs simply visits the file.
8738 With optional prefix argument IN-EMACS, Emacs will visit the file.
8739 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8740 and o use an external application to visit the file.
8742 Optional LINE specifies a line to go to, optional SEARCH a string to
8743 search for. If LINE or SEARCH is given, the file will always be
8744 opened in Emacs.
8745 If the file does not exist, an error is thrown."
8746 (setq in-emacs (or in-emacs line search))
8747 (let* ((file (if (equal path "")
8748 buffer-file-name
8749 (substitute-in-file-name (expand-file-name path))))
8750 (apps (append org-file-apps (org-default-apps)))
8751 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8752 (dirp (if remp nil (file-directory-p file)))
8753 (file (if (and dirp org-open-directory-means-index-dot-org)
8754 (concat (file-name-as-directory file) "index.org")
8755 file))
8756 (a-m-a-p (assq 'auto-mode apps))
8757 (dfile (downcase file))
8758 (old-buffer (current-buffer))
8759 (old-pos (point))
8760 (old-mode major-mode)
8761 ext cmd)
8762 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8763 (setq ext (match-string 1 dfile))
8764 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8765 (setq ext (match-string 1 dfile))))
8766 (cond
8767 ((equal in-emacs '(16))
8768 (setq cmd (cdr (assoc 'system apps))))
8769 (in-emacs (setq cmd 'emacs))
8771 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8772 (and dirp (cdr (assoc 'directory apps)))
8773 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8774 'string-match)
8775 (cdr (assoc ext apps))
8776 (cdr (assoc t apps))))))
8777 (when (eq cmd 'system)
8778 (setq cmd (cdr (assoc 'system apps))))
8779 (when (eq cmd 'default)
8780 (setq cmd (cdr (assoc t apps))))
8781 (when (eq cmd 'mailcap)
8782 (require 'mailcap)
8783 (mailcap-parse-mailcaps)
8784 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8785 (command (mailcap-mime-info mime-type)))
8786 (if (stringp command)
8787 (setq cmd command)
8788 (setq cmd 'emacs))))
8789 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8790 (not (file-exists-p file))
8791 (not org-open-non-existing-files))
8792 (error "No such file: %s" file))
8793 (cond
8794 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8795 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8796 (while (string-match "['\"]%s['\"]" cmd)
8797 (setq cmd (replace-match "%s" t t cmd)))
8798 (while (string-match "%s" cmd)
8799 (setq cmd (replace-match
8800 (save-match-data
8801 (shell-quote-argument
8802 (convert-standard-filename file)))
8803 t t cmd)))
8804 (save-window-excursion
8805 (start-process-shell-command cmd nil cmd)
8806 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8808 ((or (stringp cmd)
8809 (eq cmd 'emacs))
8810 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8811 (widen)
8812 (if line (org-goto-line line)
8813 (if search (org-link-search search))))
8814 ((consp cmd)
8815 (let ((file (convert-standard-filename file)))
8816 (eval cmd)))
8817 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8818 (and (org-mode-p) (eq old-mode 'org-mode)
8819 (or (not (equal old-buffer (current-buffer)))
8820 (not (equal old-pos (point))))
8821 (org-mark-ring-push old-pos old-buffer))))
8823 (defun org-default-apps ()
8824 "Return the default applications for this operating system."
8825 (cond
8826 ((eq system-type 'darwin)
8827 org-file-apps-defaults-macosx)
8828 ((eq system-type 'windows-nt)
8829 org-file-apps-defaults-windowsnt)
8830 (t org-file-apps-defaults-gnu)))
8832 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8833 "Convert extensions to regular expressions in the cars of LIST.
8834 Also, weed out any non-string entries, because the return value is used
8835 only for regexp matching.
8836 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8837 point to the symbol `emacs', indicating that the file should
8838 be opened in Emacs."
8839 (append
8840 (delq nil
8841 (mapcar (lambda (x)
8842 (if (not (stringp (car x)))
8844 (if (string-match "\\W" (car x))
8846 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8847 list))
8848 (if add-auto-mode
8849 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8851 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8852 (defun org-file-remote-p (file)
8853 "Test whether FILE specifies a location on a remote system.
8854 Return non-nil if the location is indeed remote.
8856 For example, the filename \"/user@host:/foo\" specifies a location
8857 on the system \"/user@host:\"."
8858 (cond ((fboundp 'file-remote-p)
8859 (file-remote-p file))
8860 ((fboundp 'tramp-handle-file-remote-p)
8861 (tramp-handle-file-remote-p file))
8862 ((and (boundp 'ange-ftp-name-format)
8863 (string-match (car ange-ftp-name-format) file))
8865 (t nil)))
8868 ;;;; Refiling
8870 (defun org-get-org-file ()
8871 "Read a filename, with default directory `org-directory'."
8872 (let ((default (or org-default-notes-file remember-data-file)))
8873 (read-file-name (format "File name [%s]: " default)
8874 (file-name-as-directory org-directory)
8875 default)))
8877 (defun org-notes-order-reversed-p ()
8878 "Check if the current file should receive notes in reversed order."
8879 (cond
8880 ((not org-reverse-note-order) nil)
8881 ((eq t org-reverse-note-order) t)
8882 ((not (listp org-reverse-note-order)) nil)
8883 (t (catch 'exit
8884 (let ((all org-reverse-note-order)
8885 entry)
8886 (while (setq entry (pop all))
8887 (if (string-match (car entry) buffer-file-name)
8888 (throw 'exit (cdr entry))))
8889 nil)))))
8891 (defvar org-refile-target-table nil
8892 "The list of refile targets, created by `org-refile'.")
8894 (defvar org-agenda-new-buffers nil
8895 "Buffers created to visit agenda files.")
8897 (defun org-get-refile-targets (&optional default-buffer)
8898 "Produce a table with refile targets."
8899 (let ((case-fold-search nil)
8900 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8901 (entries (or org-refile-targets '((nil . (:level . 1)))))
8902 targets txt re files f desc descre fast-path-p level pos0)
8903 (message "Getting targets...")
8904 (with-current-buffer (or default-buffer (current-buffer))
8905 (while (setq entry (pop entries))
8906 (setq files (car entry) desc (cdr entry))
8907 (setq fast-path-p nil)
8908 (cond
8909 ((null files) (setq files (list (current-buffer))))
8910 ((eq files 'org-agenda-files)
8911 (setq files (org-agenda-files 'unrestricted)))
8912 ((and (symbolp files) (fboundp files))
8913 (setq files (funcall files)))
8914 ((and (symbolp files) (boundp files))
8915 (setq files (symbol-value files))))
8916 (if (stringp files) (setq files (list files)))
8917 (cond
8918 ((eq (car desc) :tag)
8919 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8920 ((eq (car desc) :todo)
8921 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8922 ((eq (car desc) :regexp)
8923 (setq descre (cdr desc)))
8924 ((eq (car desc) :level)
8925 (setq descre (concat "^\\*\\{" (number-to-string
8926 (if org-odd-levels-only
8927 (1- (* 2 (cdr desc)))
8928 (cdr desc)))
8929 "\\}[ \t]")))
8930 ((eq (car desc) :maxlevel)
8931 (setq fast-path-p t)
8932 (setq descre (concat "^\\*\\{1," (number-to-string
8933 (if org-odd-levels-only
8934 (1- (* 2 (cdr desc)))
8935 (cdr desc)))
8936 "\\}[ \t]")))
8937 (t (error "Bad refiling target description %s" desc)))
8938 (while (setq f (pop files))
8939 (with-current-buffer
8940 (if (bufferp f) f (org-get-agenda-file-buffer f))
8941 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8942 (setq f (expand-file-name f))
8943 (if (eq org-refile-use-outline-path 'file)
8944 (push (list (file-name-nondirectory f) f nil nil) targets))
8945 (save-excursion
8946 (save-restriction
8947 (widen)
8948 (goto-char (point-min))
8949 (while (re-search-forward descre nil t)
8950 (goto-char (setq pos0 (point-at-bol)))
8951 (catch 'next
8952 (when org-refile-target-verify-function
8953 (save-match-data
8954 (or (funcall org-refile-target-verify-function)
8955 (throw 'next t))))
8956 (when (looking-at org-complex-heading-regexp)
8957 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8958 txt (org-link-display-format (match-string 4))
8959 re (concat "^" (regexp-quote
8960 (buffer-substring (match-beginning 1)
8961 (match-end 4)))))
8962 (if (match-end 5) (setq re (concat re "[ \t]+"
8963 (regexp-quote
8964 (match-string 5)))))
8965 (setq re (concat re "[ \t]*$"))
8966 (when org-refile-use-outline-path
8967 (setq txt (mapconcat 'org-protect-slash
8968 (append
8969 (if (eq org-refile-use-outline-path 'file)
8970 (list (file-name-nondirectory
8971 (buffer-file-name (buffer-base-buffer))))
8972 (if (eq org-refile-use-outline-path 'full-file-path)
8973 (list (buffer-file-name (buffer-base-buffer)))))
8974 (org-get-outline-path fast-path-p level txt)
8975 (list txt))
8976 "/")))
8977 (push (list txt f re (point)) targets)))
8978 (when (= (point) pos0)
8979 ;; verification function has not moved point
8980 (goto-char (point-at-eol))))))))))
8981 (message "Getting targets...done")
8982 (nreverse targets)))
8984 (defun org-protect-slash (s)
8985 (while (string-match "/" s)
8986 (setq s (replace-match "\\" t t s)))
8989 (defvar org-olpa (make-vector 20 nil))
8991 (defun org-get-outline-path (&optional fastp level heading)
8992 "Return the outline path to the current entry, as a list.
8993 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
8994 routine which makes outline path derivations for an entire file,
8995 avoiding backtracing."
8996 (if fastp
8997 (progn
8998 (if (> level 19)
8999 (error "Outline path failure, more than 19 levels."))
9000 (loop for i from level upto 19 do
9001 (aset org-olpa i nil))
9002 (prog1
9003 (delq nil (append org-olpa nil))
9004 (aset org-olpa level heading)))
9005 (let (rtn)
9006 (save-excursion
9007 (save-restriction
9008 (widen)
9009 (while (org-up-heading-safe)
9010 (when (looking-at org-complex-heading-regexp)
9011 (push (org-match-string-no-properties 4) rtn)))
9012 rtn)))))
9014 (defun org-format-outline-path (path &optional width prefix)
9015 "Format the outlie path PATH for display.
9016 Width is the maximum number of characters that is available.
9017 Prefix is a prefix to be included in the returned string,
9018 such as the file name."
9019 (setq width (or width 79))
9020 (if prefix (setq width (- width (length prefix))))
9021 (if (not path)
9022 (or prefix "")
9023 (let* ((nsteps (length path))
9024 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9025 (maxwidth (if (<= total-width width)
9026 10000 ;; everything fits
9027 ;; we need to shorten the level headings
9028 (/ (- width nsteps) nsteps)))
9029 (org-odd-levels-only nil)
9030 (n 0)
9031 (total (1+ (length prefix))))
9032 (setq maxwidth (max maxwidth 10))
9033 (concat prefix
9034 (mapconcat
9035 (lambda (h)
9036 (setq n (1+ n))
9037 (if (and (= n nsteps) (< maxwidth 10000))
9038 (setq maxwidth (- total-width total)))
9039 (if (< (length h) maxwidth)
9040 (progn (setq total (+ total (length h) 1)) h)
9041 (setq h (substring h 0 (- maxwidth 2))
9042 total (+ total maxwidth 1))
9043 (if (string-match "[ \t]+\\'" h)
9044 (setq h (substring h 0 (match-beginning 0))))
9045 (setq h (concat h "..")))
9046 (org-add-props h nil 'face
9047 (nth (% (1- n) org-n-level-faces)
9048 org-level-faces))
9050 path "/")))))
9052 (defun org-display-outline-path (&optional file current)
9053 "Display the current outline path in the echo area."
9054 (interactive "P")
9055 (let ((bfn (buffer-file-name (buffer-base-buffer)))
9056 (path (and (org-mode-p) (org-get-outline-path))))
9057 (if current (setq path (append path
9058 (save-excursion
9059 (org-back-to-heading t)
9060 (if (looking-at org-complex-heading-regexp)
9061 (list (match-string 4)))))))
9062 (message (org-format-outline-path
9063 path
9064 (1- (frame-width))
9065 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9067 (defvar org-refile-history nil
9068 "History for refiling operations.")
9070 (defvar org-after-refile-insert-hook nil
9071 "Hook run after `org-refile' has inserted its stuff at the new location.
9072 Note that this is still *before* the stuff will be removed from
9073 the *old* location.")
9075 (defun org-refile (&optional goto default-buffer rfloc)
9076 "Move the entry at point to another heading.
9077 The list of target headings is compiled using the information in
9078 `org-refile-targets', which see. This list is created before each use
9079 and will therefore always be up-to-date.
9081 At the target location, the entry is filed as a subitem of the target heading.
9082 Depending on `org-reverse-note-order', the new subitem will either be the
9083 first or the last subitem.
9085 If there is an active region, all entries in that region will be moved.
9086 However, the region must fulfil the requirement that the first heading
9087 is the first one sets the top-level of the moved text - at most siblings
9088 below it are allowed.
9090 With prefix arg GOTO, the command will only visit the target location,
9091 not actually move anything.
9092 With a double prefix `C-u C-u', go to the location where the last refiling
9093 operation has put the subtree.
9094 With a prefix argument of `2', refile to the running clock.
9096 RFLOC can be a refile location obtained in a different way.
9098 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9099 (interactive "P")
9100 (let* ((cbuf (current-buffer))
9101 (regionp (org-region-active-p))
9102 (region-start (and regionp (region-beginning)))
9103 (region-end (and regionp (region-end)))
9104 (region-length (and regionp (- region-end region-start)))
9105 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9106 pos it nbuf file re level reversed)
9107 (setq last-command nil)
9108 (when regionp
9109 (goto-char region-start)
9110 (or (bolp) (goto-char (point-at-bol)))
9111 (setq region-start (point))
9112 (unless (org-kill-is-subtree-p
9113 (buffer-substring region-start region-end))
9114 (error "The region is not a (sequence of) subtree(s)")))
9115 (if (equal goto '(16))
9116 (org-refile-goto-last-stored)
9117 (when (or
9118 (and (equal goto 2)
9119 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9120 (prog1
9121 (setq it (list (or org-clock-heading "running clock")
9122 (buffer-file-name
9123 (marker-buffer org-clock-hd-marker))
9125 (marker-position org-clock-hd-marker)))
9126 (setq goto nil)))
9127 (setq it (or rfloc
9128 (save-excursion
9129 (org-refile-get-location
9130 (if goto "Goto: " "Refile to: ") default-buffer
9131 org-refile-allow-creating-parent-nodes)))))
9132 (setq file (nth 1 it)
9133 re (nth 2 it)
9134 pos (nth 3 it))
9135 (if (and (not goto)
9137 (equal (buffer-file-name) file)
9138 (if regionp
9139 (and (>= pos region-start)
9140 (<= pos region-end))
9141 (and (>= pos (point))
9142 (< pos (save-excursion
9143 (org-end-of-subtree t t))))))
9144 (error "Cannot refile to position inside the tree or region"))
9146 (setq nbuf (or (find-buffer-visiting file)
9147 (find-file-noselect file)))
9148 (if goto
9149 (progn
9150 (switch-to-buffer nbuf)
9151 (goto-char pos)
9152 (org-show-context 'org-goto))
9153 (if regionp
9154 (progn
9155 (org-kill-new (buffer-substring region-start region-end))
9156 (org-save-markers-in-region region-start region-end))
9157 (org-copy-subtree 1 nil t))
9158 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9159 (find-file-noselect file)))
9160 (setq reversed (org-notes-order-reversed-p))
9161 (save-excursion
9162 (save-restriction
9163 (widen)
9164 (if pos
9165 (progn
9166 (goto-char pos)
9167 (looking-at outline-regexp)
9168 (setq level (org-get-valid-level (funcall outline-level) 1))
9169 (goto-char
9170 (if reversed
9171 (or (outline-next-heading) (point-max))
9172 (or (save-excursion (org-get-next-sibling))
9173 (org-end-of-subtree t t)
9174 (point-max)))))
9175 (setq level 1)
9176 (if (not reversed)
9177 (goto-char (point-max))
9178 (goto-char (point-min))
9179 (or (outline-next-heading) (goto-char (point-max)))))
9180 (if (not (bolp)) (newline))
9181 (bookmark-set "org-refile-last-stored")
9182 (org-paste-subtree level)
9183 (if (fboundp 'deactivate-mark) (deactivate-mark))
9184 (run-hooks 'org-after-refile-insert-hook))))
9185 (if regionp
9186 (delete-region (point) (+ (point) region-length))
9187 (org-cut-subtree))
9188 (when (featurep 'org-inlinetask)
9189 (org-inlinetask-remove-END-maybe))
9190 (setq org-markers-to-move nil)
9191 (message "Refiled to \"%s\"" (car it))))))
9192 (org-reveal))
9194 (defun org-refile-goto-last-stored ()
9195 "Go to the location where the last refile was stored."
9196 (interactive)
9197 (bookmark-jump "org-refile-last-stored")
9198 (message "This is the location of the last refile"))
9200 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9201 "Prompt the user for a refile location, using PROMPT."
9202 (let ((org-refile-targets org-refile-targets)
9203 (org-refile-use-outline-path org-refile-use-outline-path))
9204 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9205 (unless org-refile-target-table
9206 (error "No refile targets"))
9207 (let* ((cbuf (current-buffer))
9208 (partial-completion-mode nil)
9209 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9210 (cfunc (if (and org-refile-use-outline-path
9211 org-outline-path-complete-in-steps)
9212 'org-olpath-completing-read
9213 'org-icompleting-read))
9214 (extra (if org-refile-use-outline-path "/" ""))
9215 (filename (and cfn (expand-file-name cfn)))
9216 (tbl (mapcar
9217 (lambda (x)
9218 (if (and (not (member org-refile-use-outline-path
9219 '(file full-file-path)))
9220 (not (equal filename (nth 1 x))))
9221 (cons (concat (car x) extra " ("
9222 (file-name-nondirectory (nth 1 x)) ")")
9223 (cdr x))
9224 (cons (concat (car x) extra) (cdr x))))
9225 org-refile-target-table))
9226 (completion-ignore-case t)
9227 pa answ parent-target child parent old-hist)
9228 (setq old-hist org-refile-history)
9229 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9230 nil 'org-refile-history))
9231 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9232 (if pa
9233 (progn
9234 (when (or (not org-refile-history)
9235 (not (eq old-hist org-refile-history))
9236 (not (equal (car pa) (car org-refile-history))))
9237 (setq org-refile-history
9238 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9239 org-refile-history
9240 (cdr org-refile-history))))
9241 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9242 (pop org-refile-history)))
9244 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9245 (setq parent (match-string 1 answ)
9246 child (match-string 2 answ))
9247 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9248 (when (and parent-target
9249 (or (eq new-nodes t)
9250 (and (eq new-nodes 'confirm)
9251 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9252 (org-refile-new-child parent-target child))))))
9254 (defun org-refile-new-child (parent-target child)
9255 "Use refile target PARENT-TARGET to add new CHILD below it."
9256 (unless parent-target
9257 (error "Cannot find parent for new node"))
9258 (let ((file (nth 1 parent-target))
9259 (pos (nth 3 parent-target))
9260 level)
9261 (with-current-buffer (or (find-buffer-visiting file)
9262 (find-file-noselect file))
9263 (save-excursion
9264 (save-restriction
9265 (widen)
9266 (if pos
9267 (goto-char pos)
9268 (goto-char (point-max))
9269 (if (not (bolp)) (newline)))
9270 (when (looking-at outline-regexp)
9271 (setq level (funcall outline-level))
9272 (org-end-of-subtree t t))
9273 (org-back-over-empty-lines)
9274 (insert "\n" (make-string
9275 (if pos (org-get-valid-level level 1) 1) ?*)
9276 " " child "\n")
9277 (beginning-of-line 0)
9278 (list (concat (car parent-target) "/" child) file "" (point)))))))
9280 (defun org-olpath-completing-read (prompt collection &rest args)
9281 "Read an outline path like a file name."
9282 (let ((thetable collection)
9283 (org-completion-use-ido nil) ; does not work with ido.
9284 (org-completion-use-iswitchb nil)) ; or iswitchb
9285 (apply
9286 'org-icompleting-read prompt
9287 (lambda (string predicate &optional flag)
9288 (let (rtn r f (l (length string)))
9289 (cond
9290 ((eq flag nil)
9291 ;; try completion
9292 (try-completion string thetable))
9293 ((eq flag t)
9294 ;; all-completions
9295 (setq rtn (all-completions string thetable predicate))
9296 (mapcar
9297 (lambda (x)
9298 (setq r (substring x l))
9299 (if (string-match " ([^)]*)$" x)
9300 (setq f (match-string 0 x))
9301 (setq f ""))
9302 (if (string-match "/" r)
9303 (concat string (substring r 0 (match-end 0)) f)
9305 rtn))
9306 ((eq flag 'lambda)
9307 ;; exact match?
9308 (assoc string thetable)))
9310 args)))
9312 ;;;; Dynamic blocks
9314 (defun org-find-dblock (name)
9315 "Find the first dynamic block with name NAME in the buffer.
9316 If not found, stay at current position and return nil."
9317 (let (pos)
9318 (save-excursion
9319 (goto-char (point-min))
9320 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9321 nil t)
9322 (match-beginning 0))))
9323 (if pos (goto-char pos))
9324 pos))
9326 (defconst org-dblock-start-re
9327 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9328 "Matches the start line of a dynamic block, with parameters.")
9330 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9331 "Matches the end of a dynamic block.")
9333 (defun org-create-dblock (plist)
9334 "Create a dynamic block section, with parameters taken from PLIST.
9335 PLIST must contain a :name entry which is used as name of the block."
9336 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9337 (end-of-line 1)
9338 (newline))
9339 (let ((col (current-column))
9340 (name (plist-get plist :name)))
9341 (insert "#+BEGIN: " name)
9342 (while plist
9343 (if (eq (car plist) :name)
9344 (setq plist (cddr plist))
9345 (insert " " (prin1-to-string (pop plist)))))
9346 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9347 (beginning-of-line -2)))
9349 (defun org-prepare-dblock ()
9350 "Prepare dynamic block for refresh.
9351 This empties the block, puts the cursor at the insert position and returns
9352 the property list including an extra property :name with the block name."
9353 (unless (looking-at org-dblock-start-re)
9354 (error "Not at a dynamic block"))
9355 (let* ((begdel (1+ (match-end 0)))
9356 (name (org-no-properties (match-string 1)))
9357 (params (append (list :name name)
9358 (read (concat "(" (match-string 3) ")")))))
9359 (save-excursion
9360 (beginning-of-line 1)
9361 (skip-chars-forward " \t")
9362 (setq params (plist-put params :indentation-column (current-column))))
9363 (unless (re-search-forward org-dblock-end-re nil t)
9364 (error "Dynamic block not terminated"))
9365 (setq params
9366 (append params
9367 (list :content (buffer-substring
9368 begdel (match-beginning 0)))))
9369 (delete-region begdel (match-beginning 0))
9370 (goto-char begdel)
9371 (open-line 1)
9372 params))
9374 (defun org-map-dblocks (&optional command)
9375 "Apply COMMAND to all dynamic blocks in the current buffer.
9376 If COMMAND is not given, use `org-update-dblock'."
9377 (let ((cmd (or command 'org-update-dblock))
9378 pos)
9379 (save-excursion
9380 (goto-char (point-min))
9381 (while (re-search-forward org-dblock-start-re nil t)
9382 (goto-char (setq pos (match-beginning 0)))
9383 (condition-case nil
9384 (funcall cmd)
9385 (error (message "Error during update of dynamic block")))
9386 (goto-char pos)
9387 (unless (re-search-forward org-dblock-end-re nil t)
9388 (error "Dynamic block not terminated"))))))
9390 (defun org-dblock-update (&optional arg)
9391 "User command for updating dynamic blocks.
9392 Update the dynamic block at point. With prefix ARG, update all dynamic
9393 blocks in the buffer."
9394 (interactive "P")
9395 (if arg
9396 (org-update-all-dblocks)
9397 (or (looking-at org-dblock-start-re)
9398 (org-beginning-of-dblock))
9399 (org-update-dblock)))
9401 (defun org-update-dblock ()
9402 "Update the dynamic block at point
9403 This means to empty the block, parse for parameters and then call
9404 the correct writing function."
9405 (save-window-excursion
9406 (let* ((pos (point))
9407 (line (org-current-line))
9408 (params (org-prepare-dblock))
9409 (name (plist-get params :name))
9410 (indent (plist-get params :indentation-column))
9411 (cmd (intern (concat "org-dblock-write:" name))))
9412 (message "Updating dynamic block `%s' at line %d..." name line)
9413 (funcall cmd params)
9414 (message "Updating dynamic block `%s' at line %d...done" name line)
9415 (goto-char pos)
9416 (when (and indent (> indent 0))
9417 (setq indent (make-string indent ?\ ))
9418 (save-excursion
9419 (org-beginning-of-dblock)
9420 (forward-line 1)
9421 (while (not (looking-at org-dblock-end-re))
9422 (insert indent)
9423 (beginning-of-line 2))
9424 (when (looking-at org-dblock-end-re)
9425 (and (looking-at "[ \t]+")
9426 (replace-match ""))
9427 (insert indent)))))))
9429 (defun org-beginning-of-dblock ()
9430 "Find the beginning of the dynamic block at point.
9431 Error if there is no such block at point."
9432 (let ((pos (point))
9433 beg)
9434 (end-of-line 1)
9435 (if (and (re-search-backward org-dblock-start-re nil t)
9436 (setq beg (match-beginning 0))
9437 (re-search-forward org-dblock-end-re nil t)
9438 (> (match-end 0) pos))
9439 (goto-char beg)
9440 (goto-char pos)
9441 (error "Not in a dynamic block"))))
9443 (defun org-update-all-dblocks ()
9444 "Update all dynamic blocks in the buffer.
9445 This function can be used in a hook."
9446 (when (org-mode-p)
9447 (org-map-dblocks 'org-update-dblock)))
9450 ;;;; Completion
9452 (defconst org-additional-option-like-keywords
9453 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9454 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9455 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "LATEX_CLASS:" "ATTR_LaTeX"
9456 "BEGIN:" "END:"
9457 "ORGTBL" "TBLFM:" "TBLNAME:"
9458 "BEGIN_EXAMPLE" "END_EXAMPLE"
9459 "BEGIN_QUOTE" "END_QUOTE"
9460 "BEGIN_VERSE" "END_VERSE"
9461 "BEGIN_CENTER" "END_CENTER"
9462 "BEGIN_SRC" "END_SRC"
9463 "CATEGORY" "COLUMNS"
9464 "CAPTION" "LABEL"
9465 "SETUPFILE"
9466 "BIND"
9467 "MACRO"))
9469 (defcustom org-structure-template-alist
9471 ("s" "#+begin_src ?\n\n#+end_src"
9472 "<src lang=\"?\">\n\n</src>")
9473 ("e" "#+begin_example\n?\n#+end_example"
9474 "<example>\n?\n</example>")
9475 ("q" "#+begin_quote\n?\n#+end_quote"
9476 "<quote>\n?\n</quote>")
9477 ("v" "#+begin_verse\n?\n#+end_verse"
9478 "<verse>\n?\n/verse>")
9479 ("c" "#+begin_center\n?\n#+end_center"
9480 "<center>\n?\n/center>")
9481 ("l" "#+begin_latex\n?\n#+end_latex"
9482 "<literal style=\"latex\">\n?\n</literal>")
9483 ("L" "#+latex: "
9484 "<literal style=\"latex\">?</literal>")
9485 ("h" "#+begin_html\n?\n#+end_html"
9486 "<literal style=\"html\">\n?\n</literal>")
9487 ("H" "#+html: "
9488 "<literal style=\"html\">?</literal>")
9489 ("a" "#+begin_ascii\n?\n#+end_ascii")
9490 ("A" "#+ascii: ")
9491 ("i" "#+include %file ?"
9492 "<include file=%file markup=\"?\">")
9494 "Structure completion elements.
9495 This is a list of abbreviation keys and values. The value gets inserted
9496 it you type @samp{.} followed by the key and then the completion key,
9497 usually `M-TAB'. %file will be replaced by a file name after prompting
9498 for the file using completion.
9499 There are two templates for each key, the first uses the original Org syntax,
9500 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9501 the default when the /org-mtags.el/ module has been loaded. See also the
9502 variable `org-mtags-prefer-muse-templates'.
9503 This is an experimental feature, it is undecided if it is going to stay in."
9504 :group 'org-completion
9505 :type '(repeat
9506 (string :tag "Key")
9507 (string :tag "Template")
9508 (string :tag "Muse Template")))
9510 (defun org-try-structure-completion ()
9511 "Try to complete a structure template before point.
9512 This looks for strings like \"<e\" on an otherwise empty line and
9513 expands them."
9514 (let ((l (buffer-substring (point-at-bol) (point)))
9516 (when (and (looking-at "[ \t]*$")
9517 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9518 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9519 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9520 (match-beginning 1)) a)
9521 t)))
9523 (defun org-complete-expand-structure-template (start cell)
9524 "Expand a structure template."
9525 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9526 (rpl (nth (if musep 2 1) cell))
9527 (ind ""))
9528 (delete-region start (point))
9529 (when (string-match "\\`#\\+" rpl)
9530 (cond
9531 ((bolp))
9532 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9533 (setq ind (buffer-substring (point-at-bol) (point))))
9534 (t (newline))))
9535 (setq start (point))
9536 (if (string-match "%file" rpl)
9537 (setq rpl (replace-match
9538 (concat
9539 "\""
9540 (save-match-data
9541 (abbreviate-file-name (read-file-name "Include file: ")))
9542 "\"")
9543 t t rpl)))
9544 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9545 (concat "\n" ind)))
9546 (insert rpl)
9547 (if (re-search-backward "\\?" start t) (delete-char 1))))
9550 (defun org-complete (&optional arg)
9551 "Perform completion on word at point.
9552 At the beginning of a headline, this completes TODO keywords as given in
9553 `org-todo-keywords'.
9554 If the current word is preceded by a backslash, completes the TeX symbols
9555 that are supported for HTML support.
9556 If the current word is preceded by \"#+\", completes special words for
9557 setting file options.
9558 In the line after \"#+STARTUP:, complete valid keywords.\"
9559 At all other locations, this simply calls the value of
9560 `org-completion-fallback-command'."
9561 (interactive "P")
9562 (org-without-partial-completion
9563 (catch 'exit
9564 (let* ((a nil)
9565 (end (point))
9566 (beg1 (save-excursion
9567 (skip-chars-backward (org-re "[:alnum:]_@"))
9568 (point)))
9569 (beg (save-excursion
9570 (skip-chars-backward "a-zA-Z0-9_:$")
9571 (point)))
9572 (confirm (lambda (x) (stringp (car x))))
9573 (searchhead (equal (char-before beg) ?*))
9574 (struct
9575 (when (and (member (char-before beg1) '(?. ?<))
9576 (setq a (assoc (buffer-substring beg1 (point))
9577 org-structure-template-alist)))
9578 (org-complete-expand-structure-template (1- beg1) a)
9579 (throw 'exit t)))
9580 (tag (and (equal (char-before beg1) ?:)
9581 (equal (char-after (point-at-bol)) ?*)))
9582 (prop (and (equal (char-before beg1) ?:)
9583 (not (equal (char-after (point-at-bol)) ?*))))
9584 (texp (equal (char-before beg) ?\\))
9585 (link (equal (char-before beg) ?\[))
9586 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9587 beg)
9588 "#+"))
9589 (startup (string-match "^#\\+STARTUP:.*"
9590 (buffer-substring (point-at-bol) (point))))
9591 (completion-ignore-case opt)
9592 (type nil)
9593 (tbl nil)
9594 (table (cond
9595 (opt
9596 (setq type :opt)
9597 (require 'org-exp)
9598 (append
9599 (delq nil
9600 (mapcar
9601 (lambda (x)
9602 (if (string-match
9603 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9604 (cons (match-string 2 x)
9605 (match-string 1 x))))
9606 (org-split-string (org-get-current-options) "\n")))
9607 (mapcar 'list org-additional-option-like-keywords)))
9608 (startup
9609 (setq type :startup)
9610 org-startup-options)
9611 (link (append org-link-abbrev-alist-local
9612 org-link-abbrev-alist))
9613 (texp
9614 (setq type :tex)
9615 org-html-entities)
9616 ((string-match "\\`\\*+[ \t]+\\'"
9617 (buffer-substring (point-at-bol) beg))
9618 (setq type :todo)
9619 (mapcar 'list org-todo-keywords-1))
9620 (searchhead
9621 (setq type :searchhead)
9622 (save-excursion
9623 (goto-char (point-min))
9624 (while (re-search-forward org-todo-line-regexp nil t)
9625 (push (list
9626 (org-make-org-heading-search-string
9627 (match-string 3) t))
9628 tbl)))
9629 tbl)
9630 (tag (setq type :tag beg beg1)
9631 (or org-tag-alist (org-get-buffer-tags)))
9632 (prop (setq type :prop beg beg1)
9633 (mapcar 'list (org-buffer-property-keys nil t t)))
9634 (t (progn
9635 (call-interactively org-completion-fallback-command)
9636 (throw 'exit nil)))))
9637 (pattern (buffer-substring-no-properties beg end))
9638 (completion (try-completion pattern table confirm)))
9639 (cond ((eq completion t)
9640 (if (not (assoc (upcase pattern) table))
9641 (message "Already complete")
9642 (if (and (equal type :opt)
9643 (not (member (car (assoc (upcase pattern) table))
9644 org-additional-option-like-keywords)))
9645 (insert (substring (cdr (assoc (upcase pattern) table))
9646 (length pattern)))
9647 (if (memq type '(:tag :prop)) (insert ":")))))
9648 ((null completion)
9649 (message "Can't find completion for \"%s\"" pattern)
9650 (ding))
9651 ((not (string= pattern completion))
9652 (delete-region beg end)
9653 (if (string-match " +$" completion)
9654 (setq completion (replace-match "" t t completion)))
9655 (insert completion)
9656 (if (get-buffer-window "*Completions*")
9657 (delete-window (get-buffer-window "*Completions*")))
9658 (if (assoc completion table)
9659 (if (eq type :todo) (insert " ")
9660 (if (memq type '(:tag :prop)) (insert ":"))))
9661 (if (and (equal type :opt) (assoc completion table))
9662 (message "%s" (substitute-command-keys
9663 "Press \\[org-complete] again to insert example settings"))))
9665 (message "Making completion list...")
9666 (let ((list (sort (all-completions pattern table confirm)
9667 'string<)))
9668 (with-output-to-temp-buffer "*Completions*"
9669 (condition-case nil
9670 ;; Protection needed for XEmacs and emacs 21
9671 (display-completion-list list pattern)
9672 (error (display-completion-list list)))))
9673 (message "Making completion list...%s" "done")))))))
9675 ;;;; TODO, DEADLINE, Comments
9677 (defun org-toggle-comment ()
9678 "Change the COMMENT state of an entry."
9679 (interactive)
9680 (save-excursion
9681 (org-back-to-heading)
9682 (let (case-fold-search)
9683 (if (looking-at (concat outline-regexp
9684 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9685 (replace-match "" t t nil 1)
9686 (if (looking-at outline-regexp)
9687 (progn
9688 (goto-char (match-end 0))
9689 (insert org-comment-string " ")))))))
9691 (defvar org-last-todo-state-is-todo nil
9692 "This is non-nil when the last TODO state change led to a TODO state.
9693 If the last change removed the TODO tag or switched to DONE, then
9694 this is nil.")
9696 (defvar org-setting-tags nil) ; dynamically skipped
9698 (defun org-parse-local-options (string var)
9699 "Parse STRING for startup setting relevant for variable VAR."
9700 (let ((rtn (symbol-value var))
9701 e opts)
9702 (save-match-data
9703 (if (or (not string) (not (string-match "\\S-" string)))
9705 (setq opts (delq nil (mapcar (lambda (x)
9706 (setq e (assoc x org-startup-options))
9707 (if (eq (nth 1 e) var) e nil))
9708 (org-split-string string "[ \t]+"))))
9709 (if (not opts)
9711 (setq rtn nil)
9712 (while (setq e (pop opts))
9713 (if (not (nth 3 e))
9714 (setq rtn (nth 2 e))
9715 (if (not (listp rtn)) (setq rtn nil))
9716 (push (nth 2 e) rtn)))
9717 rtn)))))
9719 (defvar org-todo-setup-filter-hook nil
9720 "Hook for functions that pre-filter todo specs.
9722 Each function takes a todo spec and returns either `nil' or the spec
9723 transformed into canonical form." )
9725 (defvar org-todo-get-default-hook nil
9726 "Hook for functions that get a default item for todo.
9728 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9729 `nil' or a string to be used for the todo mark." )
9731 (defvar org-agenda-headline-snapshot-before-repeat)
9733 (defun org-todo (&optional arg)
9734 "Change the TODO state of an item.
9735 The state of an item is given by a keyword at the start of the heading,
9736 like
9737 *** TODO Write paper
9738 *** DONE Call mom
9740 The different keywords are specified in the variable `org-todo-keywords'.
9741 By default the available states are \"TODO\" and \"DONE\".
9742 So for this example: when the item starts with TODO, it is changed to DONE.
9743 When it starts with DONE, the DONE is removed. And when neither TODO nor
9744 DONE are present, add TODO at the beginning of the heading.
9746 With C-u prefix arg, use completion to determine the new state.
9747 With numeric prefix arg, switch to that state.
9748 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9749 With a triple C-u prefix, circumvent any state blocking.
9751 For calling through lisp, arg is also interpreted in the following way:
9752 'none -> empty state
9753 \"\"(empty string) -> switch to empty state
9754 'done -> switch to DONE
9755 'nextset -> switch to the next set of keywords
9756 'previousset -> switch to the previous set of keywords
9757 \"WAITING\" -> switch to the specified keyword, but only if it
9758 really is a member of `org-todo-keywords'."
9759 (interactive "P")
9760 (if (equal arg '(16)) (setq arg 'nextset))
9761 (let ((org-blocker-hook org-blocker-hook)
9762 (case-fold-search nil))
9763 (when (equal arg '(64))
9764 (setq arg nil org-blocker-hook nil))
9765 (when (and org-blocker-hook
9766 (or org-inhibit-blocking
9767 (org-entry-get nil "NOBLOCKING")))
9768 (setq org-blocker-hook nil))
9769 (save-excursion
9770 (catch 'exit
9771 (org-back-to-heading t)
9772 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9773 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9774 (looking-at " *"))
9775 (let* ((match-data (match-data))
9776 (startpos (point-at-bol))
9777 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9778 (org-log-done org-log-done)
9779 (org-log-repeat org-log-repeat)
9780 (org-todo-log-states org-todo-log-states)
9781 (this (match-string 1))
9782 (hl-pos (match-beginning 0))
9783 (head (org-get-todo-sequence-head this))
9784 (ass (assoc head org-todo-kwd-alist))
9785 (interpret (nth 1 ass))
9786 (done-word (nth 3 ass))
9787 (final-done-word (nth 4 ass))
9788 (last-state (or this ""))
9789 (completion-ignore-case t)
9790 (member (member this org-todo-keywords-1))
9791 (tail (cdr member))
9792 (state (cond
9793 ((and org-todo-key-trigger
9794 (or (and (equal arg '(4))
9795 (eq org-use-fast-todo-selection 'prefix))
9796 (and (not arg) org-use-fast-todo-selection
9797 (not (eq org-use-fast-todo-selection
9798 'prefix)))))
9799 ;; Use fast selection
9800 (org-fast-todo-selection))
9801 ((and (equal arg '(4))
9802 (or (not org-use-fast-todo-selection)
9803 (not org-todo-key-trigger)))
9804 ;; Read a state with completion
9805 (org-icompleting-read
9806 "State: " (mapcar (lambda(x) (list x))
9807 org-todo-keywords-1)
9808 nil t))
9809 ((eq arg 'right)
9810 (if this
9811 (if tail (car tail) nil)
9812 (car org-todo-keywords-1)))
9813 ((eq arg 'left)
9814 (if (equal member org-todo-keywords-1)
9816 (if this
9817 (nth (- (length org-todo-keywords-1)
9818 (length tail) 2)
9819 org-todo-keywords-1)
9820 (org-last org-todo-keywords-1))))
9821 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9822 (setq arg nil))) ; hack to fall back to cycling
9823 (arg
9824 ;; user or caller requests a specific state
9825 (cond
9826 ((equal arg "") nil)
9827 ((eq arg 'none) nil)
9828 ((eq arg 'done) (or done-word (car org-done-keywords)))
9829 ((eq arg 'nextset)
9830 (or (car (cdr (member head org-todo-heads)))
9831 (car org-todo-heads)))
9832 ((eq arg 'previousset)
9833 (let ((org-todo-heads (reverse org-todo-heads)))
9834 (or (car (cdr (member head org-todo-heads)))
9835 (car org-todo-heads))))
9836 ((car (member arg org-todo-keywords-1)))
9837 ((stringp arg)
9838 (error "State `%s' not valid in this file" arg))
9839 ((nth (1- (prefix-numeric-value arg))
9840 org-todo-keywords-1))))
9841 ((null member) (or head (car org-todo-keywords-1)))
9842 ((equal this final-done-word) nil) ;; -> make empty
9843 ((null tail) nil) ;; -> first entry
9844 ((memq interpret '(type priority))
9845 (if (eq this-command last-command)
9846 (car tail)
9847 (if (> (length tail) 0)
9848 (or done-word (car org-done-keywords))
9849 nil)))
9851 (car tail))))
9852 (state (or
9853 (run-hook-with-args-until-success
9854 'org-todo-get-default-hook state last-state)
9855 state))
9856 (next (if state (concat " " state " ") " "))
9857 (change-plist (list :type 'todo-state-change :from this :to state
9858 :position startpos))
9859 dolog now-done-p)
9860 (when org-blocker-hook
9861 (setq org-last-todo-state-is-todo
9862 (not (member this org-done-keywords)))
9863 (unless (save-excursion
9864 (save-match-data
9865 (run-hook-with-args-until-failure
9866 'org-blocker-hook change-plist)))
9867 (if (interactive-p)
9868 (error "TODO state change from %s to %s blocked" this state)
9869 ;; fail silently
9870 (message "TODO state change from %s to %s blocked" this state)
9871 (throw 'exit nil))))
9872 (store-match-data match-data)
9873 (replace-match next t t)
9874 (unless (pos-visible-in-window-p hl-pos)
9875 (message "TODO state changed to %s" (org-trim next)))
9876 (unless head
9877 (setq head (org-get-todo-sequence-head state)
9878 ass (assoc head org-todo-kwd-alist)
9879 interpret (nth 1 ass)
9880 done-word (nth 3 ass)
9881 final-done-word (nth 4 ass)))
9882 (when (memq arg '(nextset previousset))
9883 (message "Keyword-Set %d/%d: %s"
9884 (- (length org-todo-sets) -1
9885 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9886 (length org-todo-sets)
9887 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9888 (setq org-last-todo-state-is-todo
9889 (not (member state org-done-keywords)))
9890 (setq now-done-p (and (member state org-done-keywords)
9891 (not (member this org-done-keywords))))
9892 (and logging (org-local-logging logging))
9893 (when (and (or org-todo-log-states org-log-done)
9894 (not (eq org-inhibit-logging t))
9895 (not (memq arg '(nextset previousset))))
9896 ;; we need to look at recording a time and note
9897 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9898 (nth 2 (assoc this org-todo-log-states))))
9899 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9900 (setq dolog 'time))
9901 (when (and state
9902 (member state org-not-done-keywords)
9903 (not (member this org-not-done-keywords)))
9904 ;; This is now a todo state and was not one before
9905 ;; If there was a CLOSED time stamp, get rid of it.
9906 (org-add-planning-info nil nil 'closed))
9907 (when (and now-done-p org-log-done)
9908 ;; It is now done, and it was not done before
9909 (org-add-planning-info 'closed (org-current-time))
9910 (if (and (not dolog) (eq 'note org-log-done))
9911 (org-add-log-setup 'done state this 'findpos 'note)))
9912 (when (and state dolog)
9913 ;; This is a non-nil state, and we need to log it
9914 (org-add-log-setup 'state state this 'findpos dolog)))
9915 ;; Fixup tag positioning
9916 (org-todo-trigger-tag-changes state)
9917 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9918 (when org-provide-todo-statistics
9919 (org-update-parent-todo-statistics))
9920 (run-hooks 'org-after-todo-state-change-hook)
9921 (if (and arg (not (member state org-done-keywords)))
9922 (setq head (org-get-todo-sequence-head state)))
9923 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9924 ;; Do we need to trigger a repeat?
9925 (when now-done-p
9926 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9927 ;; This is for the agenda, take a snapshot of the headline.
9928 (save-match-data
9929 (setq org-agenda-headline-snapshot-before-repeat
9930 (org-get-heading))))
9931 (org-auto-repeat-maybe state))
9932 ;; Fixup cursor location if close to the keyword
9933 (if (and (outline-on-heading-p)
9934 (not (bolp))
9935 (save-excursion (beginning-of-line 1)
9936 (looking-at org-todo-line-regexp))
9937 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9938 (progn
9939 (goto-char (or (match-end 2) (match-end 1)))
9940 (and (looking-at " ") (just-one-space))))
9941 (when org-trigger-hook
9942 (save-excursion
9943 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9945 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9946 "Block turning an entry into a TODO, using the hierarchy.
9947 This checks whether the current task should be blocked from state
9948 changes. Such blocking occurs when:
9950 1. The task has children which are not all in a completed state.
9952 2. A task has a parent with the property :ORDERED:, and there
9953 are siblings prior to the current task with incomplete
9954 status.
9956 3. The parent of the task is blocked because it has siblings that should
9957 be done first, or is child of a block grandparent TODO entry."
9959 (catch 'dont-block
9960 ;; If this is not a todo state change, or if this entry is already DONE,
9961 ;; do not block
9962 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9963 (member (plist-get change-plist :from)
9964 (cons 'done org-done-keywords))
9965 (member (plist-get change-plist :to)
9966 (cons 'todo org-not-done-keywords))
9967 (not (plist-get change-plist :to)))
9968 (throw 'dont-block t))
9969 ;; If this task has children, and any are undone, it's blocked
9970 (save-excursion
9971 (org-back-to-heading t)
9972 (let ((this-level (funcall outline-level)))
9973 (outline-next-heading)
9974 (let ((child-level (funcall outline-level)))
9975 (while (and (not (eobp))
9976 (> child-level this-level))
9977 ;; this todo has children, check whether they are all
9978 ;; completed
9979 (if (and (not (org-entry-is-done-p))
9980 (org-entry-is-todo-p))
9981 (throw 'dont-block nil))
9982 (outline-next-heading)
9983 (setq child-level (funcall outline-level))))))
9984 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9985 ;; any previous siblings are undone, it's blocked
9986 (save-excursion
9987 (org-back-to-heading t)
9988 (let* ((pos (point))
9989 (parent-pos (and (org-up-heading-safe) (point))))
9990 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9991 (when (and (org-entry-get (point) "ORDERED")
9992 (forward-line 1)
9993 (re-search-forward org-not-done-heading-regexp pos t))
9994 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9995 ;; Search further up the hierarchy, to see if an anchestor is blocked
9996 (while t
9997 (goto-char parent-pos)
9998 (if (not (looking-at org-not-done-heading-regexp))
9999 (throw 'dont-block t)) ; do not block, parent is not a TODO
10000 (setq pos (point))
10001 (setq parent-pos (and (org-up-heading-safe) (point)))
10002 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10003 (when (and (org-entry-get (point) "ORDERED")
10004 (forward-line 1)
10005 (re-search-forward org-not-done-heading-regexp pos t))
10006 (throw 'dont-block nil))))))) ; block, older sibling not done.
10008 (defcustom org-track-ordered-property-with-tag nil
10009 "Should the ORDERED property also be shown as a tag?
10010 The ORDERED property decides if an entry should require subtasks to be
10011 completed in sequence. Since a property is not very visible, setting
10012 this option means that toggling the ORDERED property with the command
10013 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10014 not relevant for the behavior, but it makes things more visible.
10016 Note that toggling the tag with tags commands will not change the property
10017 and therefore not influence behavior!
10019 This can be t, meaning the tag ORDERED should be used, It can also be a
10020 string to select a different tag for this task."
10021 :group 'org-todo
10022 :type '(choice
10023 (const :tag "No tracking" nil)
10024 (const :tag "Track with ORDERED tag" t)
10025 (string :tag "Use other tag")))
10027 (defun org-toggle-ordered-property ()
10028 "Toggle the ORDERED property of the current entry.
10029 For better visibility, you can track the value of this property with a tag.
10030 See variable `org-track-ordered-property-with-tag'."
10031 (interactive)
10032 (let* ((t1 org-track-ordered-property-with-tag)
10033 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10034 (save-excursion
10035 (org-back-to-heading)
10036 (if (org-entry-get nil "ORDERED")
10037 (progn
10038 (org-delete-property "ORDERED")
10039 (and tag (org-toggle-tag tag 'off))
10040 (message "Subtasks can be completed in arbitrary order"))
10041 (org-entry-put nil "ORDERED" "t")
10042 (and tag (org-toggle-tag tag 'on))
10043 (message "Subtasks must be completed in sequence")))))
10045 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10046 (defun org-block-todo-from-checkboxes (change-plist)
10047 "Block turning an entry into a TODO, using checkboxes.
10048 This checks whether the current task should be blocked from state
10049 changes because there are unchecked boxes in this entry."
10050 (catch 'dont-block
10051 ;; If this is not a todo state change, or if this entry is already DONE,
10052 ;; do not block
10053 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10054 (member (plist-get change-plist :from)
10055 (cons 'done org-done-keywords))
10056 (member (plist-get change-plist :to)
10057 (cons 'todo org-not-done-keywords))
10058 (not (plist-get change-plist :to)))
10059 (throw 'dont-block t))
10060 ;; If this task has checkboxes that are not checked, it's blocked
10061 (save-excursion
10062 (org-back-to-heading t)
10063 (let ((beg (point)) end)
10064 (outline-next-heading)
10065 (setq end (point))
10066 (goto-char beg)
10067 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10068 end t)
10069 (progn
10070 (if (boundp 'org-blocked-by-checkboxes)
10071 (setq org-blocked-by-checkboxes t))
10072 (throw 'dont-block nil)))))
10073 t)) ; do not block
10075 (defun org-update-statistics-cookies (all)
10076 "Update the statistics cookie, either from TODO or from checkboxes.
10077 This should be called with the cursor in a line with a statistics cookie."
10078 (interactive "P")
10079 (if all
10080 (progn
10081 (org-update-checkbox-count 'all)
10082 (org-map-entries 'org-update-parent-todo-statistics))
10083 (if (not (org-on-heading-p))
10084 (org-update-checkbox-count)
10085 (let ((pos (move-marker (make-marker) (point)))
10086 end l1 l2)
10087 (ignore-errors (org-back-to-heading t))
10088 (if (not (org-on-heading-p))
10089 (org-update-checkbox-count)
10090 (setq l1 (org-outline-level))
10091 (setq end (save-excursion
10092 (outline-next-heading)
10093 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10094 (point)))
10095 (if (and (save-excursion (re-search-forward
10096 "^[ \t]*[-+*] \\[[- X]\\]" end t))
10097 (not (save-excursion (re-search-forward
10098 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10099 (org-update-checkbox-count)
10100 (if (and l2 (> l2 l1))
10101 (progn
10102 (goto-char end)
10103 (org-update-parent-todo-statistics))
10104 (error "No data for statistics cookie"))))
10105 (goto-char pos)
10106 (move-marker pos nil)))))
10108 (defvar org-entry-property-inherited-from) ;; defined below
10109 (defun org-update-parent-todo-statistics ()
10110 "Update any statistics cookie in the parent of the current headline.
10111 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10112 the entire subtree and this will travel up the hierarchy and update
10113 statistics everywhere."
10114 (interactive)
10115 (let* ((lim 0) prop
10116 (recursive (or (not org-hierarchical-todo-statistics)
10117 (string-match
10118 "\\<recursive\\>"
10119 (or (setq prop (org-entry-get
10120 nil "COOKIE_DATA" 'inherit)) ""))))
10121 (lim (or (and prop (marker-position
10122 org-entry-property-inherited-from))
10123 lim))
10124 (first t)
10125 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10126 level ltoggle l1 new ndel
10127 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10128 (catch 'exit
10129 (save-excursion
10130 (beginning-of-line 1)
10131 (if (org-at-heading-p)
10132 (setq ltoggle (funcall outline-level))
10133 (error "This should not happen"))
10134 (while (and (setq level (org-up-heading-safe))
10135 (or recursive first)
10136 (>= (point) lim))
10137 (setq first nil cookie-present nil)
10138 (unless (and level
10139 (not (string-match
10140 "\\<checkbox\\>"
10141 (downcase
10142 (or (org-entry-get
10143 nil "COOKIE_DATA")
10144 "")))))
10145 (throw 'exit nil))
10146 (while (re-search-forward box-re (point-at-eol) t)
10147 (setq cnt-all 0 cnt-done 0 cookie-present t)
10148 (setq is-percent (match-end 2))
10149 (save-match-data
10150 (unless (outline-next-heading) (throw 'exit nil))
10151 (while (and (looking-at org-complex-heading-regexp)
10152 (> (setq l1 (length (match-string 1))) level))
10153 (setq kwd (and (or recursive (= l1 ltoggle))
10154 (match-string 2)))
10155 (if (or (eq org-provide-todo-statistics 'all-headlines)
10156 (and (listp org-provide-todo-statistics)
10157 (or (member kwd org-provide-todo-statistics)
10158 (member kwd org-done-keywords))))
10159 (setq cnt-all (1+ cnt-all))
10160 (if (eq org-provide-todo-statistics t)
10161 (and kwd (setq cnt-all (1+ cnt-all)))))
10162 (and (member kwd org-done-keywords)
10163 (setq cnt-done (1+ cnt-done)))
10164 (outline-next-heading)))
10165 (setq new
10166 (if is-percent
10167 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10168 (format "[%d/%d]" cnt-done cnt-all))
10169 ndel (- (match-end 0) (match-beginning 0)))
10170 (goto-char (match-beginning 0))
10171 (insert new)
10172 (delete-region (point) (+ (point) ndel)))
10173 (when cookie-present
10174 (run-hook-with-args 'org-after-todo-statistics-hook
10175 cnt-done (- cnt-all cnt-done))))))
10176 (run-hooks 'org-todo-statistics-hook)))
10178 (defvar org-after-todo-statistics-hook nil
10179 "Hook that is called after a TODO statistics cookie has been updated.
10180 Each function is called with two arguments: the number of not-done entries
10181 and the number of done entries.
10183 For example, the following function, when added to this hook, will switch
10184 an entry to DONE when all children are done, and back to TODO when new
10185 entries are set to a TODO status. Note that this hook is only called
10186 when there is a statistics cookie in the headline!
10188 (defun org-summary-todo (n-done n-not-done)
10189 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10190 (let (org-log-done org-log-states) ; turn off logging
10191 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10194 (defvar org-todo-statistics-hook nil
10195 "Hook that is run whenever Org thinks TODO statistics should be updated.
10196 This hook runs even if there is no statistics cookie present, in which case
10197 `org-after-todo-statistics-hook' would not run.")
10199 (defun org-todo-trigger-tag-changes (state)
10200 "Apply the changes defined in `org-todo-state-tags-triggers'."
10201 (let ((l org-todo-state-tags-triggers)
10202 changes)
10203 (when (or (not state) (equal state ""))
10204 (setq changes (append changes (cdr (assoc "" l)))))
10205 (when (and (stringp state) (> (length state) 0))
10206 (setq changes (append changes (cdr (assoc state l)))))
10207 (when (member state org-not-done-keywords)
10208 (setq changes (append changes (cdr (assoc 'todo l)))))
10209 (when (member state org-done-keywords)
10210 (setq changes (append changes (cdr (assoc 'done l)))))
10211 (dolist (c changes)
10212 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10214 (defun org-local-logging (value)
10215 "Get logging settings from a property VALUE."
10216 (let* (words w a)
10217 ;; directly set the variables, they are already local.
10218 (setq org-log-done nil
10219 org-log-repeat nil
10220 org-todo-log-states nil)
10221 (setq words (org-split-string value))
10222 (while (setq w (pop words))
10223 (cond
10224 ((setq a (assoc w org-startup-options))
10225 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10226 (set (nth 1 a) (nth 2 a))))
10227 ((setq a (org-extract-log-state-settings w))
10228 (and (member (car a) org-todo-keywords-1)
10229 (push a org-todo-log-states)))))))
10231 (defun org-get-todo-sequence-head (kwd)
10232 "Return the head of the TODO sequence to which KWD belongs.
10233 If KWD is not set, check if there is a text property remembering the
10234 right sequence."
10235 (let (p)
10236 (cond
10237 ((not kwd)
10238 (or (get-text-property (point-at-bol) 'org-todo-head)
10239 (progn
10240 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10241 nil (point-at-eol)))
10242 (get-text-property p 'org-todo-head))))
10243 ((not (member kwd org-todo-keywords-1))
10244 (car org-todo-keywords-1))
10245 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10247 (defun org-fast-todo-selection ()
10248 "Fast TODO keyword selection with single keys.
10249 Returns the new TODO keyword, or nil if no state change should occur."
10250 (let* ((fulltable org-todo-key-alist)
10251 (done-keywords org-done-keywords) ;; needed for the faces.
10252 (maxlen (apply 'max (mapcar
10253 (lambda (x)
10254 (if (stringp (car x)) (string-width (car x)) 0))
10255 fulltable)))
10256 (expert nil)
10257 (fwidth (+ maxlen 3 1 3))
10258 (ncol (/ (- (window-width) 4) fwidth))
10259 tg cnt e c tbl
10260 groups ingroup)
10261 (save-excursion
10262 (save-window-excursion
10263 (if expert
10264 (set-buffer (get-buffer-create " *Org todo*"))
10265 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10266 (erase-buffer)
10267 (org-set-local 'org-done-keywords done-keywords)
10268 (setq tbl fulltable cnt 0)
10269 (while (setq e (pop tbl))
10270 (cond
10271 ((equal e '(:startgroup))
10272 (push '() groups) (setq ingroup t)
10273 (when (not (= cnt 0))
10274 (setq cnt 0)
10275 (insert "\n"))
10276 (insert "{ "))
10277 ((equal e '(:endgroup))
10278 (setq ingroup nil cnt 0)
10279 (insert "}\n"))
10280 ((equal e '(:newline))
10281 (when (not (= cnt 0))
10282 (setq cnt 0)
10283 (insert "\n")
10284 (setq e (car tbl))
10285 (while (equal (car tbl) '(:newline))
10286 (insert "\n")
10287 (setq tbl (cdr tbl)))))
10289 (setq tg (car e) c (cdr e))
10290 (if ingroup (push tg (car groups)))
10291 (setq tg (org-add-props tg nil 'face
10292 (org-get-todo-face tg)))
10293 (if (and (= cnt 0) (not ingroup)) (insert " "))
10294 (insert "[" c "] " tg (make-string
10295 (- fwidth 4 (length tg)) ?\ ))
10296 (when (= (setq cnt (1+ cnt)) ncol)
10297 (insert "\n")
10298 (if ingroup (insert " "))
10299 (setq cnt 0)))))
10300 (insert "\n")
10301 (goto-char (point-min))
10302 (if (not expert) (org-fit-window-to-buffer))
10303 (message "[a-z..]:Set [SPC]:clear")
10304 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10305 (cond
10306 ((or (= c ?\C-g)
10307 (and (= c ?q) (not (rassoc c fulltable))))
10308 (setq quit-flag t))
10309 ((= c ?\ ) nil)
10310 ((setq e (rassoc c fulltable) tg (car e))
10312 (t (setq quit-flag t)))))))
10314 (defun org-entry-is-todo-p ()
10315 (member (org-get-todo-state) org-not-done-keywords))
10317 (defun org-entry-is-done-p ()
10318 (member (org-get-todo-state) org-done-keywords))
10320 (defun org-get-todo-state ()
10321 (save-excursion
10322 (org-back-to-heading t)
10323 (and (looking-at org-todo-line-regexp)
10324 (match-end 2)
10325 (match-string 2))))
10327 (defun org-at-date-range-p (&optional inactive-ok)
10328 "Is the cursor inside a date range?"
10329 (interactive)
10330 (save-excursion
10331 (catch 'exit
10332 (let ((pos (point)))
10333 (skip-chars-backward "^[<\r\n")
10334 (skip-chars-backward "<[")
10335 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10336 (>= (match-end 0) pos)
10337 (throw 'exit t))
10338 (skip-chars-backward "^<[\r\n")
10339 (skip-chars-backward "<[")
10340 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10341 (>= (match-end 0) pos)
10342 (throw 'exit t)))
10343 nil)))
10345 (defun org-get-repeat (&optional tagline)
10346 "Check if there is a deadline/schedule with repeater in this entry."
10347 (save-match-data
10348 (save-excursion
10349 (org-back-to-heading t)
10350 (and (re-search-forward (if tagline
10351 (concat tagline "\\s-*" org-repeat-re)
10352 org-repeat-re)
10353 (org-entry-end-position) t)
10354 (match-string-no-properties 1)))))
10356 (defvar org-last-changed-timestamp)
10357 (defvar org-last-inserted-timestamp)
10358 (defvar org-log-post-message)
10359 (defvar org-log-note-purpose)
10360 (defvar org-log-note-how)
10361 (defvar org-log-note-extra)
10362 (defun org-auto-repeat-maybe (done-word)
10363 "Check if the current headline contains a repeated deadline/schedule.
10364 If yes, set TODO state back to what it was and change the base date
10365 of repeating deadline/scheduled time stamps to new date.
10366 This function is run automatically after each state change to a DONE state."
10367 ;; last-state is dynamically scoped into this function
10368 (let* ((repeat (org-get-repeat))
10369 (aa (assoc last-state org-todo-kwd-alist))
10370 (interpret (nth 1 aa))
10371 (head (nth 2 aa))
10372 (whata '(("d" . day) ("m" . month) ("y" . year)))
10373 (msg "Entry repeats: ")
10374 (org-log-done nil)
10375 (org-todo-log-states nil)
10376 (nshiftmax 10) (nshift 0)
10377 re type n what ts time)
10378 (when repeat
10379 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10380 (org-todo (if (eq interpret 'type) last-state head))
10381 (org-entry-put nil "LAST_REPEAT" (format-time-string
10382 (org-time-stamp-format t t)))
10383 (when org-log-repeat
10384 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10385 (memq 'org-add-log-note post-command-hook))
10386 ;; OK, we are already setup for some record
10387 (if (eq org-log-repeat 'note)
10388 ;; make sure we take a note, not only a time stamp
10389 (setq org-log-note-how 'note))
10390 ;; Set up for taking a record
10391 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10392 last-state
10393 'findpos org-log-repeat)))
10394 (org-back-to-heading t)
10395 (org-add-planning-info nil nil 'closed)
10396 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10397 org-deadline-time-regexp "\\)\\|\\("
10398 org-ts-regexp "\\)"))
10399 (while (re-search-forward
10400 re (save-excursion (outline-next-heading) (point)) t)
10401 (setq type (if (match-end 1) org-scheduled-string
10402 (if (match-end 3) org-deadline-string "Plain:"))
10403 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10404 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10405 (setq n (string-to-number (match-string 2 ts))
10406 what (match-string 3 ts))
10407 (if (equal what "w") (setq n (* n 7) what "d"))
10408 ;; Preparation, see if we need to modify the start date for the change
10409 (when (match-end 1)
10410 (setq time (save-match-data (org-time-string-to-time ts)))
10411 (cond
10412 ((equal (match-string 1 ts) ".")
10413 ;; Shift starting date to today
10414 (org-timestamp-change
10415 (- (time-to-days (current-time)) (time-to-days time))
10416 'day))
10417 ((equal (match-string 1 ts) "+")
10418 (while (or (= nshift 0)
10419 (<= (time-to-days time) (time-to-days (current-time))))
10420 (when (= (incf nshift) nshiftmax)
10421 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10422 (error "Abort")))
10423 (org-timestamp-change n (cdr (assoc what whata)))
10424 (org-at-timestamp-p t)
10425 (setq ts (match-string 1))
10426 (setq time (save-match-data (org-time-string-to-time ts))))
10427 (org-timestamp-change (- n) (cdr (assoc what whata)))
10428 ;; rematch, so that we have everything in place for the real shift
10429 (org-at-timestamp-p t)
10430 (setq ts (match-string 1))
10431 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10432 (org-timestamp-change n (cdr (assoc what whata)))
10433 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10434 (setq org-log-post-message msg)
10435 (message "%s" msg))))
10437 (defun org-show-todo-tree (arg)
10438 "Make a compact tree which shows all headlines marked with TODO.
10439 The tree will show the lines where the regexp matches, and all higher
10440 headlines above the match.
10441 With a \\[universal-argument] prefix, prompt for a regexp to match.
10442 With a numeric prefix N, construct a sparse tree for the Nth element
10443 of `org-todo-keywords-1'."
10444 (interactive "P")
10445 (let ((case-fold-search nil)
10446 (kwd-re
10447 (cond ((null arg) org-not-done-regexp)
10448 ((equal arg '(4))
10449 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10450 (mapcar 'list org-todo-keywords-1))))
10451 (concat "\\("
10452 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10453 "\\)\\>")))
10454 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10455 (regexp-quote (nth (1- (prefix-numeric-value arg))
10456 org-todo-keywords-1)))
10457 (t (error "Invalid prefix argument: %s" arg)))))
10458 (message "%d TODO entries found"
10459 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10461 (defun org-deadline (&optional remove time)
10462 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10463 With argument REMOVE, remove any deadline from the item.
10464 When TIME is set, it should be an internal time specification, and the
10465 scheduling will use the corresponding date."
10466 (interactive "P")
10467 (let ((old-date (org-entry-get nil "DEADLINE")))
10468 (if remove
10469 (progn
10470 (org-remove-timestamp-with-keyword org-deadline-string)
10471 (message "Item no longer has a deadline."))
10472 (if (org-get-repeat)
10473 (error "Cannot change deadline on task with repeater, please do that by hand")
10474 (org-add-planning-info 'deadline time 'closed)
10475 (when (and old-date org-log-redeadline
10476 (not (equal old-date
10477 (substring org-last-inserted-timestamp 1 -1))))
10478 (org-add-log-setup 'redeadline nil old-date 'findpos
10479 org-log-redeadline))
10480 (message "Deadline on %s" org-last-inserted-timestamp)))))
10482 (defun org-schedule (&optional remove time)
10483 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10484 With argument REMOVE, remove any scheduling date from the item.
10485 When TIME is set, it should be an internal time specification, and the
10486 scheduling will use the corresponding date."
10487 (interactive "P")
10488 (let ((old-date (org-entry-get nil "SCHEDULED")))
10489 (if remove
10490 (progn
10491 (org-remove-timestamp-with-keyword org-scheduled-string)
10492 (message "Item is no longer scheduled."))
10493 (if (org-get-repeat)
10494 (error "Cannot reschedule task with repeater, please do that by hand")
10495 (org-add-planning-info 'scheduled time 'closed)
10496 (when (and old-date org-log-reschedule
10497 (not (equal old-date
10498 (substring org-last-inserted-timestamp 1 -1))))
10499 (org-add-log-setup 'reschedule nil old-date 'findpos
10500 org-log-reschedule))
10501 (message "Scheduled to %s" org-last-inserted-timestamp)))))
10503 (defun org-get-scheduled-time (pom &optional inherit)
10504 "Get the scheduled time as a time tuple, of a format suitable
10505 for calling org-schedule with, or if there is no scheduling,
10506 returns nil."
10507 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10508 (when time
10509 (apply 'encode-time (org-parse-time-string time)))))
10511 (defun org-get-deadline-time (pom &optional inherit)
10512 "Get the deadine as a time tuple, of a format suitable for
10513 calling org-deadline with, or if there is no scheduling, returns
10514 nil."
10515 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10516 (when time
10517 (apply 'encode-time (org-parse-time-string time)))))
10519 (defun org-remove-timestamp-with-keyword (keyword)
10520 "Remove all time stamps with KEYWORD in the current entry."
10521 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10522 beg)
10523 (save-excursion
10524 (org-back-to-heading t)
10525 (setq beg (point))
10526 (outline-next-heading)
10527 (while (re-search-backward re beg t)
10528 (replace-match "")
10529 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10530 (equal (char-before) ?\ ))
10531 (backward-delete-char 1)
10532 (if (string-match "^[ \t]*$" (buffer-substring
10533 (point-at-bol) (point-at-eol)))
10534 (delete-region (point-at-bol)
10535 (min (point-max) (1+ (point-at-eol))))))))))
10537 (defun org-add-planning-info (what &optional time &rest remove)
10538 "Insert new timestamp with keyword in the line directly after the headline.
10539 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10540 If non is given, the user is prompted for a date.
10541 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10542 be removed."
10543 (interactive)
10544 (let (org-time-was-given org-end-time-was-given ts
10545 end default-time default-input)
10547 (catch 'exit
10548 (when (and (not time) (memq what '(scheduled deadline)))
10549 ;; Try to get a default date/time from existing timestamp
10550 (save-excursion
10551 (org-back-to-heading t)
10552 (setq end (save-excursion (outline-next-heading) (point)))
10553 (when (re-search-forward (if (eq what 'scheduled)
10554 org-scheduled-time-regexp
10555 org-deadline-time-regexp)
10556 end t)
10557 (setq ts (match-string 1)
10558 default-time
10559 (apply 'encode-time (org-parse-time-string ts))
10560 default-input (and ts (org-get-compact-tod ts))))))
10561 (when what
10562 ;; If necessary, get the time from the user
10563 (setq time (or time (org-read-date nil 'to-time nil nil
10564 default-time default-input))))
10566 (when (and org-insert-labeled-timestamps-at-point
10567 (member what '(scheduled deadline)))
10568 (insert
10569 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10570 (org-insert-time-stamp time org-time-was-given
10571 nil nil nil (list org-end-time-was-given))
10572 (setq what nil))
10573 (save-excursion
10574 (save-restriction
10575 (let (col list elt ts buffer-invisibility-spec)
10576 (org-back-to-heading t)
10577 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10578 (goto-char (match-end 1))
10579 (setq col (current-column))
10580 (goto-char (match-end 0))
10581 (if (eobp) (insert "\n") (forward-char 1))
10582 (when (and (not what)
10583 (not (looking-at
10584 (concat "[ \t]*"
10585 org-keyword-time-not-clock-regexp))))
10586 ;; Nothing to add, nothing to remove...... :-)
10587 (throw 'exit nil))
10588 (if (and (not (looking-at outline-regexp))
10589 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10590 "[^\r\n]*"))
10591 (not (equal (match-string 1) org-clock-string)))
10592 (narrow-to-region (match-beginning 0) (match-end 0))
10593 (insert-before-markers "\n")
10594 (backward-char 1)
10595 (narrow-to-region (point) (point))
10596 (and org-adapt-indentation (org-indent-to-column col)))
10597 ;; Check if we have to remove something.
10598 (setq list (cons what remove))
10599 (while list
10600 (setq elt (pop list))
10601 (goto-char (point-min))
10602 (when (or (and (eq elt 'scheduled)
10603 (re-search-forward org-scheduled-time-regexp nil t))
10604 (and (eq elt 'deadline)
10605 (re-search-forward org-deadline-time-regexp nil t))
10606 (and (eq elt 'closed)
10607 (re-search-forward org-closed-time-regexp nil t)))
10608 (replace-match "")
10609 (if (looking-at "--+<[^>]+>") (replace-match ""))
10610 (skip-chars-backward " ")
10611 (if (looking-at " +") (replace-match ""))))
10612 (goto-char (point-max))
10613 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10614 (when what
10615 (insert
10616 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10617 (cond ((eq what 'scheduled) org-scheduled-string)
10618 ((eq what 'deadline) org-deadline-string)
10619 ((eq what 'closed) org-closed-string))
10620 " ")
10621 (setq ts (org-insert-time-stamp
10622 time
10623 (or org-time-was-given
10624 (and (eq what 'closed) org-log-done-with-time))
10625 (eq what 'closed)
10626 nil nil (list org-end-time-was-given)))
10627 (end-of-line 1))
10628 (goto-char (point-min))
10629 (widen)
10630 (if (and (looking-at "[ \t]+\n")
10631 (equal (char-before) ?\n))
10632 (delete-region (1- (point)) (point-at-eol)))
10633 ts))))))
10635 (defvar org-log-note-marker (make-marker))
10636 (defvar org-log-note-purpose nil)
10637 (defvar org-log-note-state nil)
10638 (defvar org-log-note-previous-state nil)
10639 (defvar org-log-note-how nil)
10640 (defvar org-log-note-extra nil)
10641 (defvar org-log-note-window-configuration nil)
10642 (defvar org-log-note-return-to (make-marker))
10643 (defvar org-log-post-message nil
10644 "Message to be displayed after a log note has been stored.
10645 The auto-repeater uses this.")
10647 (defun org-add-note ()
10648 "Add a note to the current entry.
10649 This is done in the same way as adding a state change note."
10650 (interactive)
10651 (org-add-log-setup 'note nil nil 'findpos nil))
10653 (defvar org-property-end-re)
10654 (defun org-add-log-setup (&optional purpose state prev-state
10655 findpos how &optional extra)
10656 "Set up the post command hook to take a note.
10657 If this is about to TODO state change, the new state is expected in STATE.
10658 When FINDPOS is non-nil, find the correct position for the note in
10659 the current entry. If not, assume that it can be inserted at point.
10660 HOW is an indicator what kind of note should be created.
10661 EXTRA is additional text that will be inserted into the notes buffer."
10662 (let* ((org-log-into-drawer (org-log-into-drawer))
10663 (drawer (cond ((stringp org-log-into-drawer)
10664 org-log-into-drawer)
10665 (org-log-into-drawer "LOGBOOK")
10666 (t nil))))
10667 (save-restriction
10668 (save-excursion
10669 (when findpos
10670 (org-back-to-heading t)
10671 (narrow-to-region (point) (save-excursion
10672 (outline-next-heading) (point)))
10673 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10674 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10675 "[^\r\n]*\\)?"))
10676 (goto-char (match-end 0))
10677 (cond
10678 (drawer
10679 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10680 nil t)
10681 (progn
10682 (goto-char (match-end 0))
10683 (or org-log-states-order-reversed
10684 (and (re-search-forward org-property-end-re nil t)
10685 (goto-char (1- (match-beginning 0))))))
10686 (insert "\n:" drawer ":\n:END:")
10687 (beginning-of-line 0)
10688 (org-indent-line-function)
10689 (beginning-of-line 2)
10690 (org-indent-line-function)
10691 (end-of-line 0)))
10692 ((and org-log-state-notes-insert-after-drawers
10693 (save-excursion
10694 (forward-line) (looking-at org-drawer-regexp)))
10695 (forward-line)
10696 (while (looking-at org-drawer-regexp)
10697 (goto-char (match-end 0))
10698 (re-search-forward org-property-end-re (point-max) t)
10699 (forward-line))
10700 (forward-line -1)))
10701 (unless org-log-states-order-reversed
10702 (and (= (char-after) ?\n) (forward-char 1))
10703 (org-skip-over-state-notes)
10704 (skip-chars-backward " \t\n\r")))
10705 (move-marker org-log-note-marker (point))
10706 (setq org-log-note-purpose purpose
10707 org-log-note-state state
10708 org-log-note-previous-state prev-state
10709 org-log-note-how how
10710 org-log-note-extra extra)
10711 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10713 (defun org-skip-over-state-notes ()
10714 "Skip past the list of State notes in an entry."
10715 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10716 (while (looking-at "[ \t]*- State")
10717 (condition-case nil
10718 (org-next-item)
10719 (error (org-end-of-item)))))
10721 (defun org-add-log-note (&optional purpose)
10722 "Pop up a window for taking a note, and add this note later at point."
10723 (remove-hook 'post-command-hook 'org-add-log-note)
10724 (setq org-log-note-window-configuration (current-window-configuration))
10725 (delete-other-windows)
10726 (move-marker org-log-note-return-to (point))
10727 (switch-to-buffer (marker-buffer org-log-note-marker))
10728 (goto-char org-log-note-marker)
10729 (org-switch-to-buffer-other-window "*Org Note*")
10730 (erase-buffer)
10731 (if (memq org-log-note-how '(time state))
10732 (let (current-prefix-arg) (org-store-log-note))
10733 (let ((org-inhibit-startup t)) (org-mode))
10734 (insert (format "# Insert note for %s.
10735 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10736 (cond
10737 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10738 ((eq org-log-note-purpose 'done) "closed todo item")
10739 ((eq org-log-note-purpose 'state)
10740 (format "state change from \"%s\" to \"%s\""
10741 (or org-log-note-previous-state "")
10742 (or org-log-note-state "")))
10743 ((eq org-log-note-purpose 'reschedule)
10744 "rescheduling")
10745 ((eq org-log-note-purpose 'redeadline)
10746 "changing deadline")
10747 ((eq org-log-note-purpose 'note)
10748 "this entry")
10749 (t (error "This should not happen")))))
10750 (if org-log-note-extra (insert org-log-note-extra))
10751 (org-set-local 'org-finish-function 'org-store-log-note)))
10753 (defvar org-note-abort nil) ; dynamically scoped
10754 (defun org-store-log-note ()
10755 "Finish taking a log note, and insert it to where it belongs."
10756 (let ((txt (buffer-string))
10757 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10758 lines ind)
10759 (kill-buffer (current-buffer))
10760 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10761 (setq txt (replace-match "" t t txt)))
10762 (if (string-match "\\s-+\\'" txt)
10763 (setq txt (replace-match "" t t txt)))
10764 (setq lines (org-split-string txt "\n"))
10765 (when (and note (string-match "\\S-" note))
10766 (setq note
10767 (org-replace-escapes
10768 note
10769 (list (cons "%u" (user-login-name))
10770 (cons "%U" user-full-name)
10771 (cons "%t" (format-time-string
10772 (org-time-stamp-format 'long 'inactive)
10773 (current-time)))
10774 (cons "%s" (if org-log-note-state
10775 (concat "\"" org-log-note-state "\"")
10776 ""))
10777 (cons "%S" (if org-log-note-previous-state
10778 (concat "\"" org-log-note-previous-state "\"")
10779 "\"\"")))))
10780 (if lines (setq note (concat note " \\\\")))
10781 (push note lines))
10782 (when (or current-prefix-arg org-note-abort)
10783 (when org-log-into-drawer
10784 (org-remove-empty-drawer-at
10785 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10786 org-log-note-marker))
10787 (setq lines nil))
10788 (when lines
10789 (with-current-buffer (marker-buffer org-log-note-marker)
10790 (save-excursion
10791 (goto-char org-log-note-marker)
10792 (move-marker org-log-note-marker nil)
10793 (end-of-line 1)
10794 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10795 (insert "- " (pop lines))
10796 (org-indent-line-function)
10797 (beginning-of-line 1)
10798 (looking-at "[ \t]*")
10799 (setq ind (concat (match-string 0) " "))
10800 (end-of-line 1)
10801 (while lines (insert "\n" ind (pop lines)))
10802 (message "Note stored")
10803 (org-back-to-heading t)
10804 (org-cycle-hide-drawers 'children)))))
10805 (set-window-configuration org-log-note-window-configuration)
10806 (with-current-buffer (marker-buffer org-log-note-return-to)
10807 (goto-char org-log-note-return-to))
10808 (move-marker org-log-note-return-to nil)
10809 (and org-log-post-message (message "%s" org-log-post-message)))
10811 (defun org-remove-empty-drawer-at (drawer pos)
10812 "Remove an empty drawer DRAWER at position POS.
10813 POS may also be a marker."
10814 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10815 (save-excursion
10816 (save-restriction
10817 (widen)
10818 (goto-char pos)
10819 (if (org-in-regexp
10820 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10821 (replace-match ""))))))
10823 (defun org-sparse-tree (&optional arg)
10824 "Create a sparse tree, prompt for the details.
10825 This command can create sparse trees. You first need to select the type
10826 of match used to create the tree:
10828 t Show entries with a specific TODO keyword.
10829 m Show entries selected by a tags/property match.
10830 p Enter a property name and its value (both with completion on existing
10831 names/values) and show entries with that property.
10832 / Show entries matching a regular expression (`r' can be used as well)
10833 d Show deadlines due within `org-deadline-warning-days'.
10834 b Show deadlines and scheduled items before a date.
10835 a Show deadlines and scheduled items after a date."
10836 (interactive "P")
10837 (let (ans kwd value)
10838 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10839 (setq ans (read-char-exclusive))
10840 (cond
10841 ((equal ans ?d)
10842 (call-interactively 'org-check-deadlines))
10843 ((equal ans ?b)
10844 (call-interactively 'org-check-before-date))
10845 ((equal ans ?a)
10846 (call-interactively 'org-check-after-date))
10847 ((equal ans ?t)
10848 (org-show-todo-tree '(4)))
10849 ((member ans '(?T ?m))
10850 (call-interactively 'org-match-sparse-tree))
10851 ((member ans '(?p ?P))
10852 (setq kwd (org-icompleting-read "Property: "
10853 (mapcar 'list (org-buffer-property-keys))))
10854 (setq value (org-icompleting-read "Value: "
10855 (mapcar 'list (org-property-values kwd))))
10856 (unless (string-match "\\`{.*}\\'" value)
10857 (setq value (concat "\"" value "\"")))
10858 (org-match-sparse-tree arg (concat kwd "=" value)))
10859 ((member ans '(?r ?R ?/))
10860 (call-interactively 'org-occur))
10861 (t (error "No such sparse tree command \"%c\"" ans)))))
10863 (defvar org-occur-highlights nil
10864 "List of overlays used for occur matches.")
10865 (make-variable-buffer-local 'org-occur-highlights)
10866 (defvar org-occur-parameters nil
10867 "Parameters of the active org-occur calls.
10868 This is a list, each call to org-occur pushes as cons cell,
10869 containing the regular expression and the callback, onto the list.
10870 The list can contain several entries if `org-occur' has been called
10871 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10872 will only contain one set of parameters. When the highlights are
10873 removed (for example with `C-c C-c', or with the next edit (depending
10874 on `org-remove-highlights-with-change'), this variable is emptied
10875 as well.")
10876 (make-variable-buffer-local 'org-occur-parameters)
10878 (defun org-occur (regexp &optional keep-previous callback)
10879 "Make a compact tree which shows all matches of REGEXP.
10880 The tree will show the lines where the regexp matches, and all higher
10881 headlines above the match. It will also show the heading after the match,
10882 to make sure editing the matching entry is easy.
10883 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10884 call to `org-occur' will be kept, to allow stacking of calls to this
10885 command.
10886 If CALLBACK is non-nil, it is a function which is called to confirm
10887 that the match should indeed be shown."
10888 (interactive "sRegexp: \nP")
10889 (when (equal regexp "")
10890 (error "Regexp cannot be empty"))
10891 (unless keep-previous
10892 (org-remove-occur-highlights nil nil t))
10893 (push (cons regexp callback) org-occur-parameters)
10894 (let ((cnt 0))
10895 (save-excursion
10896 (goto-char (point-min))
10897 (if (or (not keep-previous) ; do not want to keep
10898 (not org-occur-highlights)) ; no previous matches
10899 ;; hide everything
10900 (org-overview))
10901 (while (re-search-forward regexp nil t)
10902 (when (or (not callback)
10903 (save-match-data (funcall callback)))
10904 (setq cnt (1+ cnt))
10905 (when org-highlight-sparse-tree-matches
10906 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10907 (org-show-context 'occur-tree))))
10908 (when org-remove-highlights-with-change
10909 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10910 nil 'local))
10911 (unless org-sparse-tree-open-archived-trees
10912 (org-hide-archived-subtrees (point-min) (point-max)))
10913 (run-hooks 'org-occur-hook)
10914 (if (interactive-p)
10915 (message "%d match(es) for regexp %s" cnt regexp))
10916 cnt))
10918 (defun org-show-context (&optional key)
10919 "Make sure point and context and visible.
10920 How much context is shown depends upon the variables
10921 `org-show-hierarchy-above', `org-show-following-heading'. and
10922 `org-show-siblings'."
10923 (let ((heading-p (org-on-heading-p t))
10924 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10925 (following-p (org-get-alist-option org-show-following-heading key))
10926 (entry-p (org-get-alist-option org-show-entry-below key))
10927 (siblings-p (org-get-alist-option org-show-siblings key)))
10928 (catch 'exit
10929 ;; Show heading or entry text
10930 (if (and heading-p (not entry-p))
10931 (org-flag-heading nil) ; only show the heading
10932 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10933 (org-show-hidden-entry))) ; show entire entry
10934 (when following-p
10935 ;; Show next sibling, or heading below text
10936 (save-excursion
10937 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10938 (org-flag-heading nil))))
10939 (when siblings-p (org-show-siblings))
10940 (when hierarchy-p
10941 ;; show all higher headings, possibly with siblings
10942 (save-excursion
10943 (while (and (condition-case nil
10944 (progn (org-up-heading-all 1) t)
10945 (error nil))
10946 (not (bobp)))
10947 (org-flag-heading nil)
10948 (when siblings-p (org-show-siblings))))))))
10950 (defun org-reveal (&optional siblings)
10951 "Show current entry, hierarchy above it, and the following headline.
10952 This can be used to show a consistent set of context around locations
10953 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10954 not t for the search context.
10956 With optional argument SIBLINGS, on each level of the hierarchy all
10957 siblings are shown. This repairs the tree structure to what it would
10958 look like when opened with hierarchical calls to `org-cycle'."
10959 (interactive "P")
10960 (let ((org-show-hierarchy-above t)
10961 (org-show-following-heading t)
10962 (org-show-siblings (if siblings t org-show-siblings)))
10963 (org-show-context nil)))
10965 (defun org-highlight-new-match (beg end)
10966 "Highlight from BEG to END and mark the highlight is an occur headline."
10967 (let ((ov (org-make-overlay beg end)))
10968 (org-overlay-put ov 'face 'secondary-selection)
10969 (push ov org-occur-highlights)))
10971 (defun org-remove-occur-highlights (&optional beg end noremove)
10972 "Remove the occur highlights from the buffer.
10973 BEG and END are ignored. If NOREMOVE is nil, remove this function
10974 from the `before-change-functions' in the current buffer."
10975 (interactive)
10976 (unless org-inhibit-highlight-removal
10977 (mapc 'org-delete-overlay org-occur-highlights)
10978 (setq org-occur-highlights nil)
10979 (setq org-occur-parameters nil)
10980 (unless noremove
10981 (remove-hook 'before-change-functions
10982 'org-remove-occur-highlights 'local))))
10984 ;;;; Priorities
10986 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10987 "Regular expression matching the priority indicator.")
10989 (defvar org-remove-priority-next-time nil)
10991 (defun org-priority-up ()
10992 "Increase the priority of the current item."
10993 (interactive)
10994 (org-priority 'up))
10996 (defun org-priority-down ()
10997 "Decrease the priority of the current item."
10998 (interactive)
10999 (org-priority 'down))
11001 (defun org-priority (&optional action)
11002 "Change the priority of an item by ARG.
11003 ACTION can be `set', `up', `down', or a character."
11004 (interactive)
11005 (unless org-enable-priority-commands
11006 (error "Priority commands are disabled"))
11007 (setq action (or action 'set))
11008 (let (current new news have remove)
11009 (save-excursion
11010 (org-back-to-heading t)
11011 (if (looking-at org-priority-regexp)
11012 (setq current (string-to-char (match-string 2))
11013 have t)
11014 (setq current org-default-priority))
11015 (cond
11016 ((eq action 'remove)
11017 (setq remove t new ?\ ))
11018 ((or (eq action 'set)
11019 (if (featurep 'xemacs) (characterp action) (integerp action)))
11020 (if (not (eq action 'set))
11021 (setq new action)
11022 (message "Priority %c-%c, SPC to remove: "
11023 org-highest-priority org-lowest-priority)
11024 (setq new (read-char-exclusive)))
11025 (if (and (= (upcase org-highest-priority) org-highest-priority)
11026 (= (upcase org-lowest-priority) org-lowest-priority))
11027 (setq new (upcase new)))
11028 (cond ((equal new ?\ ) (setq remove t))
11029 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11030 (error "Priority must be between `%c' and `%c'"
11031 org-highest-priority org-lowest-priority))))
11032 ((eq action 'up)
11033 (if (and (not have) (eq last-command this-command))
11034 (setq new org-lowest-priority)
11035 (setq new (if (and org-priority-start-cycle-with-default (not have))
11036 org-default-priority (1- current)))))
11037 ((eq action 'down)
11038 (if (and (not have) (eq last-command this-command))
11039 (setq new org-highest-priority)
11040 (setq new (if (and org-priority-start-cycle-with-default (not have))
11041 org-default-priority (1+ current)))))
11042 (t (error "Invalid action")))
11043 (if (or (< (upcase new) org-highest-priority)
11044 (> (upcase new) org-lowest-priority))
11045 (setq remove t))
11046 (setq news (format "%c" new))
11047 (if have
11048 (if remove
11049 (replace-match "" t t nil 1)
11050 (replace-match news t t nil 2))
11051 (if remove
11052 (error "No priority cookie found in line")
11053 (let ((case-fold-search nil))
11054 (looking-at org-todo-line-regexp))
11055 (if (match-end 2)
11056 (progn
11057 (goto-char (match-end 2))
11058 (insert " [#" news "]"))
11059 (goto-char (match-beginning 3))
11060 (insert "[#" news "] "))))
11061 (org-preserve-lc (org-set-tags nil 'align)))
11062 (if remove
11063 (message "Priority removed")
11064 (message "Priority of current item set to %s" news))))
11066 (defun org-get-priority (s)
11067 "Find priority cookie and return priority."
11068 (save-match-data
11069 (if (not (string-match org-priority-regexp s))
11070 (* 1000 (- org-lowest-priority org-default-priority))
11071 (* 1000 (- org-lowest-priority
11072 (string-to-char (match-string 2 s)))))))
11074 ;;;; Tags
11076 (defvar org-agenda-archives-mode)
11077 (defvar org-map-continue-from nil
11078 "Position from where mapping should continue.
11079 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11081 (defvar org-scanner-tags nil
11082 "The current tag list while the tags scanner is running.")
11083 (defvar org-trust-scanner-tags nil
11084 "Should `org-get-tags-at' use the tags fro the scanner.
11085 This is for internal dynamical scoping only.
11086 When this is non-nil, the function `org-get-tags-at' will return the value
11087 of `org-scanner-tags' instead of building the list by itself. This
11088 can lead to large speed-ups when the tags scanner is used in a file with
11089 many entries, and when the list of tags is retrieved, for example to
11090 obtain a list of properties. Building the tags list for each entry in such
11091 a file becomes an N^2 operation - but with this variable set, it scales
11092 as N.")
11094 (defun org-scan-tags (action matcher &optional todo-only)
11095 "Scan headline tags with inheritance and produce output ACTION.
11097 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11098 or `agenda' to produce an entry list for an agenda view. It can also be
11099 a Lisp form or a function that should be called at each matched headline, in
11100 this case the return value is a list of all return values from these calls.
11102 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11103 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11104 only lines with a TODO keyword are included in the output."
11105 (require 'org-agenda)
11106 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11107 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11108 (org-re
11109 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11110 (props (list 'face 'default
11111 'done-face 'org-agenda-done
11112 'undone-face 'default
11113 'mouse-face 'highlight
11114 'org-not-done-regexp org-not-done-regexp
11115 'org-todo-regexp org-todo-regexp
11116 'help-echo
11117 (format "mouse-2 or RET jump to org file %s"
11118 (abbreviate-file-name
11119 (or (buffer-file-name (buffer-base-buffer))
11120 (buffer-name (buffer-base-buffer)))))))
11121 (case-fold-search nil)
11122 (org-map-continue-from nil)
11123 lspos tags tags-list
11124 (tags-alist (list (cons 0 org-file-tags)))
11125 (llast 0) rtn rtn1 level category i txt
11126 todo marker entry priority)
11127 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11128 (setq action (list 'lambda nil action)))
11129 (save-excursion
11130 (goto-char (point-min))
11131 (when (eq action 'sparse-tree)
11132 (org-overview)
11133 (org-remove-occur-highlights))
11134 (while (re-search-forward re nil t)
11135 (catch :skip
11136 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11137 tags (if (match-end 4) (org-match-string-no-properties 4)))
11138 (goto-char (setq lspos (match-beginning 0)))
11139 (setq level (org-reduced-level (funcall outline-level))
11140 category (org-get-category))
11141 (setq i llast llast level)
11142 ;; remove tag lists from same and sublevels
11143 (while (>= i level)
11144 (when (setq entry (assoc i tags-alist))
11145 (setq tags-alist (delete entry tags-alist)))
11146 (setq i (1- i)))
11147 ;; add the next tags
11148 (when tags
11149 (setq tags (org-split-string tags ":")
11150 tags-alist
11151 (cons (cons level tags) tags-alist)))
11152 ;; compile tags for current headline
11153 (setq tags-list
11154 (if org-use-tag-inheritance
11155 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11156 tags)
11157 org-scanner-tags tags-list)
11158 (when org-use-tag-inheritance
11159 (setcdr (car tags-alist)
11160 (mapcar (lambda (x)
11161 (setq x (copy-sequence x))
11162 (org-add-prop-inherited x))
11163 (cdar tags-alist))))
11164 (when (and tags org-use-tag-inheritance
11165 (or (not (eq t org-use-tag-inheritance))
11166 org-tags-exclude-from-inheritance))
11167 ;; selective inheritance, remove uninherited ones
11168 (setcdr (car tags-alist)
11169 (org-remove-uniherited-tags (cdar tags-alist))))
11170 (when (and (or (not todo-only)
11171 (and (member todo org-not-done-keywords)
11172 (or (not org-agenda-tags-todo-honor-ignore-options)
11173 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11174 (let ((case-fold-search t)) (eval matcher))
11176 (not (member org-archive-tag tags-list))
11177 ;; we have an archive tag, should we use this anyway?
11178 (or (not org-agenda-skip-archived-trees)
11179 (and (eq action 'agenda) org-agenda-archives-mode))))
11180 (unless (eq action 'sparse-tree) (org-agenda-skip))
11182 ;; select this headline
11184 (cond
11185 ((eq action 'sparse-tree)
11186 (and org-highlight-sparse-tree-matches
11187 (org-get-heading) (match-end 0)
11188 (org-highlight-new-match
11189 (match-beginning 0) (match-beginning 1)))
11190 (org-show-context 'tags-tree))
11191 ((eq action 'agenda)
11192 (setq txt (org-format-agenda-item
11194 (concat
11195 (if (eq org-tags-match-list-sublevels 'indented)
11196 (make-string (1- level) ?.) "")
11197 (org-get-heading))
11198 category
11199 tags-list
11201 priority (org-get-priority txt))
11202 (goto-char lspos)
11203 (setq marker (org-agenda-new-marker))
11204 (org-add-props txt props
11205 'org-marker marker 'org-hd-marker marker 'org-category category
11206 'todo-state todo
11207 'priority priority 'type "tagsmatch")
11208 (push txt rtn))
11209 ((functionp action)
11210 (setq org-map-continue-from nil)
11211 (save-excursion
11212 (setq rtn1 (funcall action))
11213 (push rtn1 rtn)))
11214 (t (error "Invalid action")))
11216 ;; if we are to skip sublevels, jump to end of subtree
11217 (unless org-tags-match-list-sublevels
11218 (org-end-of-subtree t)
11219 (backward-char 1))))
11220 ;; Get the correct position from where to continue
11221 (if org-map-continue-from
11222 (goto-char org-map-continue-from)
11223 (and (= (point) lspos) (end-of-line 1)))))
11224 (when (and (eq action 'sparse-tree)
11225 (not org-sparse-tree-open-archived-trees))
11226 (org-hide-archived-subtrees (point-min) (point-max)))
11227 (nreverse rtn)))
11229 (defun org-remove-uniherited-tags (tags)
11230 "Remove all tags that are not inherited from the list TAGS."
11231 (cond
11232 ((eq org-use-tag-inheritance t)
11233 (if org-tags-exclude-from-inheritance
11234 (org-delete-all org-tags-exclude-from-inheritance tags)
11235 tags))
11236 ((not org-use-tag-inheritance) nil)
11237 ((stringp org-use-tag-inheritance)
11238 (delq nil (mapcar
11239 (lambda (x)
11240 (if (and (string-match org-use-tag-inheritance x)
11241 (not (member x org-tags-exclude-from-inheritance)))
11242 x nil))
11243 tags)))
11244 ((listp org-use-tag-inheritance)
11245 (delq nil (mapcar
11246 (lambda (x)
11247 (if (member x org-use-tag-inheritance) x nil))
11248 tags)))))
11250 (defvar todo-only) ;; dynamically scoped
11252 (defun org-match-sparse-tree (&optional todo-only match)
11253 "Create a sparse tree according to tags string MATCH.
11254 MATCH can contain positive and negative selection of tags, like
11255 \"+WORK+URGENT-WITHBOSS\".
11256 If optional argument TODO-ONLY is non-nil, only select lines that are
11257 also TODO lines."
11258 (interactive "P")
11259 (org-prepare-agenda-buffers (list (current-buffer)))
11260 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11262 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11264 (defvar org-cached-props nil)
11265 (defun org-cached-entry-get (pom property)
11266 (if (or (eq t org-use-property-inheritance)
11267 (and (stringp org-use-property-inheritance)
11268 (string-match org-use-property-inheritance property))
11269 (and (listp org-use-property-inheritance)
11270 (member property org-use-property-inheritance)))
11271 ;; Caching is not possible, check it directly
11272 (org-entry-get pom property 'inherit)
11273 ;; Get all properties, so that we can do complicated checks easily
11274 (cdr (assoc property (or org-cached-props
11275 (setq org-cached-props
11276 (org-entry-properties pom)))))))
11278 (defun org-global-tags-completion-table (&optional files)
11279 "Return the list of all tags in all agenda buffer/files."
11280 (save-excursion
11281 (org-uniquify
11282 (delq nil
11283 (apply 'append
11284 (mapcar
11285 (lambda (file)
11286 (set-buffer (find-file-noselect file))
11287 (append (org-get-buffer-tags)
11288 (mapcar (lambda (x) (if (stringp (car-safe x))
11289 (list (car-safe x)) nil))
11290 org-tag-alist)))
11291 (if (and files (car files))
11292 files
11293 (org-agenda-files))))))))
11295 (defun org-make-tags-matcher (match)
11296 "Create the TAGS//TODO matcher form for the selection string MATCH."
11297 ;; todo-only is scoped dynamically into this function, and the function
11298 ;; may change it if the matcher asks for it.
11299 (unless match
11300 ;; Get a new match request, with completion
11301 (let ((org-last-tags-completion-table
11302 (org-global-tags-completion-table)))
11303 (setq match (org-completing-read-no-i
11304 "Match: " 'org-tags-completion-function nil nil nil
11305 'org-tags-history))))
11307 ;; Parse the string and create a lisp form
11308 (let ((match0 match)
11309 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11310 minus tag mm
11311 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11312 orterms term orlist re-p str-p level-p level-op time-p
11313 prop-p pn pv po cat-p gv rest)
11314 (if (string-match "/+" match)
11315 ;; match contains also a todo-matching request
11316 (progn
11317 (setq tagsmatch (substring match 0 (match-beginning 0))
11318 todomatch (substring match (match-end 0)))
11319 (if (string-match "^!" todomatch)
11320 (setq todo-only t todomatch (substring todomatch 1)))
11321 (if (string-match "^\\s-*$" todomatch)
11322 (setq todomatch nil)))
11323 ;; only matching tags
11324 (setq tagsmatch match todomatch nil))
11326 ;; Make the tags matcher
11327 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11328 (setq tagsmatcher t)
11329 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11330 (while (setq term (pop orterms))
11331 (while (and (equal (substring term -1) "\\") orterms)
11332 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11333 (while (string-match re term)
11334 (setq rest (substring term (match-end 0))
11335 minus (and (match-end 1)
11336 (equal (match-string 1 term) "-"))
11337 tag (match-string 2 term)
11338 re-p (equal (string-to-char tag) ?{)
11339 level-p (match-end 4)
11340 prop-p (match-end 5)
11341 mm (cond
11342 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11343 (level-p
11344 (setq level-op (org-op-to-function (match-string 3 term)))
11345 `(,level-op level ,(string-to-number
11346 (match-string 4 term))))
11347 (prop-p
11348 (setq pn (match-string 5 term)
11349 po (match-string 6 term)
11350 pv (match-string 7 term)
11351 cat-p (equal pn "CATEGORY")
11352 re-p (equal (string-to-char pv) ?{)
11353 str-p (equal (string-to-char pv) ?\")
11354 time-p (save-match-data
11355 (string-match "^\"[[<].*[]>]\"$" pv))
11356 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11357 (if time-p (setq pv (org-matcher-time pv)))
11358 (setq po (org-op-to-function po (if time-p 'time str-p)))
11359 (cond
11360 ((equal pn "CATEGORY")
11361 (setq gv '(get-text-property (point) 'org-category)))
11362 ((equal pn "TODO")
11363 (setq gv 'todo))
11365 (setq gv `(org-cached-entry-get nil ,pn))))
11366 (if re-p
11367 (if (eq po 'org<>)
11368 `(not (string-match ,pv (or ,gv "")))
11369 `(string-match ,pv (or ,gv "")))
11370 (if str-p
11371 `(,po (or ,gv "") ,pv)
11372 `(,po (string-to-number (or ,gv ""))
11373 ,(string-to-number pv) ))))
11374 (t `(member ,tag tags-list)))
11375 mm (if minus (list 'not mm) mm)
11376 term rest)
11377 (push mm tagsmatcher))
11378 (push (if (> (length tagsmatcher) 1)
11379 (cons 'and tagsmatcher)
11380 (car tagsmatcher))
11381 orlist)
11382 (setq tagsmatcher nil))
11383 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11384 (setq tagsmatcher
11385 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11386 ;; Make the todo matcher
11387 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11388 (setq todomatcher t)
11389 (setq orterms (org-split-string todomatch "|") orlist nil)
11390 (while (setq term (pop orterms))
11391 (while (string-match re term)
11392 (setq minus (and (match-end 1)
11393 (equal (match-string 1 term) "-"))
11394 kwd (match-string 2 term)
11395 re-p (equal (string-to-char kwd) ?{)
11396 term (substring term (match-end 0))
11397 mm (if re-p
11398 `(string-match ,(substring kwd 1 -1) todo)
11399 (list 'equal 'todo kwd))
11400 mm (if minus (list 'not mm) mm))
11401 (push mm todomatcher))
11402 (push (if (> (length todomatcher) 1)
11403 (cons 'and todomatcher)
11404 (car todomatcher))
11405 orlist)
11406 (setq todomatcher nil))
11407 (setq todomatcher (if (> (length orlist) 1)
11408 (cons 'or orlist) (car orlist))))
11410 ;; Return the string and lisp forms of the matcher
11411 (setq matcher (if todomatcher
11412 (list 'and tagsmatcher todomatcher)
11413 tagsmatcher))
11414 (cons match0 matcher)))
11416 (defun org-op-to-function (op &optional stringp)
11417 "Turn an operator into the appropriate function."
11418 (setq op
11419 (cond
11420 ((equal op "<" ) '(< string< org-time<))
11421 ((equal op ">" ) '(> org-string> org-time>))
11422 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11423 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11424 ((member op '("=" "==")) '(= string= org-time=))
11425 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11426 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11428 (defun org<> (a b) (not (= a b)))
11429 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11430 (defun org-string>= (a b) (not (string< a b)))
11431 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11432 (defun org-string<> (a b) (not (string= a b)))
11433 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11434 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11435 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11436 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11437 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11438 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11439 (defun org-2ft (s)
11440 "Convert S to a floating point time.
11441 If S is already a number, just return it. If it is a string, parse
11442 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11443 (cond
11444 ((numberp s) s)
11445 ((stringp s)
11446 (condition-case nil
11447 (float-time (apply 'encode-time (org-parse-time-string s)))
11448 (error 0.)))
11449 (t 0.)))
11451 (defun org-time-today ()
11452 "Time in seconds today at 0:00.
11453 Returns the float number of seconds since the beginning of the
11454 epoch to the beginning of today (00:00)."
11455 (float-time (apply 'encode-time
11456 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11458 (defun org-matcher-time (s)
11459 "Interpret a time comparison value."
11460 (save-match-data
11461 (cond
11462 ((string= s "<now>") (float-time))
11463 ((string= s "<today>") (org-time-today))
11464 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11465 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11466 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11467 (+ (org-time-today)
11468 (* (string-to-number (match-string 1 s))
11469 (cdr (assoc (match-string 2 s)
11470 '(("d" . 86400.0) ("w" . 604800.0)
11471 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11472 (t (org-2ft s)))))
11474 (defun org-match-any-p (re list)
11475 "Does re match any element of list?"
11476 (setq list (mapcar (lambda (x) (string-match re x)) list))
11477 (delq nil list))
11479 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11480 (defvar org-tags-overlay (org-make-overlay 1 1))
11481 (org-detach-overlay org-tags-overlay)
11483 (defun org-get-local-tags-at (&optional pos)
11484 "Get a list of tags defined in the current headline."
11485 (org-get-tags-at pos 'local))
11487 (defun org-get-local-tags ()
11488 "Get a list of tags defined in the current headline."
11489 (org-get-tags-at nil 'local))
11491 (defun org-get-tags-at (&optional pos local)
11492 "Get a list of all headline tags applicable at POS.
11493 POS defaults to point. If tags are inherited, the list contains
11494 the targets in the same sequence as the headlines appear, i.e.
11495 the tags of the current headline come last.
11496 When LOCAL is non-nil, only return tags from the current headline,
11497 ignore inherited ones."
11498 (interactive)
11499 (if (and org-trust-scanner-tags
11500 (or (not pos) (equal pos (point)))
11501 (not local))
11502 org-scanner-tags
11503 (let (tags ltags lastpos parent)
11504 (save-excursion
11505 (save-restriction
11506 (widen)
11507 (goto-char (or pos (point)))
11508 (save-match-data
11509 (catch 'done
11510 (condition-case nil
11511 (progn
11512 (org-back-to-heading t)
11513 (while (not (equal lastpos (point)))
11514 (setq lastpos (point))
11515 (when (looking-at
11516 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11517 (setq ltags (org-split-string
11518 (org-match-string-no-properties 1) ":"))
11519 (when parent
11520 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11521 (setq tags (append
11522 (if parent
11523 (org-remove-uniherited-tags ltags)
11524 ltags)
11525 tags)))
11526 (or org-use-tag-inheritance (throw 'done t))
11527 (if local (throw 'done t))
11528 (or (org-up-heading-safe) (error nil))
11529 (setq parent t)))
11530 (error nil)))))
11531 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11533 (defun org-add-prop-inherited (s)
11534 (add-text-properties 0 (length s) '(inherited t) s)
11537 (defun org-toggle-tag (tag &optional onoff)
11538 "Toggle the tag TAG for the current line.
11539 If ONOFF is `on' or `off', don't toggle but set to this state."
11540 (let (res current)
11541 (save-excursion
11542 (org-back-to-heading t)
11543 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11544 (point-at-eol) t)
11545 (progn
11546 (setq current (match-string 1))
11547 (replace-match ""))
11548 (setq current ""))
11549 (setq current (nreverse (org-split-string current ":")))
11550 (cond
11551 ((eq onoff 'on)
11552 (setq res t)
11553 (or (member tag current) (push tag current)))
11554 ((eq onoff 'off)
11555 (or (not (member tag current)) (setq current (delete tag current))))
11556 (t (if (member tag current)
11557 (setq current (delete tag current))
11558 (setq res t)
11559 (push tag current))))
11560 (end-of-line 1)
11561 (if current
11562 (progn
11563 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11564 (org-set-tags nil t))
11565 (delete-horizontal-space))
11566 (run-hooks 'org-after-tags-change-hook))
11567 res))
11569 (defun org-align-tags-here (to-col)
11570 ;; Assumes that this is a headline
11571 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11572 (beginning-of-line 1)
11573 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11574 (< pos (match-beginning 2)))
11575 (progn
11576 (setq tags-l (- (match-end 2) (match-beginning 2)))
11577 (goto-char (match-beginning 1))
11578 (insert " ")
11579 (delete-region (point) (1+ (match-beginning 2)))
11580 (setq ncol (max (1+ (current-column))
11581 (1+ col)
11582 (if (> to-col 0)
11583 to-col
11584 (- (abs to-col) tags-l))))
11585 (setq p (point))
11586 (insert (make-string (- ncol (current-column)) ?\ ))
11587 (setq ncol (current-column))
11588 (when indent-tabs-mode (tabify p (point-at-eol)))
11589 (org-move-to-column (min ncol col) t))
11590 (goto-char pos))))
11592 (defun org-set-tags-command (&optional arg just-align)
11593 "Call the set-tags command for the current entry."
11594 (interactive "P")
11595 (if (org-on-heading-p)
11596 (org-set-tags arg just-align)
11597 (save-excursion
11598 (org-back-to-heading t)
11599 (org-set-tags arg just-align))))
11601 (defun org-set-tags-to (data)
11602 "Set the tags of the current entry to DATA, replacing the current tags.
11603 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11604 If DATA is nil or the empty string, any tags will be removed."
11605 (interactive "sTags: ")
11606 (setq data
11607 (cond
11608 ((eq data nil) "")
11609 ((equal data "") "")
11610 ((stringp data)
11611 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11612 ":"))
11613 ((listp data)
11614 (concat ":" (mapconcat 'identity data ":") ":"))
11615 (t nil)))
11616 (when data
11617 (save-excursion
11618 (org-back-to-heading t)
11619 (when (looking-at org-complex-heading-regexp)
11620 (if (match-end 5)
11621 (progn
11622 (goto-char (match-beginning 5))
11623 (insert data)
11624 (delete-region (point) (point-at-eol))
11625 (org-set-tags nil 'align))
11626 (goto-char (point-at-eol))
11627 (insert " " data)
11628 (org-set-tags nil 'align)))
11629 (beginning-of-line 1)
11630 (if (looking-at ".*?\\([ \t]+\\)$")
11631 (delete-region (match-beginning 1) (match-end 1))))))
11633 (defun org-set-tags (&optional arg just-align)
11634 "Set the tags for the current headline.
11635 With prefix ARG, realign all tags in headings in the current buffer."
11636 (interactive "P")
11637 (let* ((re (concat "^" outline-regexp))
11638 (current (org-get-tags-string))
11639 (col (current-column))
11640 (org-setting-tags t)
11641 table current-tags inherited-tags ; computed below when needed
11642 tags p0 c0 c1 rpl)
11643 (if arg
11644 (save-excursion
11645 (goto-char (point-min))
11646 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11647 (while (re-search-forward re nil t)
11648 (org-set-tags nil t)
11649 (end-of-line 1)))
11650 (message "All tags realigned to column %d" org-tags-column))
11651 (if just-align
11652 (setq tags current)
11653 ;; Get a new set of tags from the user
11654 (save-excursion
11655 (setq table (append org-tag-persistent-alist
11656 (or org-tag-alist (org-get-buffer-tags)))
11657 org-last-tags-completion-table table
11658 current-tags (org-split-string current ":")
11659 inherited-tags (nreverse
11660 (nthcdr (length current-tags)
11661 (nreverse (org-get-tags-at))))
11662 tags
11663 (if (or (eq t org-use-fast-tag-selection)
11664 (and org-use-fast-tag-selection
11665 (delq nil (mapcar 'cdr table))))
11666 (org-fast-tag-selection
11667 current-tags inherited-tags table
11668 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11669 (let ((org-add-colon-after-tag-completion t))
11670 (org-trim
11671 (org-without-partial-completion
11672 (org-icompleting-read "Tags: " 'org-tags-completion-function
11673 nil nil current 'org-tags-history)))))))
11674 (while (string-match "[-+&]+" tags)
11675 ;; No boolean logic, just a list
11676 (setq tags (replace-match ":" t t tags))))
11678 (if org-tags-sort-function
11679 (setq tags (mapconcat 'identity
11680 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11681 org-tags-sort-function) ":")))
11683 (if (string-match "\\`[\t ]*\\'" tags)
11684 (setq tags "")
11685 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11686 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11688 ;; Insert new tags at the correct column
11689 (beginning-of-line 1)
11690 (cond
11691 ((and (equal current "") (equal tags "")))
11692 ((re-search-forward
11693 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11694 (point-at-eol) t)
11695 (if (equal tags "")
11696 (setq rpl "")
11697 (goto-char (match-beginning 0))
11698 (setq c0 (current-column) p0 (point)
11699 c1 (max (1+ c0) (if (> org-tags-column 0)
11700 org-tags-column
11701 (- (- org-tags-column) (length tags))))
11702 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11703 (replace-match rpl t t)
11704 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11705 tags)
11706 (t (error "Tags alignment failed")))
11707 (org-move-to-column col)
11708 (unless just-align
11709 (run-hooks 'org-after-tags-change-hook)))))
11711 (defun org-change-tag-in-region (beg end tag off)
11712 "Add or remove TAG for each entry in the region.
11713 This works in the agenda, and also in an org-mode buffer."
11714 (interactive
11715 (list (region-beginning) (region-end)
11716 (let ((org-last-tags-completion-table
11717 (if (org-mode-p)
11718 (org-get-buffer-tags)
11719 (org-global-tags-completion-table))))
11720 (org-icompleting-read
11721 "Tag: " 'org-tags-completion-function nil nil nil
11722 'org-tags-history))
11723 (progn
11724 (message "[s]et or [r]emove? ")
11725 (equal (read-char-exclusive) ?r))))
11726 (if (fboundp 'deactivate-mark) (deactivate-mark))
11727 (let ((agendap (equal major-mode 'org-agenda-mode))
11728 l1 l2 m buf pos newhead (cnt 0))
11729 (goto-char end)
11730 (setq l2 (1- (org-current-line)))
11731 (goto-char beg)
11732 (setq l1 (org-current-line))
11733 (loop for l from l1 to l2 do
11734 (org-goto-line l)
11735 (setq m (get-text-property (point) 'org-hd-marker))
11736 (when (or (and (org-mode-p) (org-on-heading-p))
11737 (and agendap m))
11738 (setq buf (if agendap (marker-buffer m) (current-buffer))
11739 pos (if agendap m (point)))
11740 (with-current-buffer buf
11741 (save-excursion
11742 (save-restriction
11743 (goto-char pos)
11744 (setq cnt (1+ cnt))
11745 (org-toggle-tag tag (if off 'off 'on))
11746 (setq newhead (org-get-heading)))))
11747 (and agendap (org-agenda-change-all-lines newhead m))))
11748 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11750 (defun org-tags-completion-function (string predicate &optional flag)
11751 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11752 (confirm (lambda (x) (stringp (car x)))))
11753 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11754 (setq s1 (match-string 1 string)
11755 s2 (match-string 2 string))
11756 (setq s1 "" s2 string))
11757 (cond
11758 ((eq flag nil)
11759 ;; try completion
11760 (setq rtn (try-completion s2 ctable confirm))
11761 (if (stringp rtn)
11762 (setq rtn
11763 (concat s1 s2 (substring rtn (length s2))
11764 (if (and org-add-colon-after-tag-completion
11765 (assoc rtn ctable))
11766 ":" ""))))
11767 rtn)
11768 ((eq flag t)
11769 ;; all-completions
11770 (all-completions s2 ctable confirm)
11772 ((eq flag 'lambda)
11773 ;; exact match?
11774 (assoc s2 ctable)))
11777 (defun org-fast-tag-insert (kwd tags face &optional end)
11778 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11779 (insert (format "%-12s" (concat kwd ":"))
11780 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11781 (or end "")))
11783 (defun org-fast-tag-show-exit (flag)
11784 (save-excursion
11785 (org-goto-line 3)
11786 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11787 (replace-match ""))
11788 (when flag
11789 (end-of-line 1)
11790 (org-move-to-column (- (window-width) 19) t)
11791 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11793 (defun org-set-current-tags-overlay (current prefix)
11794 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11795 (if (featurep 'xemacs)
11796 (org-overlay-display org-tags-overlay (concat prefix s)
11797 'secondary-selection)
11798 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11799 (org-overlay-display org-tags-overlay (concat prefix s)))))
11801 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11802 "Fast tag selection with single keys.
11803 CURRENT is the current list of tags in the headline, INHERITED is the
11804 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11805 possibly with grouping information. TODO-TABLE is a similar table with
11806 TODO keywords, should these have keys assigned to them.
11807 If the keys are nil, a-z are automatically assigned.
11808 Returns the new tags string, or nil to not change the current settings."
11809 (let* ((fulltable (append table todo-table))
11810 (maxlen (apply 'max (mapcar
11811 (lambda (x)
11812 (if (stringp (car x)) (string-width (car x)) 0))
11813 fulltable)))
11814 (buf (current-buffer))
11815 (expert (eq org-fast-tag-selection-single-key 'expert))
11816 (buffer-tags nil)
11817 (fwidth (+ maxlen 3 1 3))
11818 (ncol (/ (- (window-width) 4) fwidth))
11819 (i-face 'org-done)
11820 (c-face 'org-todo)
11821 tg cnt e c char c1 c2 ntable tbl rtn
11822 ov-start ov-end ov-prefix
11823 (exit-after-next org-fast-tag-selection-single-key)
11824 (done-keywords org-done-keywords)
11825 groups ingroup)
11826 (save-excursion
11827 (beginning-of-line 1)
11828 (if (looking-at
11829 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11830 (setq ov-start (match-beginning 1)
11831 ov-end (match-end 1)
11832 ov-prefix "")
11833 (setq ov-start (1- (point-at-eol))
11834 ov-end (1+ ov-start))
11835 (skip-chars-forward "^\n\r")
11836 (setq ov-prefix
11837 (concat
11838 (buffer-substring (1- (point)) (point))
11839 (if (> (current-column) org-tags-column)
11841 (make-string (- org-tags-column (current-column)) ?\ ))))))
11842 (org-move-overlay org-tags-overlay ov-start ov-end)
11843 (save-window-excursion
11844 (if expert
11845 (set-buffer (get-buffer-create " *Org tags*"))
11846 (delete-other-windows)
11847 (split-window-vertically)
11848 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11849 (erase-buffer)
11850 (org-set-local 'org-done-keywords done-keywords)
11851 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11852 (org-fast-tag-insert "Current" current c-face "\n\n")
11853 (org-fast-tag-show-exit exit-after-next)
11854 (org-set-current-tags-overlay current ov-prefix)
11855 (setq tbl fulltable char ?a cnt 0)
11856 (while (setq e (pop tbl))
11857 (cond
11858 ((equal (car e) :startgroup)
11859 (push '() groups) (setq ingroup t)
11860 (when (not (= cnt 0))
11861 (setq cnt 0)
11862 (insert "\n"))
11863 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
11864 ((equal (car e) :endgroup)
11865 (setq ingroup nil cnt 0)
11866 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
11867 ((equal e '(:newline))
11868 (when (not (= cnt 0))
11869 (setq cnt 0)
11870 (insert "\n")
11871 (setq e (car tbl))
11872 (while (equal (car tbl) '(:newline))
11873 (insert "\n")
11874 (setq tbl (cdr tbl)))))
11876 (setq tg (copy-sequence (car e)) c2 nil)
11877 (if (cdr e)
11878 (setq c (cdr e))
11879 ;; automatically assign a character.
11880 (setq c1 (string-to-char
11881 (downcase (substring
11882 tg (if (= (string-to-char tg) ?@) 1 0)))))
11883 (if (or (rassoc c1 ntable) (rassoc c1 table))
11884 (while (or (rassoc char ntable) (rassoc char table))
11885 (setq char (1+ char)))
11886 (setq c2 c1))
11887 (setq c (or c2 char)))
11888 (if ingroup (push tg (car groups)))
11889 (setq tg (org-add-props tg nil 'face
11890 (cond
11891 ((not (assoc tg table))
11892 (org-get-todo-face tg))
11893 ((member tg current) c-face)
11894 ((member tg inherited) i-face)
11895 (t nil))))
11896 (if (and (= cnt 0) (not ingroup)) (insert " "))
11897 (insert "[" c "] " tg (make-string
11898 (- fwidth 4 (length tg)) ?\ ))
11899 (push (cons tg c) ntable)
11900 (when (= (setq cnt (1+ cnt)) ncol)
11901 (insert "\n")
11902 (if ingroup (insert " "))
11903 (setq cnt 0)))))
11904 (setq ntable (nreverse ntable))
11905 (insert "\n")
11906 (goto-char (point-min))
11907 (if (not expert) (org-fit-window-to-buffer))
11908 (setq rtn
11909 (catch 'exit
11910 (while t
11911 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
11912 (if (not groups) "no " "")
11913 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11914 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11915 (cond
11916 ((= c ?\r) (throw 'exit t))
11917 ((= c ?!)
11918 (setq groups (not groups))
11919 (goto-char (point-min))
11920 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11921 ((= c ?\C-c)
11922 (if (not expert)
11923 (org-fast-tag-show-exit
11924 (setq exit-after-next (not exit-after-next)))
11925 (setq expert nil)
11926 (delete-other-windows)
11927 (split-window-vertically)
11928 (org-switch-to-buffer-other-window " *Org tags*")
11929 (org-fit-window-to-buffer)))
11930 ((or (= c ?\C-g)
11931 (and (= c ?q) (not (rassoc c ntable))))
11932 (org-detach-overlay org-tags-overlay)
11933 (setq quit-flag t))
11934 ((= c ?\ )
11935 (setq current nil)
11936 (if exit-after-next (setq exit-after-next 'now)))
11937 ((= c ?\t)
11938 (condition-case nil
11939 (setq tg (org-icompleting-read
11940 "Tag: "
11941 (or buffer-tags
11942 (with-current-buffer buf
11943 (org-get-buffer-tags)))))
11944 (quit (setq tg "")))
11945 (when (string-match "\\S-" tg)
11946 (add-to-list 'buffer-tags (list tg))
11947 (if (member tg current)
11948 (setq current (delete tg current))
11949 (push tg current)))
11950 (if exit-after-next (setq exit-after-next 'now)))
11951 ((setq e (rassoc c todo-table) tg (car e))
11952 (with-current-buffer buf
11953 (save-excursion (org-todo tg)))
11954 (if exit-after-next (setq exit-after-next 'now)))
11955 ((setq e (rassoc c ntable) tg (car e))
11956 (if (member tg current)
11957 (setq current (delete tg current))
11958 (loop for g in groups do
11959 (if (member tg g)
11960 (mapc (lambda (x)
11961 (setq current (delete x current)))
11962 g)))
11963 (push tg current))
11964 (if exit-after-next (setq exit-after-next 'now))))
11966 ;; Create a sorted list
11967 (setq current
11968 (sort current
11969 (lambda (a b)
11970 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11971 (if (eq exit-after-next 'now) (throw 'exit t))
11972 (goto-char (point-min))
11973 (beginning-of-line 2)
11974 (delete-region (point) (point-at-eol))
11975 (org-fast-tag-insert "Current" current c-face)
11976 (org-set-current-tags-overlay current ov-prefix)
11977 (while (re-search-forward
11978 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11979 (setq tg (match-string 1))
11980 (add-text-properties
11981 (match-beginning 1) (match-end 1)
11982 (list 'face
11983 (cond
11984 ((member tg current) c-face)
11985 ((member tg inherited) i-face)
11986 (t (get-text-property (match-beginning 1) 'face))))))
11987 (goto-char (point-min)))))
11988 (org-detach-overlay org-tags-overlay)
11989 (if rtn
11990 (mapconcat 'identity current ":")
11991 nil))))
11993 (defun org-get-tags-string ()
11994 "Get the TAGS string in the current headline."
11995 (unless (org-on-heading-p t)
11996 (error "Not on a heading"))
11997 (save-excursion
11998 (beginning-of-line 1)
11999 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12000 (org-match-string-no-properties 1)
12001 "")))
12003 (defun org-get-tags ()
12004 "Get the list of tags specified in the current headline."
12005 (org-split-string (org-get-tags-string) ":"))
12007 (defun org-get-buffer-tags ()
12008 "Get a table of all tags used in the buffer, for completion."
12009 (let (tags)
12010 (save-excursion
12011 (goto-char (point-min))
12012 (while (re-search-forward
12013 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12014 (when (equal (char-after (point-at-bol 0)) ?*)
12015 (mapc (lambda (x) (add-to-list 'tags x))
12016 (org-split-string (org-match-string-no-properties 1) ":")))))
12017 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12018 (mapcar 'list tags)))
12020 ;;;; The mapping API
12022 ;;;###autoload
12023 (defun org-map-entries (func &optional match scope &rest skip)
12024 "Call FUNC at each headline selected by MATCH in SCOPE.
12026 FUNC is a function or a lisp form. The function will be called without
12027 arguments, with the cursor positioned at the beginning of the headline.
12028 The return values of all calls to the function will be collected and
12029 returned as a list.
12031 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12032 does not need to preserve point. After evaluation, the cursor will be
12033 moved to the end of the line (presumably of the headline of the
12034 processed entry) and search continues from there. Under some
12035 circumstances, this may not produce the wanted results. For example,
12036 if you have removed (e.g. archived) the current (sub)tree it could
12037 mean that the next entry will be skipped entirely. In such cases, you
12038 can specify the position from where search should continue by making
12039 FUNC set the variable `org-map-continue-from' to the desired buffer
12040 position.
12042 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12043 Only headlines that are matched by this query will be considered during
12044 the iteration. When MATCH is nil or t, all headlines will be
12045 visited by the iteration.
12047 SCOPE determines the scope of this command. It can be any of:
12049 nil The current buffer, respecting the restriction if any
12050 tree The subtree started with the entry at point
12051 file The current buffer, without restriction
12052 file-with-archives
12053 The current buffer, and any archives associated with it
12054 agenda All agenda files
12055 agenda-with-archives
12056 All agenda files with any archive files associated with them
12057 \(file1 file2 ...)
12058 If this is a list, all files in the list will be scanned
12060 The remaining args are treated as settings for the skipping facilities of
12061 the scanner. The following items can be given here:
12063 archive skip trees with the archive tag.
12064 comment skip trees with the COMMENT keyword
12065 function or Emacs Lisp form:
12066 will be used as value for `org-agenda-skip-function', so whenever
12067 the function returns t, FUNC will not be called for that
12068 entry and search will continue from the point where the
12069 function leaves it.
12071 If your function needs to retrieve the tags including inherited tags
12072 at the *current* entry, you can use the value of the variable
12073 `org-scanner-tags' which will be much faster than getting the value
12074 with `org-get-tags-at'. If your function gets properties with
12075 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12076 to t around the call to `org-entry-properties' to get the same speedup.
12077 Note that if your function moves around to retrieve tags and properties at
12078 a *different* entry, you cannot use these techniques."
12079 (let* ((org-agenda-archives-mode nil) ; just to make sure
12080 (org-agenda-skip-archived-trees (memq 'archive skip))
12081 (org-agenda-skip-comment-trees (memq 'comment skip))
12082 (org-agenda-skip-function
12083 (car (org-delete-all '(comment archive) skip)))
12084 (org-tags-match-list-sublevels t)
12085 matcher file res
12086 org-todo-keywords-for-agenda
12087 org-done-keywords-for-agenda
12088 org-todo-keyword-alist-for-agenda
12089 org-drawers-for-agenda
12090 org-tag-alist-for-agenda)
12092 (cond
12093 ((eq match t) (setq matcher t))
12094 ((eq match nil) (setq matcher t))
12095 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12097 (save-excursion
12098 (save-restriction
12099 (when (eq scope 'tree)
12100 (org-back-to-heading t)
12101 (org-narrow-to-subtree)
12102 (setq scope nil))
12104 (if (not scope)
12105 (progn
12106 (org-prepare-agenda-buffers
12107 (list (buffer-file-name (current-buffer))))
12108 (setq res (org-scan-tags func matcher)))
12109 ;; Get the right scope
12110 (cond
12111 ((and scope (listp scope) (symbolp (car scope)))
12112 (setq scope (eval scope)))
12113 ((eq scope 'agenda)
12114 (setq scope (org-agenda-files t)))
12115 ((eq scope 'agenda-with-archives)
12116 (setq scope (org-agenda-files t))
12117 (setq scope (org-add-archive-files scope)))
12118 ((eq scope 'file)
12119 (setq scope (list (buffer-file-name))))
12120 ((eq scope 'file-with-archives)
12121 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12122 (org-prepare-agenda-buffers scope)
12123 (while (setq file (pop scope))
12124 (with-current-buffer (org-find-base-buffer-visiting file)
12125 (save-excursion
12126 (save-restriction
12127 (widen)
12128 (goto-char (point-min))
12129 (setq res (append res (org-scan-tags func matcher))))))))))
12130 res))
12132 ;;;; Properties
12134 ;;; Setting and retrieving properties
12136 (defconst org-special-properties
12137 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12138 "TIMESTAMP" "TIMESTAMP_IA")
12139 "The special properties valid in Org-mode.
12141 These are properties that are not defined in the property drawer,
12142 but in some other way.")
12144 (defconst org-default-properties
12145 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12146 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12147 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12148 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12149 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12150 "CLOCK_MODELINE_TOTAL" "STYLE")
12151 "Some properties that are used by Org-mode for various purposes.
12152 Being in this list makes sure that they are offered for completion.")
12154 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12155 "Regular expression matching the first line of a property drawer.")
12157 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12158 "Regular expression matching the first line of a property drawer.")
12160 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12161 "Regular expression matching the first line of a property drawer.")
12163 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12164 "Regular expression matching the first line of a property drawer.")
12166 (defconst org-property-drawer-re
12167 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12168 org-property-end-re "\\)\n?")
12169 "Matches an entire property drawer.")
12171 (defconst org-clock-drawer-re
12172 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12173 org-property-end-re "\\)\n?")
12174 "Matches an entire clock drawer.")
12176 (defun org-property-action ()
12177 "Do an action on properties."
12178 (interactive)
12179 (let (c)
12180 (org-at-property-p)
12181 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12182 (setq c (read-char-exclusive))
12183 (cond
12184 ((equal c ?s)
12185 (call-interactively 'org-set-property))
12186 ((equal c ?d)
12187 (call-interactively 'org-delete-property))
12188 ((equal c ?D)
12189 (call-interactively 'org-delete-property-globally))
12190 ((equal c ?c)
12191 (call-interactively 'org-compute-property-at-point))
12192 (t (error "No such property action %c" c)))))
12194 (defun org-set-effort (&optional value)
12195 "Set the effort property of the current entry.
12196 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12197 allowed value."
12198 (interactive "P")
12199 (if (equal value 0) (setq value 10))
12200 (let* ((completion-ignore-case t)
12201 (prop org-effort-property)
12202 (cur (org-entry-get nil prop))
12203 (allowed (org-property-get-allowed-values nil prop 'table))
12204 (existing (mapcar 'list (org-property-values prop)))
12206 (val (cond
12207 ((stringp value) value)
12208 ((and allowed (integerp value))
12209 (or (car (nth (1- value) allowed))
12210 (car (org-last allowed))))
12211 (allowed
12212 (message "Select 1-9,0, [RET%s]: %s"
12213 (if cur (concat "=" cur) "")
12214 (mapconcat 'car allowed " "))
12215 (setq rpl (read-char-exclusive))
12216 (if (equal rpl ?\r)
12218 (setq rpl (- rpl ?0))
12219 (if (equal rpl 0) (setq rpl 10))
12220 (if (and (> rpl 0) (<= rpl (length allowed)))
12221 (car (nth (1- rpl) allowed))
12222 (org-completing-read "Effort: " allowed nil))))
12224 (let (org-completion-use-ido org-completion-use-iswitchb)
12225 (org-completing-read
12226 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12227 (concat "[" cur "]") "")
12228 ": ")
12229 existing nil nil "" nil cur))))))
12230 (unless (equal (org-entry-get nil prop) val)
12231 (org-entry-put nil prop val))
12232 (message "%s is now %s" prop val)))
12234 (defun org-at-property-p ()
12235 "Is the cursor in a property line?"
12236 ;; FIXME: Does not check if we are actually in the drawer.
12237 ;; FIXME: also returns true on any drawers.....
12238 ;; This is used by C-c C-c for property action.
12239 (save-excursion
12240 (beginning-of-line 1)
12241 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12243 (defun org-get-property-block (&optional beg end force)
12244 "Return the (beg . end) range of the body of the property drawer.
12245 BEG and END can be beginning and end of subtree, if not given
12246 they will be found.
12247 If the drawer does not exist and FORCE is non-nil, create the drawer."
12248 (catch 'exit
12249 (save-excursion
12250 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12251 (end (or end (progn (outline-next-heading) (point)))))
12252 (goto-char beg)
12253 (if (re-search-forward org-property-start-re end t)
12254 (setq beg (1+ (match-end 0)))
12255 (if force
12256 (save-excursion
12257 (org-insert-property-drawer)
12258 (setq end (progn (outline-next-heading) (point))))
12259 (throw 'exit nil))
12260 (goto-char beg)
12261 (if (re-search-forward org-property-start-re end t)
12262 (setq beg (1+ (match-end 0)))))
12263 (if (re-search-forward org-property-end-re end t)
12264 (setq end (match-beginning 0))
12265 (or force (throw 'exit nil))
12266 (goto-char beg)
12267 (setq end beg)
12268 (org-indent-line-function)
12269 (insert ":END:\n"))
12270 (cons beg end)))))
12272 (defun org-entry-properties (&optional pom which)
12273 "Get all properties of the entry at point-or-marker POM.
12274 This includes the TODO keyword, the tags, time strings for deadline,
12275 scheduled, and clocking, and any additional properties defined in the
12276 entry. The return value is an alist, keys may occur multiple times
12277 if the property key was used several times.
12278 POM may also be nil, in which case the current entry is used.
12279 If WHICH is nil or `all', get all properties. If WHICH is
12280 `special' or `standard', only get that subclass."
12281 (setq which (or which 'all))
12282 (org-with-point-at pom
12283 (let ((clockstr (substring org-clock-string 0 -1))
12284 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
12285 beg end range props sum-props key value string clocksum)
12286 (save-excursion
12287 (when (condition-case nil
12288 (and (org-mode-p) (org-back-to-heading t))
12289 (error nil))
12290 (setq beg (point))
12291 (setq sum-props (get-text-property (point) 'org-summaries))
12292 (setq clocksum (get-text-property (point) :org-clock-minutes))
12293 (outline-next-heading)
12294 (setq end (point))
12295 (when (memq which '(all special))
12296 ;; Get the special properties, like TODO and tags
12297 (goto-char beg)
12298 (when (and (looking-at org-todo-line-regexp) (match-end 2))
12299 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12300 (when (looking-at org-priority-regexp)
12301 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12302 (when (and (setq value (org-get-tags-string))
12303 (string-match "\\S-" value))
12304 (push (cons "TAGS" value) props))
12305 (when (setq value (org-get-tags-at))
12306 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
12307 props))
12308 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12309 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12310 string (if (equal key clockstr)
12311 (org-no-properties
12312 (org-trim
12313 (buffer-substring
12314 (match-beginning 3) (goto-char (point-at-eol)))))
12315 (substring (org-match-string-no-properties 3) 1 -1)))
12316 (unless key
12317 (if (= (char-after (match-beginning 3)) ?\[)
12318 (setq key "TIMESTAMP_IA")
12319 (setq key "TIMESTAMP")))
12320 (when (or (equal key clockstr) (not (assoc key props)))
12321 (push (cons key string) props)))
12325 (when (memq which '(all standard))
12326 ;; Get the standard properties, like :PROP: ...
12327 (setq range (org-get-property-block beg end))
12328 (when range
12329 (goto-char (car range))
12330 (while (re-search-forward
12331 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12332 (cdr range) t)
12333 (setq key (org-match-string-no-properties 1)
12334 value (org-trim (or (org-match-string-no-properties 2) "")))
12335 (unless (member key excluded)
12336 (push (cons key (or value "")) props)))))
12337 (if clocksum
12338 (push (cons "CLOCKSUM"
12339 (org-columns-number-to-string (/ (float clocksum) 60.)
12340 'add_times))
12341 props))
12342 (unless (assoc "CATEGORY" props)
12343 (setq value (or (org-get-category)
12344 (progn (org-refresh-category-properties)
12345 (org-get-category))))
12346 (push (cons "CATEGORY" value) props))
12347 (append sum-props (nreverse props)))))))
12349 (defun org-entry-get (pom property &optional inherit)
12350 "Get value of PROPERTY for entry at point-or-marker POM.
12351 If INHERIT is non-nil and the entry does not have the property,
12352 then also check higher levels of the hierarchy.
12353 If INHERIT is the symbol `selective', use inheritance only if the setting
12354 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12355 If the property is present but empty, the return value is the empty string.
12356 If the property is not present at all, nil is returned."
12357 (org-with-point-at pom
12358 (if (and inherit (if (eq inherit 'selective)
12359 (org-property-inherit-p property)
12361 (org-entry-get-with-inheritance property)
12362 (if (member property org-special-properties)
12363 ;; We need a special property. Use brute force, get all properties.
12364 (cdr (assoc property (org-entry-properties nil 'special)))
12365 (let ((range (org-get-property-block)))
12366 (if (and range
12367 (goto-char (car range))
12368 (re-search-forward
12369 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12370 (cdr range) t))
12371 ;; Found the property, return it.
12372 (if (match-end 1)
12373 (org-match-string-no-properties 1)
12374 "")))))))
12376 (defun org-property-or-variable-value (var &optional inherit)
12377 "Check if there is a property fixing the value of VAR.
12378 If yes, return this value. If not, return the current value of the variable."
12379 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12380 (if (and prop (stringp prop) (string-match "\\S-" prop))
12381 (read prop)
12382 (symbol-value var))))
12384 (defun org-entry-delete (pom property)
12385 "Delete the property PROPERTY from entry at point-or-marker POM."
12386 (org-with-point-at pom
12387 (if (member property org-special-properties)
12388 nil ; cannot delete these properties.
12389 (let ((range (org-get-property-block)))
12390 (if (and range
12391 (goto-char (car range))
12392 (re-search-forward
12393 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12394 (cdr range) t))
12395 (progn
12396 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12398 nil)))))
12400 ;; Multi-values properties are properties that contain multiple values
12401 ;; These values are assumed to be single words, separated by whitespace.
12402 (defun org-entry-add-to-multivalued-property (pom property value)
12403 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12404 (let* ((old (org-entry-get pom property))
12405 (values (and old (org-split-string old "[ \t]"))))
12406 (setq value (org-entry-protect-space value))
12407 (unless (member value values)
12408 (setq values (cons value values))
12409 (org-entry-put pom property
12410 (mapconcat 'identity values " ")))))
12412 (defun org-entry-remove-from-multivalued-property (pom property value)
12413 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12414 (let* ((old (org-entry-get pom property))
12415 (values (and old (org-split-string old "[ \t]"))))
12416 (setq value (org-entry-protect-space value))
12417 (when (member value values)
12418 (setq values (delete value values))
12419 (org-entry-put pom property
12420 (mapconcat 'identity values " ")))))
12422 (defun org-entry-member-in-multivalued-property (pom property value)
12423 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12424 (let* ((old (org-entry-get pom property))
12425 (values (and old (org-split-string old "[ \t]"))))
12426 (setq value (org-entry-protect-space value))
12427 (member value values)))
12429 (defun org-entry-get-multivalued-property (pom property)
12430 "Return a list of values in a multivalued property."
12431 (let* ((value (org-entry-get pom property))
12432 (values (and value (org-split-string value "[ \t]"))))
12433 (mapcar 'org-entry-restore-space values)))
12435 (defun org-entry-put-multivalued-property (pom property &rest values)
12436 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12437 VALUES should be a list of strings. Spaces will be protected."
12438 (org-entry-put pom property
12439 (mapconcat 'org-entry-protect-space values " "))
12440 (let* ((value (org-entry-get pom property))
12441 (values (and value (org-split-string value "[ \t]"))))
12442 (mapcar 'org-entry-restore-space values)))
12444 (defun org-entry-protect-space (s)
12445 "Protect spaces and newline in string S."
12446 (while (string-match " " s)
12447 (setq s (replace-match "%20" t t s)))
12448 (while (string-match "\n" s)
12449 (setq s (replace-match "%0A" t t s)))
12452 (defun org-entry-restore-space (s)
12453 "Restore spaces and newline in string S."
12454 (while (string-match "%20" s)
12455 (setq s (replace-match " " t t s)))
12456 (while (string-match "%0A" s)
12457 (setq s (replace-match "\n" t t s)))
12460 (defvar org-entry-property-inherited-from (make-marker)
12461 "Marker pointing to the entry from where a property was inherited.
12462 Each call to `org-entry-get-with-inheritance' will set this marker to the
12463 location of the entry where the inheritance search matched. If there was
12464 no match, the marker will point nowhere.
12465 Note that also `org-entry-get' calls this function, if the INHERIT flag
12466 is set.")
12468 (defun org-entry-get-with-inheritance (property)
12469 "Get entry property, and search higher levels if not present."
12470 (move-marker org-entry-property-inherited-from nil)
12471 (let (tmp)
12472 (save-excursion
12473 (save-restriction
12474 (widen)
12475 (catch 'ex
12476 (while t
12477 (when (setq tmp (org-entry-get nil property))
12478 (org-back-to-heading t)
12479 (move-marker org-entry-property-inherited-from (point))
12480 (throw 'ex tmp))
12481 (or (org-up-heading-safe) (throw 'ex nil)))))
12482 (or tmp
12483 (cdr (assoc property org-file-properties))
12484 (cdr (assoc property org-global-properties))
12485 (cdr (assoc property org-global-properties-fixed))))))
12487 (defun org-entry-put (pom property value)
12488 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12489 (org-with-point-at pom
12490 (org-back-to-heading t)
12491 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12492 range)
12493 (cond
12494 ((equal property "TODO")
12495 (when (and (stringp value) (string-match "\\S-" value)
12496 (not (member value org-todo-keywords-1)))
12497 (error "\"%s\" is not a valid TODO state" value))
12498 (if (or (not value)
12499 (not (string-match "\\S-" value)))
12500 (setq value 'none))
12501 (org-todo value)
12502 (org-set-tags nil 'align))
12503 ((equal property "PRIORITY")
12504 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12505 (string-to-char value) ?\ ))
12506 (org-set-tags nil 'align))
12507 ((equal property "SCHEDULED")
12508 (if (re-search-forward org-scheduled-time-regexp end t)
12509 (cond
12510 ((eq value 'earlier) (org-timestamp-change -1 'day))
12511 ((eq value 'later) (org-timestamp-change 1 'day))
12512 (t (call-interactively 'org-schedule)))
12513 (call-interactively 'org-schedule)))
12514 ((equal property "DEADLINE")
12515 (if (re-search-forward org-deadline-time-regexp end t)
12516 (cond
12517 ((eq value 'earlier) (org-timestamp-change -1 'day))
12518 ((eq value 'later) (org-timestamp-change 1 'day))
12519 (t (call-interactively 'org-deadline)))
12520 (call-interactively 'org-deadline)))
12521 ((member property org-special-properties)
12522 (error "The %s property can not yet be set with `org-entry-put'"
12523 property))
12524 (t ; a non-special property
12525 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12526 (setq range (org-get-property-block beg end 'force))
12527 (goto-char (car range))
12528 (if (re-search-forward
12529 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12530 (progn
12531 (delete-region (match-beginning 1) (match-end 1))
12532 (goto-char (match-beginning 1)))
12533 (goto-char (cdr range))
12534 (insert "\n")
12535 (backward-char 1)
12536 (org-indent-line-function)
12537 (insert ":" property ":"))
12538 (and value (insert " " value))
12539 (org-indent-line-function)))))))
12541 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12542 "Get all property keys in the current buffer.
12543 With INCLUDE-SPECIALS, also list the special properties that reflect things
12544 like tags and TODO state.
12545 With INCLUDE-DEFAULTS, also include properties that has special meaning
12546 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12547 With INCLUDE-COLUMNS, also include property names given in COLUMN
12548 formats in the current buffer."
12549 (let (rtn range cfmt s p)
12550 (save-excursion
12551 (save-restriction
12552 (widen)
12553 (goto-char (point-min))
12554 (while (re-search-forward org-property-start-re nil t)
12555 (setq range (org-get-property-block))
12556 (goto-char (car range))
12557 (while (re-search-forward
12558 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12559 (cdr range) t)
12560 (add-to-list 'rtn (org-match-string-no-properties 1)))
12561 (outline-next-heading))))
12563 (when include-specials
12564 (setq rtn (append org-special-properties rtn)))
12566 (when include-defaults
12567 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12568 (add-to-list 'rtn org-effort-property))
12570 (when include-columns
12571 (save-excursion
12572 (save-restriction
12573 (widen)
12574 (goto-char (point-min))
12575 (while (re-search-forward
12576 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12577 nil t)
12578 (setq cfmt (match-string 2) s 0)
12579 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12580 cfmt s)
12581 (setq s (match-end 0)
12582 p (match-string 1 cfmt))
12583 (unless (or (equal p "ITEM")
12584 (member p org-special-properties))
12585 (add-to-list 'rtn (match-string 1 cfmt))))))))
12587 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12589 (defun org-property-values (key)
12590 "Return a list of all values of property KEY."
12591 (save-excursion
12592 (save-restriction
12593 (widen)
12594 (goto-char (point-min))
12595 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12596 values)
12597 (while (re-search-forward re nil t)
12598 (add-to-list 'values (org-trim (match-string 1))))
12599 (delete "" values)))))
12601 (defun org-insert-property-drawer ()
12602 "Insert a property drawer into the current entry."
12603 (interactive)
12604 (org-back-to-heading t)
12605 (looking-at outline-regexp)
12606 (let ((indent (if org-adapt-indentation
12607 (- (match-end 0)(match-beginning 0))
12609 (beg (point))
12610 (re (concat "^[ \t]*" org-keyword-time-regexp))
12611 end hiddenp)
12612 (outline-next-heading)
12613 (setq end (point))
12614 (goto-char beg)
12615 (while (re-search-forward re end t))
12616 (setq hiddenp (org-invisible-p))
12617 (end-of-line 1)
12618 (and (equal (char-after) ?\n) (forward-char 1))
12619 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12620 (if (member (match-string 1) '("CLOCK:" ":END:"))
12621 ;; just skip this line
12622 (beginning-of-line 2)
12623 ;; Drawer start, find the end
12624 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12625 (beginning-of-line 1)))
12626 (org-skip-over-state-notes)
12627 (skip-chars-backward " \t\n\r")
12628 (if (eq (char-before) ?*) (forward-char 1))
12629 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12630 (beginning-of-line 0)
12631 (org-indent-to-column indent)
12632 (beginning-of-line 2)
12633 (org-indent-to-column indent)
12634 (beginning-of-line 0)
12635 (if hiddenp
12636 (save-excursion
12637 (org-back-to-heading t)
12638 (hide-entry))
12639 (org-flag-drawer t))))
12641 (defun org-set-property (property value)
12642 "In the current entry, set PROPERTY to VALUE.
12643 When called interactively, this will prompt for a property name, offering
12644 completion on existing and default properties. And then it will prompt
12645 for a value, offering completion either on allowed values (via an inherited
12646 xxx_ALL property) or on existing values in other instances of this property
12647 in the current file."
12648 (interactive
12649 (let* ((completion-ignore-case t)
12650 (keys (org-buffer-property-keys nil t t))
12651 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12652 (prop (if (member prop0 keys)
12653 prop0
12654 (or (cdr (assoc (downcase prop0)
12655 (mapcar (lambda (x) (cons (downcase x) x))
12656 keys)))
12657 prop0)))
12658 (cur (org-entry-get nil prop))
12659 (allowed (org-property-get-allowed-values nil prop 'table))
12660 (existing (mapcar 'list (org-property-values prop)))
12661 (val (if allowed
12662 (org-completing-read "Value: " allowed nil 'req-match)
12663 (let (org-completion-use-ido org-completion-use-iswitchb)
12664 (org-completing-read
12665 (concat "Value " (if (and cur (string-match "\\S-" cur))
12666 (concat "[" cur "]") "")
12667 ": ")
12668 existing nil nil "" nil cur)))))
12669 (list prop (if (equal val "") cur val))))
12670 (unless (equal (org-entry-get nil property) value)
12671 (org-entry-put nil property value)))
12673 (defun org-delete-property (property)
12674 "In the current entry, delete PROPERTY."
12675 (interactive
12676 (let* ((completion-ignore-case t)
12677 (prop (org-icompleting-read
12678 "Property: " (org-entry-properties nil 'standard))))
12679 (list prop)))
12680 (message "Property %s %s" property
12681 (if (org-entry-delete nil property)
12682 "deleted"
12683 "was not present in the entry")))
12685 (defun org-delete-property-globally (property)
12686 "Remove PROPERTY globally, from all entries."
12687 (interactive
12688 (let* ((completion-ignore-case t)
12689 (prop (org-icompleting-read
12690 "Globally remove property: "
12691 (mapcar 'list (org-buffer-property-keys)))))
12692 (list prop)))
12693 (save-excursion
12694 (save-restriction
12695 (widen)
12696 (goto-char (point-min))
12697 (let ((cnt 0))
12698 (while (re-search-forward
12699 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12700 nil t)
12701 (setq cnt (1+ cnt))
12702 (replace-match ""))
12703 (message "Property \"%s\" removed from %d entries" property cnt)))))
12705 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12707 (defun org-compute-property-at-point ()
12708 "Compute the property at point.
12709 This looks for an enclosing column format, extracts the operator and
12710 then applies it to the property in the column format's scope."
12711 (interactive)
12712 (unless (org-at-property-p)
12713 (error "Not at a property"))
12714 (let ((prop (org-match-string-no-properties 2)))
12715 (org-columns-get-format-and-top-level)
12716 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12717 (error "No operator defined for property %s" prop))
12718 (org-columns-compute prop)))
12720 (defun org-property-get-allowed-values (pom property &optional table)
12721 "Get allowed values for the property PROPERTY.
12722 When TABLE is non-nil, return an alist that can directly be used for
12723 completion."
12724 (let (vals)
12725 (cond
12726 ((equal property "TODO")
12727 (setq vals (org-with-point-at pom
12728 (append org-todo-keywords-1 '("")))))
12729 ((equal property "PRIORITY")
12730 (let ((n org-lowest-priority))
12731 (while (>= n org-highest-priority)
12732 (push (char-to-string n) vals)
12733 (setq n (1- n)))))
12734 ((member property org-special-properties))
12736 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12738 (when (and vals (string-match "\\S-" vals))
12739 (setq vals (car (read-from-string (concat "(" vals ")"))))
12740 (setq vals (mapcar (lambda (x)
12741 (cond ((stringp x) x)
12742 ((numberp x) (number-to-string x))
12743 ((symbolp x) (symbol-name x))
12744 (t "???")))
12745 vals)))))
12746 (if table (mapcar 'list vals) vals)))
12748 (defun org-property-previous-allowed-value (&optional previous)
12749 "Switch to the next allowed value for this property."
12750 (interactive)
12751 (org-property-next-allowed-value t))
12753 (defun org-property-next-allowed-value (&optional previous)
12754 "Switch to the next allowed value for this property."
12755 (interactive)
12756 (unless (org-at-property-p)
12757 (error "Not at a property"))
12758 (let* ((key (match-string 2))
12759 (value (match-string 3))
12760 (allowed (or (org-property-get-allowed-values (point) key)
12761 (and (member value '("[ ]" "[-]" "[X]"))
12762 '("[ ]" "[X]"))))
12763 nval)
12764 (unless allowed
12765 (error "Allowed values for this property have not been defined"))
12766 (if previous (setq allowed (reverse allowed)))
12767 (if (member value allowed)
12768 (setq nval (car (cdr (member value allowed)))))
12769 (setq nval (or nval (car allowed)))
12770 (if (equal nval value)
12771 (error "Only one allowed value for this property"))
12772 (org-at-property-p)
12773 (replace-match (concat " :" key ": " nval) t t)
12774 (org-indent-line-function)
12775 (beginning-of-line 1)
12776 (skip-chars-forward " \t")))
12778 (defun org-find-entry-with-id (ident)
12779 "Locate the entry that contains the ID property with exact value IDENT.
12780 IDENT can be a string, a symbol or a number, this function will search for
12781 the string representation of it.
12782 Return the position where this entry starts, or nil if there is no such entry."
12783 (interactive "sID: ")
12784 (let ((id (cond
12785 ((stringp ident) ident)
12786 ((symbol-name ident) (symbol-name ident))
12787 ((numberp ident) (number-to-string ident))
12788 (t (error "IDENT %s must be a string, symbol or number" ident))))
12789 (case-fold-search nil))
12790 (save-excursion
12791 (save-restriction
12792 (widen)
12793 (goto-char (point-min))
12794 (when (re-search-forward
12795 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12796 nil t)
12797 (org-back-to-heading t)
12798 (point))))))
12800 ;;;; Timestamps
12802 (defvar org-last-changed-timestamp nil)
12803 (defvar org-last-inserted-timestamp nil
12804 "The last time stamp inserted with `org-insert-time-stamp'.")
12805 (defvar org-time-was-given) ; dynamically scoped parameter
12806 (defvar org-end-time-was-given) ; dynamically scoped parameter
12807 (defvar org-ts-what) ; dynamically scoped parameter
12809 (defun org-time-stamp (arg &optional inactive)
12810 "Prompt for a date/time and insert a time stamp.
12811 If the user specifies a time like HH:MM, or if this command is called
12812 with a prefix argument, the time stamp will contain date and time.
12813 Otherwise, only the date will be included. All parts of a date not
12814 specified by the user will be filled in from the current date/time.
12815 So if you press just return without typing anything, the time stamp
12816 will represent the current date/time. If there is already a timestamp
12817 at the cursor, it will be modified."
12818 (interactive "P")
12819 (let* ((ts nil)
12820 (default-time
12821 ;; Default time is either today, or, when entering a range,
12822 ;; the range start.
12823 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12824 (save-excursion
12825 (re-search-backward
12826 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12827 (- (point) 20) t)))
12828 (apply 'encode-time (org-parse-time-string (match-string 1)))
12829 (current-time)))
12830 (default-input (and ts (org-get-compact-tod ts)))
12831 org-time-was-given org-end-time-was-given time)
12832 (cond
12833 ((and (org-at-timestamp-p t)
12834 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12835 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12836 (insert "--")
12837 (setq time (let ((this-command this-command))
12838 (org-read-date arg 'totime nil nil
12839 default-time default-input)))
12840 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12841 ((org-at-timestamp-p t)
12842 (setq time (let ((this-command this-command))
12843 (org-read-date arg 'totime nil nil default-time default-input)))
12844 (when (org-at-timestamp-p t) ; just to get the match data
12845 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12846 (replace-match "")
12847 (setq org-last-changed-timestamp
12848 (org-insert-time-stamp
12849 time (or org-time-was-given arg)
12850 inactive nil nil (list org-end-time-was-given))))
12851 (message "Timestamp updated"))
12853 (setq time (let ((this-command this-command))
12854 (org-read-date arg 'totime nil nil default-time default-input)))
12855 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12856 nil nil (list org-end-time-was-given))))))
12858 ;; FIXME: can we use this for something else, like computing time differences?
12859 (defun org-get-compact-tod (s)
12860 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12861 (let* ((t1 (match-string 1 s))
12862 (h1 (string-to-number (match-string 2 s)))
12863 (m1 (string-to-number (match-string 3 s)))
12864 (t2 (and (match-end 4) (match-string 5 s)))
12865 (h2 (and t2 (string-to-number (match-string 6 s))))
12866 (m2 (and t2 (string-to-number (match-string 7 s))))
12867 dh dm)
12868 (if (not t2)
12870 (setq dh (- h2 h1) dm (- m2 m1))
12871 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12872 (concat t1 "+" (number-to-string dh)
12873 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12875 (defun org-time-stamp-inactive (&optional arg)
12876 "Insert an inactive time stamp.
12877 An inactive time stamp is enclosed in square brackets instead of angle
12878 brackets. It is inactive in the sense that it does not trigger agenda entries,
12879 does not link to the calendar and cannot be changed with the S-cursor keys.
12880 So these are more for recording a certain time/date."
12881 (interactive "P")
12882 (org-time-stamp arg 'inactive))
12884 (defvar org-date-ovl (org-make-overlay 1 1))
12885 (org-overlay-put org-date-ovl 'face 'org-warning)
12886 (org-detach-overlay org-date-ovl)
12888 (defvar org-ans1) ; dynamically scoped parameter
12889 (defvar org-ans2) ; dynamically scoped parameter
12891 (defvar org-plain-time-of-day-regexp) ; defined below
12893 (defvar org-overriding-default-time nil) ; dynamically scoped
12894 (defvar org-read-date-overlay nil)
12895 (defvar org-dcst nil) ; dynamically scoped
12896 (defvar org-read-date-history nil)
12897 (defvar org-read-date-final-answer nil)
12899 (defun org-read-date (&optional with-time to-time from-string prompt
12900 default-time default-input)
12901 "Read a date, possibly a time, and make things smooth for the user.
12902 The prompt will suggest to enter an ISO date, but you can also enter anything
12903 which will at least partially be understood by `parse-time-string'.
12904 Unrecognized parts of the date will default to the current day, month, year,
12905 hour and minute. If this command is called to replace a timestamp at point,
12906 of to enter the second timestamp of a range, the default time is taken from the
12907 existing stamp. For example,
12908 3-2-5 --> 2003-02-05
12909 feb 15 --> currentyear-02-15
12910 sep 12 9 --> 2009-09-12
12911 12:45 --> today 12:45
12912 22 sept 0:34 --> currentyear-09-22 0:34
12913 12 --> currentyear-currentmonth-12
12914 Fri --> nearest Friday (today or later)
12915 etc.
12917 Furthermore you can specify a relative date by giving, as the *first* thing
12918 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12919 change in days weeks, months, years.
12920 With a single plus or minus, the date is relative to today. With a double
12921 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12922 +4d --> four days from today
12923 +4 --> same as above
12924 +2w --> two weeks from today
12925 ++5 --> five days from default date
12927 The function understands only English month and weekday abbreviations,
12928 but this can be configured with the variables `parse-time-months' and
12929 `parse-time-weekdays'.
12931 While prompting, a calendar is popped up - you can also select the
12932 date with the mouse (button 1). The calendar shows a period of three
12933 months. To scroll it to other months, use the keys `>' and `<'.
12934 If you don't like the calendar, turn it off with
12935 \(setq org-read-date-popup-calendar nil)
12937 With optional argument TO-TIME, the date will immediately be converted
12938 to an internal time.
12939 With an optional argument WITH-TIME, the prompt will suggest to also
12940 insert a time. Note that when WITH-TIME is not set, you can still
12941 enter a time, and this function will inform the calling routine about
12942 this change. The calling routine may then choose to change the format
12943 used to insert the time stamp into the buffer to include the time.
12944 With optional argument FROM-STRING, read from this string instead from
12945 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12946 the time/date that is used for everything that is not specified by the
12947 user."
12948 (require 'parse-time)
12949 (let* ((org-time-stamp-rounding-minutes
12950 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12951 (org-dcst org-display-custom-times)
12952 (ct (org-current-time))
12953 (def (or org-overriding-default-time default-time ct))
12954 (defdecode (decode-time def))
12955 (dummy (progn
12956 (when (< (nth 2 defdecode) org-extend-today-until)
12957 (setcar (nthcdr 2 defdecode) -1)
12958 (setcar (nthcdr 1 defdecode) 59)
12959 (setq def (apply 'encode-time defdecode)
12960 defdecode (decode-time def)))))
12961 (calendar-frame-setup nil)
12962 (calendar-move-hook nil)
12963 (calendar-view-diary-initially-flag nil)
12964 (view-diary-entries-initially nil)
12965 (calendar-view-holidays-initially-flag nil)
12966 (view-calendar-holidays-initially nil)
12967 (timestr (format-time-string
12968 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12969 (prompt (concat (if prompt (concat prompt " ") "")
12970 (format "Date+time [%s]: " timestr)))
12971 ans (org-ans0 "") org-ans1 org-ans2 final)
12973 (cond
12974 (from-string (setq ans from-string))
12975 (org-read-date-popup-calendar
12976 (save-excursion
12977 (save-window-excursion
12978 (calendar)
12979 (calendar-forward-day (- (time-to-days def)
12980 (calendar-absolute-from-gregorian
12981 (calendar-current-date))))
12982 (org-eval-in-calendar nil t)
12983 (let* ((old-map (current-local-map))
12984 (map (copy-keymap calendar-mode-map))
12985 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12986 (org-defkey map (kbd "RET") 'org-calendar-select)
12987 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12988 'org-calendar-select-mouse)
12989 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12990 'org-calendar-select-mouse)
12991 (org-defkey minibuffer-local-map [(meta shift left)]
12992 (lambda () (interactive)
12993 (org-eval-in-calendar '(calendar-backward-month 1))))
12994 (org-defkey minibuffer-local-map [(meta shift right)]
12995 (lambda () (interactive)
12996 (org-eval-in-calendar '(calendar-forward-month 1))))
12997 (org-defkey minibuffer-local-map [(meta shift up)]
12998 (lambda () (interactive)
12999 (org-eval-in-calendar '(calendar-backward-year 1))))
13000 (org-defkey minibuffer-local-map [(meta shift down)]
13001 (lambda () (interactive)
13002 (org-eval-in-calendar '(calendar-forward-year 1))))
13003 (org-defkey minibuffer-local-map [?\e (shift left)]
13004 (lambda () (interactive)
13005 (org-eval-in-calendar '(calendar-backward-month 1))))
13006 (org-defkey minibuffer-local-map [?\e (shift right)]
13007 (lambda () (interactive)
13008 (org-eval-in-calendar '(calendar-forward-month 1))))
13009 (org-defkey minibuffer-local-map [?\e (shift up)]
13010 (lambda () (interactive)
13011 (org-eval-in-calendar '(calendar-backward-year 1))))
13012 (org-defkey minibuffer-local-map [?\e (shift down)]
13013 (lambda () (interactive)
13014 (org-eval-in-calendar '(calendar-forward-year 1))))
13015 (org-defkey minibuffer-local-map [(shift up)]
13016 (lambda () (interactive)
13017 (org-eval-in-calendar '(calendar-backward-week 1))))
13018 (org-defkey minibuffer-local-map [(shift down)]
13019 (lambda () (interactive)
13020 (org-eval-in-calendar '(calendar-forward-week 1))))
13021 (org-defkey minibuffer-local-map [(shift left)]
13022 (lambda () (interactive)
13023 (org-eval-in-calendar '(calendar-backward-day 1))))
13024 (org-defkey minibuffer-local-map [(shift right)]
13025 (lambda () (interactive)
13026 (org-eval-in-calendar '(calendar-forward-day 1))))
13027 (org-defkey minibuffer-local-map ">"
13028 (lambda () (interactive)
13029 (org-eval-in-calendar '(scroll-calendar-left 1))))
13030 (org-defkey minibuffer-local-map "<"
13031 (lambda () (interactive)
13032 (org-eval-in-calendar '(scroll-calendar-right 1))))
13033 (run-hooks 'org-read-date-minibuffer-setup-hook)
13034 (unwind-protect
13035 (progn
13036 (use-local-map map)
13037 (add-hook 'post-command-hook 'org-read-date-display)
13038 (setq org-ans0 (read-string prompt default-input
13039 'org-read-date-history nil))
13040 ;; org-ans0: from prompt
13041 ;; org-ans1: from mouse click
13042 ;; org-ans2: from calendar motion
13043 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13044 (remove-hook 'post-command-hook 'org-read-date-display)
13045 (use-local-map old-map)
13046 (when org-read-date-overlay
13047 (org-delete-overlay org-read-date-overlay)
13048 (setq org-read-date-overlay nil)))))))
13050 (t ; Naked prompt only
13051 (unwind-protect
13052 (setq ans (read-string prompt default-input
13053 'org-read-date-history timestr))
13054 (when org-read-date-overlay
13055 (org-delete-overlay org-read-date-overlay)
13056 (setq org-read-date-overlay nil)))))
13058 (setq final (org-read-date-analyze ans def defdecode))
13059 (setq org-read-date-final-answer ans)
13061 (if to-time
13062 (apply 'encode-time final)
13063 (if (and (boundp 'org-time-was-given) org-time-was-given)
13064 (format "%04d-%02d-%02d %02d:%02d"
13065 (nth 5 final) (nth 4 final) (nth 3 final)
13066 (nth 2 final) (nth 1 final))
13067 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13069 (defvar def)
13070 (defvar defdecode)
13071 (defvar with-time)
13072 (defvar org-read-date-analyze-futurep nil)
13073 (defun org-read-date-display ()
13074 "Display the current date prompt interpretation in the minibuffer."
13075 (when org-read-date-display-live
13076 (when org-read-date-overlay
13077 (org-delete-overlay org-read-date-overlay))
13078 (let ((p (point)))
13079 (end-of-line 1)
13080 (while (not (equal (buffer-substring
13081 (max (point-min) (- (point) 4)) (point))
13082 " "))
13083 (insert " "))
13084 (goto-char p))
13085 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13086 " " (or org-ans1 org-ans2)))
13087 (org-end-time-was-given nil)
13088 (f (org-read-date-analyze ans def defdecode))
13089 (fmts (if org-dcst
13090 org-time-stamp-custom-formats
13091 org-time-stamp-formats))
13092 (fmt (if (or with-time
13093 (and (boundp 'org-time-was-given) org-time-was-given))
13094 (cdr fmts)
13095 (car fmts)))
13096 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13097 (when (and org-end-time-was-given
13098 (string-match org-plain-time-of-day-regexp txt))
13099 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13100 org-end-time-was-given
13101 (substring txt (match-end 0)))))
13102 (when org-read-date-analyze-futurep
13103 (setq txt (concat txt " (=>F)")))
13104 (setq org-read-date-overlay
13105 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13106 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13108 (defun org-read-date-analyze (ans def defdecode)
13109 "Analyse the combined answer of the date prompt."
13110 ;; FIXME: cleanup and comment
13111 (let (delta deltan deltaw deltadef year month day
13112 hour minute second wday pm h2 m2 tl wday1
13113 iso-year iso-weekday iso-week iso-year iso-date futurep)
13114 (setq org-read-date-analyze-futurep nil)
13115 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13116 (setq ans "+0"))
13118 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13119 (setq ans (replace-match "" t t ans)
13120 deltan (car delta)
13121 deltaw (nth 1 delta)
13122 deltadef (nth 2 delta)))
13124 ;; Check if there is an iso week date in there
13125 ;; If yes, sore the info and postpone interpreting it until the rest
13126 ;; of the parsing is done
13127 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13128 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
13129 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
13130 iso-week (string-to-number (match-string 2 ans)))
13131 (setq ans (replace-match "" t t ans)))
13133 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
13134 (when (string-match
13135 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13136 (setq year (if (match-end 2)
13137 (string-to-number (match-string 2 ans))
13138 (string-to-number (format-time-string "%Y")))
13139 month (string-to-number (match-string 3 ans))
13140 day (string-to-number (match-string 4 ans)))
13141 (if (< year 100) (setq year (+ 2000 year)))
13142 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13143 t nil ans)))
13144 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13145 ;; If there is a time with am/pm, and *no* time without it, we convert
13146 ;; so that matching will be successful.
13147 (loop for i from 1 to 2 do ; twice, for end time as well
13148 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13149 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13150 (setq hour (string-to-number (match-string 1 ans))
13151 minute (if (match-end 3)
13152 (string-to-number (match-string 3 ans))
13154 pm (equal ?p
13155 (string-to-char (downcase (match-string 4 ans)))))
13156 (if (and (= hour 12) (not pm))
13157 (setq hour 0)
13158 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13159 (setq ans (replace-match (format "%02d:%02d" hour minute)
13160 t t ans))))
13162 ;; Check if a time range is given as a duration
13163 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13164 (setq hour (string-to-number (match-string 1 ans))
13165 h2 (+ hour (string-to-number (match-string 3 ans)))
13166 minute (string-to-number (match-string 2 ans))
13167 m2 (+ minute (if (match-end 5) (string-to-number
13168 (match-string 5 ans))0)))
13169 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13170 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13171 t t ans)))
13173 ;; Check if there is a time range
13174 (when (boundp 'org-end-time-was-given)
13175 (setq org-time-was-given nil)
13176 (when (and (string-match org-plain-time-of-day-regexp ans)
13177 (match-end 8))
13178 (setq org-end-time-was-given (match-string 8 ans))
13179 (setq ans (concat (substring ans 0 (match-beginning 7))
13180 (substring ans (match-end 7))))))
13182 (setq tl (parse-time-string ans)
13183 day (or (nth 3 tl) (nth 3 defdecode))
13184 month (or (nth 4 tl)
13185 (if (and org-read-date-prefer-future
13186 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
13187 (prog1 (1+ (nth 4 defdecode)) (setq futurep t))
13188 (nth 4 defdecode)))
13189 year (or (nth 5 tl)
13190 (if (and org-read-date-prefer-future
13191 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
13192 (prog1 (1+ (nth 5 defdecode)) (setq futurep t))
13193 (nth 5 defdecode)))
13194 hour (or (nth 2 tl) (nth 2 defdecode))
13195 minute (or (nth 1 tl) (nth 1 defdecode))
13196 second (or (nth 0 tl) 0)
13197 wday (nth 6 tl))
13199 (when (and (eq org-read-date-prefer-future 'time)
13200 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13201 (equal day (nth 3 defdecode))
13202 (equal month (nth 4 defdecode))
13203 (equal year (nth 5 defdecode))
13204 (nth 2 tl)
13205 (or (< (nth 2 tl) (nth 2 defdecode))
13206 (and (= (nth 2 tl) (nth 2 defdecode))
13207 (nth 1 tl)
13208 (< (nth 1 tl) (nth 1 defdecode)))))
13209 (setq day (1+ day)
13210 futurep t))
13212 ;; Special date definitions below
13213 (cond
13214 (iso-week
13215 ;; There was an iso week
13216 (setq futurep nil)
13217 (setq year (or iso-year year)
13218 day (or iso-weekday wday 1)
13219 wday nil ; to make sure that the trigger below does not match
13220 iso-date (calendar-gregorian-from-absolute
13221 (calendar-absolute-from-iso
13222 (list iso-week day year))))
13223 ; FIXME: Should we also push ISO weeks into the future?
13224 ; (when (and org-read-date-prefer-future
13225 ; (not iso-year)
13226 ; (< (calendar-absolute-from-gregorian iso-date)
13227 ; (time-to-days (current-time))))
13228 ; (setq year (1+ year)
13229 ; iso-date (calendar-gregorian-from-absolute
13230 ; (calendar-absolute-from-iso
13231 ; (list iso-week day year)))))
13232 (setq month (car iso-date)
13233 year (nth 2 iso-date)
13234 day (nth 1 iso-date)))
13235 (deltan
13236 (setq futurep nil)
13237 (unless deltadef
13238 (let ((now (decode-time (current-time))))
13239 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13240 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13241 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13242 ((equal deltaw "m") (setq month (+ month deltan)))
13243 ((equal deltaw "y") (setq year (+ year deltan)))))
13244 ((and wday (not (nth 3 tl)))
13245 (setq futurep nil)
13246 ;; Weekday was given, but no day, so pick that day in the week
13247 ;; on or after the derived date.
13248 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13249 (unless (equal wday wday1)
13250 (setq day (+ day (% (- wday wday1 -7) 7))))))
13251 (if (and (boundp 'org-time-was-given)
13252 (nth 2 tl))
13253 (setq org-time-was-given t))
13254 (if (< year 100) (setq year (+ 2000 year)))
13255 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13256 (setq org-read-date-analyze-futurep futurep)
13257 (list second minute hour day month year)))
13259 (defvar parse-time-weekdays)
13261 (defun org-read-date-get-relative (s today default)
13262 "Check string S for special relative date string.
13263 TODAY and DEFAULT are internal times, for today and for a default.
13264 Return shift list (N what def-flag)
13265 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13266 N is the number of WHATs to shift.
13267 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13268 the DEFAULT date rather than TODAY."
13269 (when (and
13270 (string-match
13271 (concat
13272 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13273 "\\([0-9]+\\)?"
13274 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13275 "\\([ \t]\\|$\\)") s)
13276 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13277 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13278 (string-to-char (substring (match-string 1 s) -1))
13279 ?+))
13280 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13281 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13282 (what (if (match-end 3) (match-string 3 s) "d"))
13283 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13284 (date (if rel default today))
13285 (wday (nth 6 (decode-time date)))
13286 delta)
13287 (if wday1
13288 (progn
13289 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13290 (if (= dir ?-) (setq delta (- delta 7)))
13291 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13292 (list delta "d" rel))
13293 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13295 (defun org-eval-in-calendar (form &optional keepdate)
13296 "Eval FORM in the calendar window and return to current window.
13297 Also, store the cursor date in variable org-ans2."
13298 (let ((sf (selected-frame))
13299 (sw (selected-window)))
13300 (select-window (get-buffer-window "*Calendar*" t))
13301 (eval form)
13302 (when (and (not keepdate) (calendar-cursor-to-date))
13303 (let* ((date (calendar-cursor-to-date))
13304 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13305 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13306 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13307 (select-window sw)
13308 (org-select-frame-set-input-focus sf)))
13310 (defun org-calendar-select ()
13311 "Return to `org-read-date' with the date currently selected.
13312 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13313 (interactive)
13314 (when (calendar-cursor-to-date)
13315 (let* ((date (calendar-cursor-to-date))
13316 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13317 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13318 (if (active-minibuffer-window) (exit-minibuffer))))
13320 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13321 "Insert a date stamp for the date given by the internal TIME.
13322 WITH-HM means, use the stamp format that includes the time of the day.
13323 INACTIVE means use square brackets instead of angular ones, so that the
13324 stamp will not contribute to the agenda.
13325 PRE and POST are optional strings to be inserted before and after the
13326 stamp.
13327 The command returns the inserted time stamp."
13328 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13329 stamp)
13330 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13331 (insert-before-markers (or pre ""))
13332 (insert-before-markers (setq stamp (format-time-string fmt time)))
13333 (when (listp extra)
13334 (setq extra (car extra))
13335 (if (and (stringp extra)
13336 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13337 (setq extra (format "-%02d:%02d"
13338 (string-to-number (match-string 1 extra))
13339 (string-to-number (match-string 2 extra))))
13340 (setq extra nil)))
13341 (when extra
13342 (backward-char 1)
13343 (insert-before-markers extra)
13344 (forward-char 1))
13345 (insert-before-markers (or post ""))
13346 (setq org-last-inserted-timestamp stamp)))
13348 (defun org-toggle-time-stamp-overlays ()
13349 "Toggle the use of custom time stamp formats."
13350 (interactive)
13351 (setq org-display-custom-times (not org-display-custom-times))
13352 (unless org-display-custom-times
13353 (let ((p (point-min)) (bmp (buffer-modified-p)))
13354 (while (setq p (next-single-property-change p 'display))
13355 (if (and (get-text-property p 'display)
13356 (eq (get-text-property p 'face) 'org-date))
13357 (remove-text-properties
13358 p (setq p (next-single-property-change p 'display))
13359 '(display t))))
13360 (set-buffer-modified-p bmp)))
13361 (if (featurep 'xemacs)
13362 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13363 (org-restart-font-lock)
13364 (setq org-table-may-need-update t)
13365 (if org-display-custom-times
13366 (message "Time stamps are overlayed with custom format")
13367 (message "Time stamp overlays removed")))
13369 (defun org-display-custom-time (beg end)
13370 "Overlay modified time stamp format over timestamp between BEG and END."
13371 (let* ((ts (buffer-substring beg end))
13372 t1 w1 with-hm tf time str w2 (off 0))
13373 (save-match-data
13374 (setq t1 (org-parse-time-string ts t))
13375 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13376 (setq off (- (match-end 0) (match-beginning 0)))))
13377 (setq end (- end off))
13378 (setq w1 (- end beg)
13379 with-hm (and (nth 1 t1) (nth 2 t1))
13380 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13381 time (org-fix-decoded-time t1)
13382 str (org-add-props
13383 (format-time-string
13384 (substring tf 1 -1) (apply 'encode-time time))
13385 nil 'mouse-face 'highlight)
13386 w2 (length str))
13387 (if (not (= w2 w1))
13388 (add-text-properties (1+ beg) (+ 2 beg)
13389 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13390 (if (featurep 'xemacs)
13391 (progn
13392 (put-text-property beg end 'invisible t)
13393 (put-text-property beg end 'end-glyph (make-glyph str)))
13394 (put-text-property beg end 'display str))))
13396 (defun org-translate-time (string)
13397 "Translate all timestamps in STRING to custom format.
13398 But do this only if the variable `org-display-custom-times' is set."
13399 (when org-display-custom-times
13400 (save-match-data
13401 (let* ((start 0)
13402 (re org-ts-regexp-both)
13403 t1 with-hm inactive tf time str beg end)
13404 (while (setq start (string-match re string start))
13405 (setq beg (match-beginning 0)
13406 end (match-end 0)
13407 t1 (save-match-data
13408 (org-parse-time-string (substring string beg end) t))
13409 with-hm (and (nth 1 t1) (nth 2 t1))
13410 inactive (equal (substring string beg (1+ beg)) "[")
13411 tf (funcall (if with-hm 'cdr 'car)
13412 org-time-stamp-custom-formats)
13413 time (org-fix-decoded-time t1)
13414 str (format-time-string
13415 (concat
13416 (if inactive "[" "<") (substring tf 1 -1)
13417 (if inactive "]" ">"))
13418 (apply 'encode-time time))
13419 string (replace-match str t t string)
13420 start (+ start (length str)))))))
13421 string)
13423 (defun org-fix-decoded-time (time)
13424 "Set 0 instead of nil for the first 6 elements of time.
13425 Don't touch the rest."
13426 (let ((n 0))
13427 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13429 (defun org-days-to-time (timestamp-string)
13430 "Difference between TIMESTAMP-STRING and now in days."
13431 (- (time-to-days (org-time-string-to-time timestamp-string))
13432 (time-to-days (current-time))))
13434 (defun org-deadline-close (timestamp-string &optional ndays)
13435 "Is the time in TIMESTAMP-STRING close to the current date?"
13436 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13437 (and (< (org-days-to-time timestamp-string) ndays)
13438 (not (org-entry-is-done-p))))
13440 (defun org-get-wdays (ts)
13441 "Get the deadline lead time appropriate for timestring TS."
13442 (cond
13443 ((<= org-deadline-warning-days 0)
13444 ;; 0 or negative, enforce this value no matter what
13445 (- org-deadline-warning-days))
13446 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13447 ;; lead time is specified.
13448 (floor (* (string-to-number (match-string 1 ts))
13449 (cdr (assoc (match-string 2 ts)
13450 '(("d" . 1) ("w" . 7)
13451 ("m" . 30.4) ("y" . 365.25)))))))
13452 ;; go for the default.
13453 (t org-deadline-warning-days)))
13455 (defun org-calendar-select-mouse (ev)
13456 "Return to `org-read-date' with the date currently selected.
13457 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13458 (interactive "e")
13459 (mouse-set-point ev)
13460 (when (calendar-cursor-to-date)
13461 (let* ((date (calendar-cursor-to-date))
13462 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13463 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13464 (if (active-minibuffer-window) (exit-minibuffer))))
13466 (defun org-check-deadlines (ndays)
13467 "Check if there are any deadlines due or past due.
13468 A deadline is considered due if it happens within `org-deadline-warning-days'
13469 days from today's date. If the deadline appears in an entry marked DONE,
13470 it is not shown. The prefix arg NDAYS can be used to test that many
13471 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13472 (interactive "P")
13473 (let* ((org-warn-days
13474 (cond
13475 ((equal ndays '(4)) 100000)
13476 (ndays (prefix-numeric-value ndays))
13477 (t (abs org-deadline-warning-days))))
13478 (case-fold-search nil)
13479 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13480 (callback
13481 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13483 (message "%d deadlines past-due or due within %d days"
13484 (org-occur regexp nil callback)
13485 org-warn-days)))
13487 (defun org-check-before-date (date)
13488 "Check if there are deadlines or scheduled entries before DATE."
13489 (interactive (list (org-read-date)))
13490 (let ((case-fold-search nil)
13491 (regexp (concat "\\<\\(" org-deadline-string
13492 "\\|" org-scheduled-string
13493 "\\) *<\\([^>]+\\)>"))
13494 (callback
13495 (lambda () (time-less-p
13496 (org-time-string-to-time (match-string 2))
13497 (org-time-string-to-time date)))))
13498 (message "%d entries before %s"
13499 (org-occur regexp nil callback) date)))
13501 (defun org-check-after-date (date)
13502 "Check if there are deadlines or scheduled entries after DATE."
13503 (interactive (list (org-read-date)))
13504 (let ((case-fold-search nil)
13505 (regexp (concat "\\<\\(" org-deadline-string
13506 "\\|" org-scheduled-string
13507 "\\) *<\\([^>]+\\)>"))
13508 (callback
13509 (lambda () (not
13510 (time-less-p
13511 (org-time-string-to-time (match-string 2))
13512 (org-time-string-to-time date))))))
13513 (message "%d entries after %s"
13514 (org-occur regexp nil callback) date)))
13516 (defun org-evaluate-time-range (&optional to-buffer)
13517 "Evaluate a time range by computing the difference between start and end.
13518 Normally the result is just printed in the echo area, but with prefix arg
13519 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13520 If the time range is actually in a table, the result is inserted into the
13521 next column.
13522 For time difference computation, a year is assumed to be exactly 365
13523 days in order to avoid rounding problems."
13524 (interactive "P")
13526 (org-clock-update-time-maybe)
13527 (save-excursion
13528 (unless (org-at-date-range-p t)
13529 (goto-char (point-at-bol))
13530 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13531 (if (not (org-at-date-range-p t))
13532 (error "Not at a time-stamp range, and none found in current line")))
13533 (let* ((ts1 (match-string 1))
13534 (ts2 (match-string 2))
13535 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13536 (match-end (match-end 0))
13537 (time1 (org-time-string-to-time ts1))
13538 (time2 (org-time-string-to-time ts2))
13539 (t1 (org-float-time time1))
13540 (t2 (org-float-time time2))
13541 (diff (abs (- t2 t1)))
13542 (negative (< (- t2 t1) 0))
13543 ;; (ys (floor (* 365 24 60 60)))
13544 (ds (* 24 60 60))
13545 (hs (* 60 60))
13546 (fy "%dy %dd %02d:%02d")
13547 (fy1 "%dy %dd")
13548 (fd "%dd %02d:%02d")
13549 (fd1 "%dd")
13550 (fh "%02d:%02d")
13551 y d h m align)
13552 (if havetime
13553 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13555 d (floor (/ diff ds)) diff (mod diff ds)
13556 h (floor (/ diff hs)) diff (mod diff hs)
13557 m (floor (/ diff 60)))
13558 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13560 d (floor (+ (/ diff ds) 0.5))
13561 h 0 m 0))
13562 (if (not to-buffer)
13563 (message "%s" (org-make-tdiff-string y d h m))
13564 (if (org-at-table-p)
13565 (progn
13566 (goto-char match-end)
13567 (setq align t)
13568 (and (looking-at " *|") (goto-char (match-end 0))))
13569 (goto-char match-end))
13570 (if (looking-at
13571 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13572 (replace-match ""))
13573 (if negative (insert " -"))
13574 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13575 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13576 (insert " " (format fh h m))))
13577 (if align (org-table-align))
13578 (message "Time difference inserted")))))
13580 (defun org-make-tdiff-string (y d h m)
13581 (let ((fmt "")
13582 (l nil))
13583 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13584 l (push y l)))
13585 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13586 l (push d l)))
13587 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13588 l (push h l)))
13589 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13590 l (push m l)))
13591 (apply 'format fmt (nreverse l))))
13593 (defun org-time-string-to-time (s)
13594 (apply 'encode-time (org-parse-time-string s)))
13595 (defun org-time-string-to-seconds (s)
13596 (org-float-time (org-time-string-to-time s)))
13598 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13599 "Convert a time stamp to an absolute day number.
13600 If there is a specifyer for a cyclic time stamp, get the closest date to
13601 DAYNR.
13602 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13603 the variable date is bound by the calendar when this is called."
13604 (cond
13605 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13606 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13607 daynr
13608 (+ daynr 1000)))
13609 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13610 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13611 (time-to-days (current-time))) (match-string 0 s)
13612 prefer show-all))
13613 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13615 (defun org-days-to-iso-week (days)
13616 "Return the iso week number."
13617 (require 'cal-iso)
13618 (car (calendar-iso-from-absolute days)))
13620 (defun org-small-year-to-year (year)
13621 "Convert 2-digit years into 4-digit years.
13622 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13623 The year 2000 cannot be abbreviated. Any year larger than 99
13624 is returned unchanged."
13625 (if (< year 38)
13626 (setq year (+ 2000 year))
13627 (if (< year 100)
13628 (setq year (+ 1900 year))))
13629 year)
13631 (defun org-time-from-absolute (d)
13632 "Return the time corresponding to date D.
13633 D may be an absolute day number, or a calendar-type list (month day year)."
13634 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13635 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13637 (defun org-calendar-holiday ()
13638 "List of holidays, for Diary display in Org-mode."
13639 (require 'holidays)
13640 (let ((hl (funcall
13641 (if (fboundp 'calendar-check-holidays)
13642 'calendar-check-holidays 'check-calendar-holidays) date)))
13643 (if hl (mapconcat 'identity hl "; "))))
13645 (defun org-diary-sexp-entry (sexp entry date)
13646 "Process a SEXP diary ENTRY for DATE."
13647 (require 'diary-lib)
13648 (let ((result (if calendar-debug-sexp
13649 (let ((stack-trace-on-error t))
13650 (eval (car (read-from-string sexp))))
13651 (condition-case nil
13652 (eval (car (read-from-string sexp)))
13653 (error
13654 (beep)
13655 (message "Bad sexp at line %d in %s: %s"
13656 (org-current-line)
13657 (buffer-file-name) sexp)
13658 (sleep-for 2))))))
13659 (cond ((stringp result) result)
13660 ((and (consp result)
13661 (stringp (cdr result))) (cdr result))
13662 (result entry)
13663 (t nil))))
13665 (defun org-diary-to-ical-string (frombuf)
13666 "Get iCalendar entries from diary entries in buffer FROMBUF.
13667 This uses the icalendar.el library."
13668 (let* ((tmpdir (if (featurep 'xemacs)
13669 (temp-directory)
13670 temporary-file-directory))
13671 (tmpfile (make-temp-name
13672 (expand-file-name "orgics" tmpdir)))
13673 buf rtn b e)
13674 (with-current-buffer frombuf
13675 (icalendar-export-region (point-min) (point-max) tmpfile)
13676 (setq buf (find-buffer-visiting tmpfile))
13677 (set-buffer buf)
13678 (goto-char (point-min))
13679 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13680 (setq b (match-beginning 0)))
13681 (goto-char (point-max))
13682 (if (re-search-backward "^END:VEVENT" nil t)
13683 (setq e (match-end 0)))
13684 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13685 (kill-buffer buf)
13686 (delete-file tmpfile)
13687 rtn))
13689 (defun org-closest-date (start current change prefer show-all)
13690 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13691 When PREFER is `past' return a date that is either CURRENT or past.
13692 When PREFER is `future', return a date that is either CURRENT or future.
13693 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13694 ;; Make the proper lists from the dates
13695 (catch 'exit
13696 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13697 dn dw sday cday n1 n2 n0
13698 d m y y1 y2 date1 date2 nmonths nm ny m2)
13700 (setq start (org-date-to-gregorian start)
13701 current (org-date-to-gregorian
13702 (if show-all
13703 current
13704 (time-to-days (current-time))))
13705 sday (calendar-absolute-from-gregorian start)
13706 cday (calendar-absolute-from-gregorian current))
13708 (if (<= cday sday) (throw 'exit sday))
13710 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13711 (setq dn (string-to-number (match-string 1 change))
13712 dw (cdr (assoc (match-string 2 change) a1)))
13713 (error "Invalid change specifyer: %s" change))
13714 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13715 (cond
13716 ((eq dw 'day)
13717 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13718 n2 (+ n1 dn)))
13719 ((eq dw 'year)
13720 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13721 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13722 (setq date1 (list m d y1)
13723 n1 (calendar-absolute-from-gregorian date1)
13724 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13725 n2 (calendar-absolute-from-gregorian date2)))
13726 ((eq dw 'month)
13727 ;; approx number of month between the two dates
13728 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13729 ;; How often does dn fit in there?
13730 (setq d (nth 1 start) m (car start) y (nth 2 start)
13731 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13732 m (+ m nm)
13733 ny (floor (/ m 12))
13734 y (+ y ny)
13735 m (- m (* ny 12)))
13736 (while (> m 12) (setq m (- m 12) y (1+ y)))
13737 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13738 (setq m2 (+ m dn) y2 y)
13739 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13740 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13741 (while (<= n2 cday)
13742 (setq n1 n2 m m2 y y2)
13743 (setq m2 (+ m dn) y2 y)
13744 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13745 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13746 ;; Make sure n1 is the earlier date
13747 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13748 (if show-all
13749 (cond
13750 ((eq prefer 'past) (if (= cday n2) n2 n1))
13751 ((eq prefer 'future) (if (= cday n1) n1 n2))
13752 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13753 (cond
13754 ((eq prefer 'past) (if (= cday n2) n2 n1))
13755 ((eq prefer 'future) (if (= cday n1) n1 n2))
13756 (t (if (= cday n1) n1 n2)))))))
13758 (defun org-date-to-gregorian (date)
13759 "Turn any specification of DATE into a gregorian date for the calendar."
13760 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13761 ((and (listp date) (= (length date) 3)) date)
13762 ((stringp date)
13763 (setq date (org-parse-time-string date))
13764 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13765 ((listp date)
13766 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13768 (defun org-parse-time-string (s &optional nodefault)
13769 "Parse the standard Org-mode time string.
13770 This should be a lot faster than the normal `parse-time-string'.
13771 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13772 hour and minute fields will be nil if not given."
13773 (if (string-match org-ts-regexp0 s)
13774 (list 0
13775 (if (or (match-beginning 8) (not nodefault))
13776 (string-to-number (or (match-string 8 s) "0")))
13777 (if (or (match-beginning 7) (not nodefault))
13778 (string-to-number (or (match-string 7 s) "0")))
13779 (string-to-number (match-string 4 s))
13780 (string-to-number (match-string 3 s))
13781 (string-to-number (match-string 2 s))
13782 nil nil nil)
13783 (error "Not a standard Org-mode time string: %s" s)))
13785 (defun org-timestamp-up (&optional arg)
13786 "Increase the date item at the cursor by one.
13787 If the cursor is on the year, change the year. If it is on the month or
13788 the day, change that.
13789 With prefix ARG, change by that many units."
13790 (interactive "p")
13791 (org-timestamp-change (prefix-numeric-value arg)))
13793 (defun org-timestamp-down (&optional arg)
13794 "Decrease the date item at the cursor by one.
13795 If the cursor is on the year, change the year. If it is on the month or
13796 the day, change that.
13797 With prefix ARG, change by that many units."
13798 (interactive "p")
13799 (org-timestamp-change (- (prefix-numeric-value arg))))
13801 (defun org-timestamp-up-day (&optional arg)
13802 "Increase the date in the time stamp by one day.
13803 With prefix ARG, change that many days."
13804 (interactive "p")
13805 (if (and (not (org-at-timestamp-p t))
13806 (org-on-heading-p))
13807 (org-todo 'up)
13808 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13810 (defun org-timestamp-down-day (&optional arg)
13811 "Decrease the date in the time stamp by one day.
13812 With prefix ARG, change that many days."
13813 (interactive "p")
13814 (if (and (not (org-at-timestamp-p t))
13815 (org-on-heading-p))
13816 (org-todo 'down)
13817 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13819 (defun org-at-timestamp-p (&optional inactive-ok)
13820 "Determine if the cursor is in or at a timestamp."
13821 (interactive)
13822 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13823 (pos (point))
13824 (ans (or (looking-at tsr)
13825 (save-excursion
13826 (skip-chars-backward "^[<\n\r\t")
13827 (if (> (point) (point-min)) (backward-char 1))
13828 (and (looking-at tsr)
13829 (> (- (match-end 0) pos) -1))))))
13830 (and ans
13831 (boundp 'org-ts-what)
13832 (setq org-ts-what
13833 (cond
13834 ((= pos (match-beginning 0)) 'bracket)
13835 ((= pos (1- (match-end 0))) 'bracket)
13836 ((org-pos-in-match-range pos 2) 'year)
13837 ((org-pos-in-match-range pos 3) 'month)
13838 ((org-pos-in-match-range pos 7) 'hour)
13839 ((org-pos-in-match-range pos 8) 'minute)
13840 ((or (org-pos-in-match-range pos 4)
13841 (org-pos-in-match-range pos 5)) 'day)
13842 ((and (> pos (or (match-end 8) (match-end 5)))
13843 (< pos (match-end 0)))
13844 (- pos (or (match-end 8) (match-end 5))))
13845 (t 'day))))
13846 ans))
13848 (defun org-toggle-timestamp-type ()
13849 "Toggle the type (<active> or [inactive]) of a time stamp."
13850 (interactive)
13851 (when (org-at-timestamp-p t)
13852 (let ((beg (match-beginning 0)) (end (match-end 0))
13853 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13854 (save-excursion
13855 (goto-char beg)
13856 (while (re-search-forward "[][<>]" end t)
13857 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13858 t t)))
13859 (message "Timestamp is now %sactive"
13860 (if (equal (char-after beg) ?<) "" "in")))))
13862 (defun org-timestamp-change (n &optional what)
13863 "Change the date in the time stamp at point.
13864 The date will be changed by N times WHAT. WHAT can be `day', `month',
13865 `year', `minute', `second'. If WHAT is not given, the cursor position
13866 in the timestamp determines what will be changed."
13867 (let ((pos (point))
13868 with-hm inactive
13869 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13870 org-ts-what
13871 extra rem
13872 ts time time0)
13873 (if (not (org-at-timestamp-p t))
13874 (error "Not at a timestamp"))
13875 (if (and (not what) (eq org-ts-what 'bracket))
13876 (org-toggle-timestamp-type)
13877 (if (and (not what) (not (eq org-ts-what 'day))
13878 org-display-custom-times
13879 (get-text-property (point) 'display)
13880 (not (get-text-property (1- (point)) 'display)))
13881 (setq org-ts-what 'day))
13882 (setq org-ts-what (or what org-ts-what)
13883 inactive (= (char-after (match-beginning 0)) ?\[)
13884 ts (match-string 0))
13885 (replace-match "")
13886 (if (string-match
13887 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
13889 (setq extra (match-string 1 ts)))
13890 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13891 (setq with-hm t))
13892 (setq time0 (org-parse-time-string ts))
13893 (when (and (eq org-ts-what 'minute)
13894 (eq current-prefix-arg nil))
13895 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13896 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13897 (setcar (cdr time0) (+ (nth 1 time0)
13898 (if (> n 0) (- rem) (- dm rem))))))
13899 (setq time
13900 (encode-time (or (car time0) 0)
13901 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13902 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13903 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13904 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13905 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13906 (nthcdr 6 time0)))
13907 (when (and (member org-ts-what '(hour minute))
13908 extra
13909 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13910 (setq extra (org-modify-ts-extra
13911 extra
13912 (if (eq org-ts-what 'hour) 2 5)
13913 n dm)))
13914 (when (integerp org-ts-what)
13915 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13916 (if (eq what 'calendar)
13917 (let ((cal-date (org-get-date-from-calendar)))
13918 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13919 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13920 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13921 (setcar time0 (or (car time0) 0))
13922 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13923 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13924 (setq time (apply 'encode-time time0))))
13925 (setq org-last-changed-timestamp
13926 (org-insert-time-stamp time with-hm inactive nil nil extra))
13927 (org-clock-update-time-maybe)
13928 (goto-char pos)
13929 ;; Try to recenter the calendar window, if any
13930 (if (and org-calendar-follow-timestamp-change
13931 (get-buffer-window "*Calendar*" t)
13932 (memq org-ts-what '(day month year)))
13933 (org-recenter-calendar (time-to-days time))))))
13935 (defun org-modify-ts-extra (s pos n dm)
13936 "Change the different parts of the lead-time and repeat fields in timestamp."
13937 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13938 ng h m new rem)
13939 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13940 (cond
13941 ((or (org-pos-in-match-range pos 2)
13942 (org-pos-in-match-range pos 3))
13943 (setq m (string-to-number (match-string 3 s))
13944 h (string-to-number (match-string 2 s)))
13945 (if (org-pos-in-match-range pos 2)
13946 (setq h (+ h n))
13947 (setq n (* dm (org-no-warnings (signum n))))
13948 (when (not (= 0 (setq rem (% m dm))))
13949 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13950 (setq m (+ m n)))
13951 (if (< m 0) (setq m (+ m 60) h (1- h)))
13952 (if (> m 59) (setq m (- m 60) h (1+ h)))
13953 (setq h (min 24 (max 0 h)))
13954 (setq ng 1 new (format "-%02d:%02d" h m)))
13955 ((org-pos-in-match-range pos 6)
13956 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13957 ((org-pos-in-match-range pos 5)
13958 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13960 ((org-pos-in-match-range pos 9)
13961 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13962 ((org-pos-in-match-range pos 8)
13963 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13965 (when ng
13966 (setq s (concat
13967 (substring s 0 (match-beginning ng))
13969 (substring s (match-end ng))))))
13972 (defun org-recenter-calendar (date)
13973 "If the calendar is visible, recenter it to DATE."
13974 (let* ((win (selected-window))
13975 (cwin (get-buffer-window "*Calendar*" t))
13976 (calendar-move-hook nil))
13977 (when cwin
13978 (select-window cwin)
13979 (calendar-goto-date (if (listp date) date
13980 (calendar-gregorian-from-absolute date)))
13981 (select-window win))))
13983 (defun org-goto-calendar (&optional arg)
13984 "Go to the Emacs calendar at the current date.
13985 If there is a time stamp in the current line, go to that date.
13986 A prefix ARG can be used to force the current date."
13987 (interactive "P")
13988 (let ((tsr org-ts-regexp) diff
13989 (calendar-move-hook nil)
13990 (calendar-view-holidays-initially-flag nil)
13991 (view-calendar-holidays-initially nil)
13992 (calendar-view-diary-initially-flag nil)
13993 (view-diary-entries-initially nil))
13994 (if (or (org-at-timestamp-p)
13995 (save-excursion
13996 (beginning-of-line 1)
13997 (looking-at (concat ".*" tsr))))
13998 (let ((d1 (time-to-days (current-time)))
13999 (d2 (time-to-days
14000 (org-time-string-to-time (match-string 1)))))
14001 (setq diff (- d2 d1))))
14002 (calendar)
14003 (calendar-goto-today)
14004 (if (and diff (not arg)) (calendar-forward-day diff))))
14006 (defun org-get-date-from-calendar ()
14007 "Return a list (month day year) of date at point in calendar."
14008 (with-current-buffer "*Calendar*"
14009 (save-match-data
14010 (calendar-cursor-to-date))))
14012 (defun org-date-from-calendar ()
14013 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14014 If there is already a time stamp at the cursor position, update it."
14015 (interactive)
14016 (if (org-at-timestamp-p t)
14017 (org-timestamp-change 0 'calendar)
14018 (let ((cal-date (org-get-date-from-calendar)))
14019 (org-insert-time-stamp
14020 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14022 (defun org-minutes-to-hh:mm-string (m)
14023 "Compute H:MM from a number of minutes."
14024 (let ((h (/ m 60)))
14025 (setq m (- m (* 60 h)))
14026 (format org-time-clocksum-format h m)))
14028 (defun org-hh:mm-string-to-minutes (s)
14029 "Convert a string H:MM to a number of minutes.
14030 If the string is just a number, interpret it as minutes.
14031 In fact, the first hh:mm or number in the string will be taken,
14032 there can be extra stuff in the string.
14033 If no number is found, the return value is 0."
14034 (cond
14035 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14036 (+ (* (string-to-number (match-string 1 s)) 60)
14037 (string-to-number (match-string 2 s))))
14038 ((string-match "\\([0-9]+\\)" s)
14039 (string-to-number (match-string 1 s)))
14040 (t 0)))
14042 ;;;; Files
14044 (defun org-save-all-org-buffers ()
14045 "Save all Org-mode buffers without user confirmation."
14046 (interactive)
14047 (message "Saving all Org-mode buffers...")
14048 (save-some-buffers t 'org-mode-p)
14049 (when (featurep 'org-id) (org-id-locations-save))
14050 (message "Saving all Org-mode buffers... done"))
14052 (defun org-revert-all-org-buffers ()
14053 "Revert all Org-mode buffers.
14054 Prompt for confirmation when there are unsaved changes.
14055 Be sure you know what you are doing before letting this function
14056 overwrite your changes.
14058 This function is useful in a setup where one tracks org files
14059 with a version control system, to revert on one machine after pulling
14060 changes from another. I believe the procedure must be like this:
14062 1. M-x org-save-all-org-buffers
14063 2. Pull changes from the other machine, resolve conflicts
14064 3. M-x org-revert-all-org-buffers"
14065 (interactive)
14066 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14067 (error "Abort"))
14068 (save-excursion
14069 (save-window-excursion
14070 (mapc
14071 (lambda (b)
14072 (when (and (with-current-buffer b (org-mode-p))
14073 (with-current-buffer b buffer-file-name))
14074 (switch-to-buffer b)
14075 (revert-buffer t 'no-confirm)))
14076 (buffer-list))
14077 (when (and (featurep 'org-id) org-id-track-globally)
14078 (org-id-locations-load)))))
14080 ;;;; Agenda files
14082 ;;;###autoload
14083 (defun org-iswitchb (&optional arg)
14084 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14085 With a prefix argument, restrict available to files.
14086 With two prefix arguments, restrict available buffers to agenda files."
14087 (interactive "P")
14088 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14089 ((equal arg '(16)) (org-buffer-list 'agenda))
14090 (t (org-buffer-list)))))
14091 (switch-to-buffer
14092 (org-icompleting-read "Org buffer: "
14093 (mapcar 'list (mapcar 'buffer-name blist))
14094 nil t))))
14096 ;;;###autoload
14097 (defalias 'org-ido-switchb 'org-iswitchb)
14099 (defun org-buffer-list (&optional predicate exclude-tmp)
14100 "Return a list of Org buffers.
14101 PREDICATE can be `export', `files' or `agenda'.
14103 export restrict the list to Export buffers.
14104 files restrict the list to buffers visiting Org files.
14105 agenda restrict the list to buffers visiting agenda files.
14107 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14108 (let* ((bfn nil)
14109 (agenda-files (and (eq predicate 'agenda)
14110 (mapcar 'file-truename (org-agenda-files t))))
14111 (filter
14112 (cond
14113 ((eq predicate 'files)
14114 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14115 ((eq predicate 'export)
14116 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14117 ((eq predicate 'agenda)
14118 (lambda (b)
14119 (with-current-buffer b
14120 (and (eq major-mode 'org-mode)
14121 (setq bfn (buffer-file-name b))
14122 (member (file-truename bfn) agenda-files)))))
14123 (t (lambda (b) (with-current-buffer b
14124 (or (eq major-mode 'org-mode)
14125 (string-match "\*Org .*Export"
14126 (buffer-name b)))))))))
14127 (delq nil
14128 (mapcar
14129 (lambda(b)
14130 (if (and (funcall filter b)
14131 (or (not exclude-tmp)
14132 (not (string-match "tmp" (buffer-name b)))))
14134 nil))
14135 (buffer-list)))))
14137 (defun org-agenda-files (&optional unrestricted archives)
14138 "Get the list of agenda files.
14139 Optional UNRESTRICTED means return the full list even if a restriction
14140 is currently in place.
14141 When ARCHIVES is t, include all archive files hat are really being
14142 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14143 `org-agenda-archives-mode' is t."
14144 (let ((files
14145 (cond
14146 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14147 ((stringp org-agenda-files) (org-read-agenda-file-list))
14148 ((listp org-agenda-files) org-agenda-files)
14149 (t (error "Invalid value of `org-agenda-files'")))))
14150 (setq files (apply 'append
14151 (mapcar (lambda (f)
14152 (if (file-directory-p f)
14153 (directory-files
14154 f t org-agenda-file-regexp)
14155 (list f)))
14156 files)))
14157 (when org-agenda-skip-unavailable-files
14158 (setq files (delq nil
14159 (mapcar (function
14160 (lambda (file)
14161 (and (file-readable-p file) file)))
14162 files))))
14163 (when (or (eq archives t)
14164 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14165 (setq files (org-add-archive-files files)))
14166 files))
14168 (defun org-edit-agenda-file-list ()
14169 "Edit the list of agenda files.
14170 Depending on setup, this either uses customize to edit the variable
14171 `org-agenda-files', or it visits the file that is holding the list. In the
14172 latter case, the buffer is set up in a way that saving it automatically kills
14173 the buffer and restores the previous window configuration."
14174 (interactive)
14175 (if (stringp org-agenda-files)
14176 (let ((cw (current-window-configuration)))
14177 (find-file org-agenda-files)
14178 (org-set-local 'org-window-configuration cw)
14179 (org-add-hook 'after-save-hook
14180 (lambda ()
14181 (set-window-configuration
14182 (prog1 org-window-configuration
14183 (kill-buffer (current-buffer))))
14184 (org-install-agenda-files-menu)
14185 (message "New agenda file list installed"))
14186 nil 'local)
14187 (message "%s" (substitute-command-keys
14188 "Edit list and finish with \\[save-buffer]")))
14189 (customize-variable 'org-agenda-files)))
14191 (defun org-store-new-agenda-file-list (list)
14192 "Set new value for the agenda file list and save it correctly."
14193 (if (stringp org-agenda-files)
14194 (let ((f org-agenda-files) b)
14195 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14196 (with-temp-file f
14197 (insert (mapconcat 'identity list "\n") "\n")))
14198 (let ((org-mode-hook nil) (org-inhibit-startup t)
14199 (org-insert-mode-line-in-empty-file nil))
14200 (setq org-agenda-files list)
14201 (customize-save-variable 'org-agenda-files org-agenda-files))))
14203 (defun org-read-agenda-file-list ()
14204 "Read the list of agenda files from a file."
14205 (when (file-directory-p org-agenda-files)
14206 (error "`org-agenda-files' cannot be a single directory"))
14207 (when (stringp org-agenda-files)
14208 (with-temp-buffer
14209 (insert-file-contents org-agenda-files)
14210 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14213 ;;;###autoload
14214 (defun org-cycle-agenda-files ()
14215 "Cycle through the files in `org-agenda-files'.
14216 If the current buffer visits an agenda file, find the next one in the list.
14217 If the current buffer does not, find the first agenda file."
14218 (interactive)
14219 (let* ((fs (org-agenda-files t))
14220 (files (append fs (list (car fs))))
14221 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14222 file)
14223 (unless files (error "No agenda files"))
14224 (catch 'exit
14225 (while (setq file (pop files))
14226 (if (equal (file-truename file) tcf)
14227 (when (car files)
14228 (find-file (car files))
14229 (throw 'exit t))))
14230 (find-file (car fs)))
14231 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14233 (defun org-agenda-file-to-front (&optional to-end)
14234 "Move/add the current file to the top of the agenda file list.
14235 If the file is not present in the list, it is added to the front. If it is
14236 present, it is moved there. With optional argument TO-END, add/move to the
14237 end of the list."
14238 (interactive "P")
14239 (let ((org-agenda-skip-unavailable-files nil)
14240 (file-alist (mapcar (lambda (x)
14241 (cons (file-truename x) x))
14242 (org-agenda-files t)))
14243 (ctf (file-truename buffer-file-name))
14244 x had)
14245 (setq x (assoc ctf file-alist) had x)
14247 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14248 (if to-end
14249 (setq file-alist (append (delq x file-alist) (list x)))
14250 (setq file-alist (cons x (delq x file-alist))))
14251 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14252 (org-install-agenda-files-menu)
14253 (message "File %s to %s of agenda file list"
14254 (if had "moved" "added") (if to-end "end" "front"))))
14256 (defun org-remove-file (&optional file)
14257 "Remove current file from the list of files in variable `org-agenda-files'.
14258 These are the files which are being checked for agenda entries.
14259 Optional argument FILE means, use this file instead of the current."
14260 (interactive)
14261 (let* ((org-agenda-skip-unavailable-files nil)
14262 (file (or file buffer-file-name))
14263 (true-file (file-truename file))
14264 (afile (abbreviate-file-name file))
14265 (files (delq nil (mapcar
14266 (lambda (x)
14267 (if (equal true-file
14268 (file-truename x))
14269 nil x))
14270 (org-agenda-files t)))))
14271 (if (not (= (length files) (length (org-agenda-files t))))
14272 (progn
14273 (org-store-new-agenda-file-list files)
14274 (org-install-agenda-files-menu)
14275 (message "Removed file: %s" afile))
14276 (message "File was not in list: %s (not removed)" afile))))
14278 (defun org-file-menu-entry (file)
14279 (vector file (list 'find-file file) t))
14281 (defun org-check-agenda-file (file)
14282 "Make sure FILE exists. If not, ask user what to do."
14283 (when (not (file-exists-p file))
14284 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14285 (abbreviate-file-name file))
14286 (let ((r (downcase (read-char-exclusive))))
14287 (cond
14288 ((equal r ?r)
14289 (org-remove-file file)
14290 (throw 'nextfile t))
14291 (t (error "Abort"))))))
14293 (defun org-get-agenda-file-buffer (file)
14294 "Get a buffer visiting FILE. If the buffer needs to be created, add
14295 it to the list of buffers which might be released later."
14296 (let ((buf (org-find-base-buffer-visiting file)))
14297 (if buf
14298 buf ; just return it
14299 ;; Make a new buffer and remember it
14300 (setq buf (find-file-noselect file))
14301 (if buf (push buf org-agenda-new-buffers))
14302 buf)))
14304 (defun org-release-buffers (blist)
14305 "Release all buffers in list, asking the user for confirmation when needed.
14306 When a buffer is unmodified, it is just killed. When modified, it is saved
14307 \(if the user agrees) and then killed."
14308 (let (buf file)
14309 (while (setq buf (pop blist))
14310 (setq file (buffer-file-name buf))
14311 (when (and (buffer-modified-p buf)
14312 file
14313 (y-or-n-p (format "Save file %s? " file)))
14314 (with-current-buffer buf (save-buffer)))
14315 (kill-buffer buf))))
14317 (defun org-prepare-agenda-buffers (files)
14318 "Create buffers for all agenda files, protect archived trees and comments."
14319 (interactive)
14320 (let ((pa '(:org-archived t))
14321 (pc '(:org-comment t))
14322 (pall '(:org-archived t :org-comment t))
14323 (inhibit-read-only t)
14324 (rea (concat ":" org-archive-tag ":"))
14325 bmp file re)
14326 (save-excursion
14327 (save-restriction
14328 (while (setq file (pop files))
14329 (catch 'nextfile
14330 (if (bufferp file)
14331 (set-buffer file)
14332 (org-check-agenda-file file)
14333 (set-buffer (org-get-agenda-file-buffer file)))
14334 (widen)
14335 (setq bmp (buffer-modified-p))
14336 (org-refresh-category-properties)
14337 (setq org-todo-keywords-for-agenda
14338 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14339 (setq org-done-keywords-for-agenda
14340 (append org-done-keywords-for-agenda org-done-keywords))
14341 (setq org-todo-keyword-alist-for-agenda
14342 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14343 (setq org-drawers-for-agenda
14344 (append org-drawers-for-agenda org-drawers))
14345 (setq org-tag-alist-for-agenda
14346 (append org-tag-alist-for-agenda org-tag-alist))
14348 (save-excursion
14349 (remove-text-properties (point-min) (point-max) pall)
14350 (when org-agenda-skip-archived-trees
14351 (goto-char (point-min))
14352 (while (re-search-forward rea nil t)
14353 (if (org-on-heading-p t)
14354 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14355 (goto-char (point-min))
14356 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14357 (while (re-search-forward re nil t)
14358 (add-text-properties
14359 (match-beginning 0) (org-end-of-subtree t) pc)))
14360 (set-buffer-modified-p bmp)))))
14361 (setq org-todo-keyword-alist-for-agenda
14362 (org-uniquify org-todo-keyword-alist-for-agenda)
14363 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14365 ;;;; Embedded LaTeX
14367 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14368 "Keymap for the minor `org-cdlatex-mode'.")
14370 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14371 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14372 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14373 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14374 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14376 (defvar org-cdlatex-texmathp-advice-is-done nil
14377 "Flag remembering if we have applied the advice to texmathp already.")
14379 (define-minor-mode org-cdlatex-mode
14380 "Toggle the minor `org-cdlatex-mode'.
14381 This mode supports entering LaTeX environment and math in LaTeX fragments
14382 in Org-mode.
14383 \\{org-cdlatex-mode-map}"
14384 nil " OCDL" nil
14385 (when org-cdlatex-mode (require 'cdlatex))
14386 (unless org-cdlatex-texmathp-advice-is-done
14387 (setq org-cdlatex-texmathp-advice-is-done t)
14388 (defadvice texmathp (around org-math-always-on activate)
14389 "Always return t in org-mode buffers.
14390 This is because we want to insert math symbols without dollars even outside
14391 the LaTeX math segments. If Orgmode thinks that point is actually inside
14392 an embedded LaTeX fragment, let texmathp do its job.
14393 \\[org-cdlatex-mode-map]"
14394 (interactive)
14395 (let (p)
14396 (cond
14397 ((not (org-mode-p)) ad-do-it)
14398 ((eq this-command 'cdlatex-math-symbol)
14399 (setq ad-return-value t
14400 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14402 (let ((p (org-inside-LaTeX-fragment-p)))
14403 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14404 (setq ad-return-value t
14405 texmathp-why '("Org-mode embedded math" . 0))
14406 (if p ad-do-it)))))))))
14408 (defun turn-on-org-cdlatex ()
14409 "Unconditionally turn on `org-cdlatex-mode'."
14410 (org-cdlatex-mode 1))
14412 (defun org-inside-LaTeX-fragment-p ()
14413 "Test if point is inside a LaTeX fragment.
14414 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14415 sequence appearing also before point.
14416 Even though the matchers for math are configurable, this function assumes
14417 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14418 delimiters are skipped when they have been removed by customization.
14419 The return value is nil, or a cons cell with the delimiter and
14420 and the position of this delimiter.
14422 This function does a reasonably good job, but can locally be fooled by
14423 for example currency specifications. For example it will assume being in
14424 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14425 fragments that are properly closed, but during editing, we have to live
14426 with the uncertainty caused by missing closing delimiters. This function
14427 looks only before point, not after."
14428 (catch 'exit
14429 (let ((pos (point))
14430 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14431 (lim (progn
14432 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14433 (point)))
14434 dd-on str (start 0) m re)
14435 (goto-char pos)
14436 (when dodollar
14437 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14438 re (nth 1 (assoc "$" org-latex-regexps)))
14439 (while (string-match re str start)
14440 (cond
14441 ((= (match-end 0) (length str))
14442 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14443 ((= (match-end 0) (- (length str) 5))
14444 (throw 'exit nil))
14445 (t (setq start (match-end 0))))))
14446 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14447 (goto-char pos)
14448 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14449 (and (match-beginning 2) (throw 'exit nil))
14450 ;; count $$
14451 (while (re-search-backward "\\$\\$" lim t)
14452 (setq dd-on (not dd-on)))
14453 (goto-char pos)
14454 (if dd-on (cons "$$" m))))))
14457 (defun org-try-cdlatex-tab ()
14458 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14459 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14460 - inside a LaTeX fragment, or
14461 - after the first word in a line, where an abbreviation expansion could
14462 insert a LaTeX environment."
14463 (when org-cdlatex-mode
14464 (cond
14465 ((save-excursion
14466 (skip-chars-backward "a-zA-Z0-9*")
14467 (skip-chars-backward " \t")
14468 (bolp))
14469 (cdlatex-tab) t)
14470 ((org-inside-LaTeX-fragment-p)
14471 (cdlatex-tab) t)
14472 (t nil))))
14474 (defun org-cdlatex-underscore-caret (&optional arg)
14475 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14476 Revert to the normal definition outside of these fragments."
14477 (interactive "P")
14478 (if (org-inside-LaTeX-fragment-p)
14479 (call-interactively 'cdlatex-sub-superscript)
14480 (let (org-cdlatex-mode)
14481 (call-interactively (key-binding (vector last-input-event))))))
14483 (defun org-cdlatex-math-modify (&optional arg)
14484 "Execute `cdlatex-math-modify' in LaTeX fragments.
14485 Revert to the normal definition outside of these fragments."
14486 (interactive "P")
14487 (if (org-inside-LaTeX-fragment-p)
14488 (call-interactively 'cdlatex-math-modify)
14489 (let (org-cdlatex-mode)
14490 (call-interactively (key-binding (vector last-input-event))))))
14492 (defvar org-latex-fragment-image-overlays nil
14493 "List of overlays carrying the images of latex fragments.")
14494 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14496 (defun org-remove-latex-fragment-image-overlays ()
14497 "Remove all overlays with LaTeX fragment images in current buffer."
14498 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14499 (setq org-latex-fragment-image-overlays nil))
14501 (defun org-preview-latex-fragment (&optional subtree)
14502 "Preview the LaTeX fragment at point, or all locally or globally.
14503 If the cursor is in a LaTeX fragment, create the image and overlay
14504 it over the source code. If there is no fragment at point, display
14505 all fragments in the current text, from one headline to the next. With
14506 prefix SUBTREE, display all fragments in the current subtree. With a
14507 double prefix `C-u C-u', or when the cursor is before the first headline,
14508 display all fragments in the buffer.
14509 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14510 (interactive "P")
14511 (org-remove-latex-fragment-image-overlays)
14512 (save-excursion
14513 (save-restriction
14514 (let (beg end at msg)
14515 (cond
14516 ((or (equal subtree '(16))
14517 (not (save-excursion
14518 (re-search-backward (concat "^" outline-regexp) nil t))))
14519 (setq beg (point-min) end (point-max)
14520 msg "Creating images for buffer...%s"))
14521 ((equal subtree '(4))
14522 (org-back-to-heading)
14523 (setq beg (point) end (org-end-of-subtree t)
14524 msg "Creating images for subtree...%s"))
14526 (if (setq at (org-inside-LaTeX-fragment-p))
14527 (goto-char (max (point-min) (- (cdr at) 2)))
14528 (org-back-to-heading))
14529 (setq beg (point) end (progn (outline-next-heading) (point))
14530 msg (if at "Creating image...%s"
14531 "Creating images for entry...%s"))))
14532 (message msg "")
14533 (narrow-to-region beg end)
14534 (goto-char beg)
14535 (org-format-latex
14536 (concat "ltxpng/" (file-name-sans-extension
14537 (file-name-nondirectory
14538 buffer-file-name)))
14539 default-directory 'overlays msg at 'forbuffer)
14540 (message msg "done. Use `C-c C-c' to remove images.")))))
14542 (defvar org-latex-regexps
14543 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14544 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14545 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14546 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14547 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14548 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14549 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14550 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14551 "Regular expressions for matching embedded LaTeX.")
14553 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14554 "Replace LaTeX fragments with links to an image, and produce images.
14555 Some of the options can be changed using the variable
14556 `org-format-latex-options'."
14557 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14558 (let* ((prefixnodir (file-name-nondirectory prefix))
14559 (absprefix (expand-file-name prefix dir))
14560 (todir (file-name-directory absprefix))
14561 (opt org-format-latex-options)
14562 (matchers (plist-get opt :matchers))
14563 (re-list org-latex-regexps)
14564 (cnt 0) txt hash link beg end re e checkdir
14565 executables-checked
14566 m n block linkfile movefile ov)
14567 ;; Check the different regular expressions
14568 (while (setq e (pop re-list))
14569 (setq m (car e) re (nth 1 e) n (nth 2 e)
14570 block (if (nth 3 e) "\n\n" ""))
14571 (when (member m matchers)
14572 (goto-char (point-min))
14573 (while (re-search-forward re nil t)
14574 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14575 (not (get-text-property (match-beginning n)
14576 'org-protected))
14577 (or (not overlays)
14578 (not (eq (get-char-property (match-beginning n)
14579 'org-overlay-type)
14580 'org-latex-overlay))))
14581 (setq txt (match-string n)
14582 beg (match-beginning n) end (match-end n)
14583 cnt (1+ cnt)
14584 link (concat block "[[file:" linkfile "]]" block))
14585 (let (print-length print-level) ; make sure full list is printed
14586 (setq hash (sha1 (prin1-to-string
14587 (list org-format-latex-header
14588 org-export-latex-packages-alist
14589 org-format-latex-options
14590 forbuffer txt)))
14591 linkfile (format "%s_%s.png" prefix hash)
14592 movefile (format "%s_%s.png" absprefix hash)))
14593 (if msg (message msg cnt))
14594 (goto-char beg)
14595 (unless checkdir ; make sure the directory exists
14596 (setq checkdir t)
14597 (or (file-directory-p todir) (make-directory todir)))
14599 (unless executables-checked
14600 (org-check-external-command
14601 "latex" "needed to convert LaTeX fragments to images")
14602 (org-check-external-command
14603 "dvipng" "needed to convert LaTeX fragments to images")
14604 (setq executables-checked t))
14606 (unless (file-exists-p movefile)
14607 (org-create-formula-image
14608 txt movefile opt forbuffer))
14609 (if overlays
14610 (progn
14611 (mapc (lambda (o)
14612 (if (eq (org-overlay-get o 'org-overlay-type)
14613 'org-latex-overlay)
14614 (org-delete-overlay o)))
14615 (org-overlays-in beg end))
14616 (setq ov (org-make-overlay beg end))
14617 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14618 (if (featurep 'xemacs)
14619 (progn
14620 (org-overlay-put ov 'invisible t)
14621 (org-overlay-put
14622 ov 'end-glyph
14623 (make-glyph (vector 'png :file movefile))))
14624 (org-overlay-put
14625 ov 'display
14626 (list 'image :type 'png :file movefile :ascent 'center)))
14627 (push ov org-latex-fragment-image-overlays)
14628 (goto-char end))
14629 (delete-region beg end)
14630 (insert link))))))))
14632 ;; This function borrows from Ganesh Swami's latex2png.el
14633 (defun org-create-formula-image (string tofile options buffer)
14634 "This calls dvipng."
14635 (require 'org-latex)
14636 (let* ((tmpdir (if (featurep 'xemacs)
14637 (temp-directory)
14638 temporary-file-directory))
14639 (texfilebase (make-temp-name
14640 (expand-file-name "orgtex" tmpdir)))
14641 (texfile (concat texfilebase ".tex"))
14642 (dvifile (concat texfilebase ".dvi"))
14643 (pngfile (concat texfilebase ".png"))
14644 (fnh (if (featurep 'xemacs)
14645 (font-height (get-face-font 'default))
14646 (face-attribute 'default :height nil)))
14647 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14648 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14649 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14650 "Black"))
14651 (bg (or (plist-get options (if buffer :background :html-background))
14652 "Transparent")))
14653 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14654 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14655 (with-temp-file texfile
14656 (insert org-format-latex-header
14657 (if org-export-latex-packages-alist
14658 (concat "\n"
14659 (mapconcat (lambda(p)
14660 (if (equal "" (car p))
14661 (format "\\usepackage{%s}" (cadr p))
14662 (format "\\usepackage[%s]{%s}"
14663 (car p) (cadr p))))
14664 org-export-latex-packages-alist "\n"))
14666 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14667 (let ((dir default-directory))
14668 (condition-case nil
14669 (progn
14670 (cd tmpdir)
14671 (call-process "latex" nil nil nil texfile))
14672 (error nil))
14673 (cd dir))
14674 (if (not (file-exists-p dvifile))
14675 (progn (message "Failed to create dvi file from %s" texfile) nil)
14676 (condition-case nil
14677 (call-process "dvipng" nil nil nil
14678 "-fg" fg "-bg" bg
14679 "-D" dpi
14680 ;;"-x" scale "-y" scale
14681 "-T" "tight"
14682 "-o" pngfile
14683 dvifile)
14684 (error nil))
14685 (if (not (file-exists-p pngfile))
14686 (progn (message "Failed to create png file from %s" texfile) nil)
14687 ;; Use the requested file name and clean up
14688 (copy-file pngfile tofile 'replace)
14689 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14690 (delete-file (concat texfilebase e)))
14691 pngfile))))
14693 (defun org-dvipng-color (attr)
14694 "Return an rgb color specification for dvipng."
14695 (apply 'format "rgb %s %s %s"
14696 (mapcar 'org-normalize-color
14697 (color-values (face-attribute 'default attr nil)))))
14699 (defun org-normalize-color (value)
14700 "Return string to be used as color value for an RGB component."
14701 (format "%g" (/ value 65535.0)))
14703 ;;;; Key bindings
14705 ;; Make `C-c C-x' a prefix key
14706 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14708 ;; TAB key with modifiers
14709 (org-defkey org-mode-map "\C-i" 'org-cycle)
14710 (org-defkey org-mode-map [(tab)] 'org-cycle)
14711 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14712 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14713 (org-defkey org-mode-map "\M-\t" 'org-complete)
14714 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14715 ;; The following line is necessary under Suse GNU/Linux
14716 (unless (featurep 'xemacs)
14717 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14718 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14719 (define-key org-mode-map [backtab] 'org-shifttab)
14721 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14722 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14723 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14725 ;; Cursor keys with modifiers
14726 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14727 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14728 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14729 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14731 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14732 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14733 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14734 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14736 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14737 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14738 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14739 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14741 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14742 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14744 ;;; Extra keys for tty access.
14745 ;; We only set them when really needed because otherwise the
14746 ;; menus don't show the simple keys
14748 (when (or org-use-extra-keys
14749 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14750 (not window-system))
14751 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14752 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14753 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14754 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14755 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14756 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14757 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14758 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14759 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14760 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14761 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14762 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14763 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14764 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14765 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14766 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14767 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14768 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14769 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14770 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14771 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14772 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14773 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14774 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14775 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14776 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14777 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14778 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14780 ;; All the other keys
14782 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14783 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14784 (if (boundp 'narrow-map)
14785 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14786 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14787 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14788 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14789 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14790 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14791 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
14792 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14793 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14794 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14795 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14796 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14797 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14798 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14799 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14800 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14801 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14802 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14803 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14804 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14805 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14806 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14807 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14808 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14809 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14810 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14811 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14812 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14813 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14814 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14815 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14816 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14817 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14818 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14819 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14820 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14821 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14822 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14823 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14824 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14825 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14826 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14827 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14828 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14829 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14830 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14831 (org-defkey org-mode-map "\C-c^" 'org-sort)
14832 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14833 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14834 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
14835 (org-defkey org-mode-map "\C-m" 'org-return)
14836 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14837 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14838 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14839 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14840 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14841 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14842 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14843 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14844 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14845 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14846 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14847 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14848 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14849 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14850 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14851 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14852 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14853 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
14854 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
14855 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14856 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14858 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14859 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14860 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14861 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14863 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14864 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14865 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14866 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14867 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14868 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14869 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14870 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14871 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14872 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14873 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14874 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
14875 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14876 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14877 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14879 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14880 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14881 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14882 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14884 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14886 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14888 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14889 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14891 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14894 (when (featurep 'xemacs)
14895 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14898 (defconst org-speed-commands-default
14900 ("Outline Navigation")
14901 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
14902 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
14903 ("f" . (org-speed-move-safe 'org-forward-same-level))
14904 ("b" . (org-speed-move-safe 'org-backward-same-level))
14905 ("u" . (org-speed-move-safe 'outline-up-heading))
14906 ("j" . org-goto)
14907 ("g" . (org-refile t))
14908 ("Outline Visibility")
14909 ("c" . org-cycle)
14910 ("C" . org-shifttab)
14911 (" " . org-display-outline-path)
14912 ("Outline Structure Editing")
14913 ("U" . org-shiftmetaup)
14914 ("D" . org-shiftmetadown)
14915 ("r" . org-metaright)
14916 ("l" . org-metaleft)
14917 ("R" . org-shiftmetaright)
14918 ("L" . org-shiftmetaleft)
14919 ("i" . (progn (forward-char 1) (call-interactively
14920 'org-insert-heading-respect-content)))
14921 ("^" . org-sort)
14922 ("w" . org-refile)
14923 ("a" . org-archive-subtree-default-with-confirmation)
14924 ("." . outline-mark-subtree)
14925 ("Clock Commands")
14926 ("I" . org-clock-in)
14927 ("O" . org-clock-out)
14928 ("Meta Data Editing")
14929 ("t" . org-todo)
14930 ("0" . (org-priority ?\ ))
14931 ("1" . (org-priority ?A))
14932 ("2" . (org-priority ?B))
14933 ("3" . (org-priority ?C))
14934 (";" . org-set-tags-command)
14935 ("e" . org-set-effort)
14936 ("Agenda Views etc")
14937 ("v" . org-agenda)
14938 ("/" . org-sparse-tree)
14939 ("/" . org-sparse-tree)
14940 ("Misc")
14941 ("o" . org-open-at-point)
14942 ("?" . org-speed-command-help)
14944 "The default speed commands.")
14946 (defun org-print-speed-command (e)
14947 (if (> (length (car e)) 1)
14948 (progn
14949 (princ "\n")
14950 (princ (car e))
14951 (princ "\n")
14952 (princ (make-string (length (car e)) ?-))
14953 (princ "\n"))
14954 (princ (car e))
14955 (princ " ")
14956 (if (symbolp (cdr e))
14957 (princ (symbol-name (cdr e)))
14958 (prin1 (cdr e)))
14959 (princ "\n")))
14961 (defun org-speed-command-help ()
14962 "Show the available speed commands."
14963 (interactive)
14964 (if (not org-use-speed-commands)
14965 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
14966 (with-output-to-temp-buffer "*Help*"
14967 (princ "User-defined Speed commands\n===========================\n")
14968 (mapc 'org-print-speed-command org-speed-commands-user)
14969 (princ "\n")
14970 (princ "Built-in Speed commands\n=======================\n")
14971 (mapc 'org-print-speed-command org-speed-commands-default))
14972 (with-current-buffer "*Help*"
14973 (setq truncate-lines t))))
14975 (defun org-speed-move-safe (cmd)
14976 "Execute CMD, but make sure that the cursor always ends up in a headline.
14977 If not, return to the original position and throw an error."
14978 (interactive)
14979 (let ((pos (point)))
14980 (call-interactively cmd)
14981 (unless (and (bolp) (org-on-heading-p))
14982 (goto-char pos)
14983 (error "Boundary reached while executing %s" cmd))))
14985 (defvar org-self-insert-command-undo-counter 0)
14987 (defvar org-table-auto-blank-field) ; defined in org-table.el
14988 (defvar org-speed-command nil)
14989 (defun org-self-insert-command (N)
14990 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14991 If the cursor is in a table looking at whitespace, the whitespace is
14992 overwritten, and the table is not marked as requiring realignment."
14993 (interactive "p")
14994 (cond
14995 ((and org-use-speed-commands
14996 (or (and (bolp) (looking-at outline-regexp))
14997 (and (functionp org-use-speed-commands)
14998 (funcall org-use-speed-commands)))
14999 (setq
15000 org-speed-command
15001 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15002 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15003 (cond
15004 ((commandp org-speed-command)
15005 (setq this-command org-speed-command)
15006 (call-interactively org-speed-command))
15007 ((functionp org-speed-command)
15008 (funcall org-speed-command))
15009 ((and org-speed-command (listp org-speed-command))
15010 (eval org-speed-command))
15011 (t (let (org-use-speed-commands)
15012 (call-interactively 'org-self-insert-command)))))
15013 ((and
15014 (org-table-p)
15015 (progn
15016 ;; check if we blank the field, and if that triggers align
15017 (and (featurep 'org-table) org-table-auto-blank-field
15018 (member last-command
15019 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15020 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15021 ;; got extra space, this field does not determine column width
15022 (let (org-table-may-need-update) (org-table-blank-field))
15023 ;; no extra space, this field may determine column width
15024 (org-table-blank-field)))
15026 (eq N 1)
15027 (looking-at "[^|\n]* |"))
15028 (let (org-table-may-need-update)
15029 (goto-char (1- (match-end 0)))
15030 (delete-backward-char 1)
15031 (goto-char (match-beginning 0))
15032 (self-insert-command N)))
15034 (setq org-table-may-need-update t)
15035 (self-insert-command N)
15036 (org-fix-tags-on-the-fly)
15037 (if org-self-insert-cluster-for-undo
15038 (if (not (eq last-command 'org-self-insert-command))
15039 (setq org-self-insert-command-undo-counter 1)
15040 (if (>= org-self-insert-command-undo-counter 20)
15041 (setq org-self-insert-command-undo-counter 1)
15042 (and (> org-self-insert-command-undo-counter 0)
15043 buffer-undo-list
15044 (not (cadr buffer-undo-list)) ; remove nil entry
15045 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15046 (setq org-self-insert-command-undo-counter
15047 (1+ org-self-insert-command-undo-counter))))))))
15049 (defun org-fix-tags-on-the-fly ()
15050 (when (and (equal (char-after (point-at-bol)) ?*)
15051 (org-on-heading-p))
15052 (org-align-tags-here org-tags-column)))
15054 (defun org-delete-backward-char (N)
15055 "Like `delete-backward-char', insert whitespace at field end in tables.
15056 When deleting backwards, in tables this function will insert whitespace in
15057 front of the next \"|\" separator, to keep the table aligned. The table will
15058 still be marked for re-alignment if the field did fill the entire column,
15059 because, in this case the deletion might narrow the column."
15060 (interactive "p")
15061 (if (and (org-table-p)
15062 (eq N 1)
15063 (string-match "|" (buffer-substring (point-at-bol) (point)))
15064 (looking-at ".*?|"))
15065 (let ((pos (point))
15066 (noalign (looking-at "[^|\n\r]* |"))
15067 (c org-table-may-need-update))
15068 (backward-delete-char N)
15069 (skip-chars-forward "^|")
15070 (insert " ")
15071 (goto-char (1- pos))
15072 ;; noalign: if there were two spaces at the end, this field
15073 ;; does not determine the width of the column.
15074 (if noalign (setq org-table-may-need-update c)))
15075 (backward-delete-char N)
15076 (org-fix-tags-on-the-fly)))
15078 (defun org-delete-char (N)
15079 "Like `delete-char', but insert whitespace at field end in tables.
15080 When deleting characters, in tables this function will insert whitespace in
15081 front of the next \"|\" separator, to keep the table aligned. The table will
15082 still be marked for re-alignment if the field did fill the entire column,
15083 because, in this case the deletion might narrow the column."
15084 (interactive "p")
15085 (if (and (org-table-p)
15086 (not (bolp))
15087 (not (= (char-after) ?|))
15088 (eq N 1))
15089 (if (looking-at ".*?|")
15090 (let ((pos (point))
15091 (noalign (looking-at "[^|\n\r]* |"))
15092 (c org-table-may-need-update))
15093 (replace-match (concat
15094 (substring (match-string 0) 1 -1)
15095 " |"))
15096 (goto-char pos)
15097 ;; noalign: if there were two spaces at the end, this field
15098 ;; does not determine the width of the column.
15099 (if noalign (setq org-table-may-need-update c)))
15100 (delete-char N))
15101 (delete-char N)
15102 (org-fix-tags-on-the-fly)))
15104 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15105 (put 'org-self-insert-command 'delete-selection t)
15106 (put 'orgtbl-self-insert-command 'delete-selection t)
15107 (put 'org-delete-char 'delete-selection 'supersede)
15108 (put 'org-delete-backward-char 'delete-selection 'supersede)
15109 (put 'org-yank 'delete-selection 'yank)
15111 ;; Make `flyspell-mode' delay after some commands
15112 (put 'org-self-insert-command 'flyspell-delayed t)
15113 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15114 (put 'org-delete-char 'flyspell-delayed t)
15115 (put 'org-delete-backward-char 'flyspell-delayed t)
15117 ;; Make pabbrev-mode expand after org-mode commands
15118 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15119 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15121 ;; How to do this: Measure non-white length of current string
15122 ;; If equal to column width, we should realign.
15124 (defun org-remap (map &rest commands)
15125 "In MAP, remap the functions given in COMMANDS.
15126 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15127 (let (new old)
15128 (while commands
15129 (setq old (pop commands) new (pop commands))
15130 (if (fboundp 'command-remapping)
15131 (org-defkey map (vector 'remap old) new)
15132 (substitute-key-definition old new map global-map)))))
15134 (when (eq org-enable-table-editor 'optimized)
15135 ;; If the user wants maximum table support, we need to hijack
15136 ;; some standard editing functions
15137 (org-remap org-mode-map
15138 'self-insert-command 'org-self-insert-command
15139 'delete-char 'org-delete-char
15140 'delete-backward-char 'org-delete-backward-char)
15141 (org-defkey org-mode-map "|" 'org-force-self-insert))
15143 (defvar org-ctrl-c-ctrl-c-hook nil
15144 "Hook for functions attaching themselves to `C-c C-c'.
15145 This can be used to add additional functionality to the C-c C-c key which
15146 executes context-dependent commands.
15147 Each function will be called with no arguments. The function must check
15148 if the context is appropriate for it to act. If yes, it should do its
15149 thing and then return a non-nil value. If the context is wrong,
15150 just do nothing and return nil.")
15152 (defvar org-tab-first-hook nil
15153 "Hook for functions to attach themselves to TAB.
15154 See `org-ctrl-c-ctrl-c-hook' for more information.
15155 This hook runs as the first action when TAB is pressed, even before
15156 `org-cycle' messes around with the `outline-regexp' to cater for
15157 inline tasks and plain list item folding.
15158 If any function in this hook returns t, not other actions like table
15159 field motion visibility cycling will be done.")
15161 (defvar org-tab-after-check-for-table-hook nil
15162 "Hook for functions to attach themselves to TAB.
15163 See `org-ctrl-c-ctrl-c-hook' for more information.
15164 This hook runs after it has been established that the cursor is not in a
15165 table, but before checking if the cursor is in a headline or if global cycling
15166 should be done.
15167 If any function in this hook returns t, not other actions like visibility
15168 cycling will be done.")
15170 (defvar org-tab-after-check-for-cycling-hook nil
15171 "Hook for functions to attach themselves to TAB.
15172 See `org-ctrl-c-ctrl-c-hook' for more information.
15173 This hook runs after it has been established that not table field motion and
15174 not visibility should be done because of current context. This is probably
15175 the place where a package like yasnippets can hook in.")
15177 (defvar org-tab-before-tab-emulation-hook nil
15178 "Hook for functions to attach themselves to TAB.
15179 See `org-ctrl-c-ctrl-c-hook' for more information.
15180 This hook runs after every other options for TAB have been exhausted, but
15181 before indentation and \t insertion takes place.")
15183 (defvar org-metaleft-hook nil
15184 "Hook for functions attaching themselves to `M-left'.
15185 See `org-ctrl-c-ctrl-c-hook' for more information.")
15186 (defvar org-metaright-hook nil
15187 "Hook for functions attaching themselves to `M-right'.
15188 See `org-ctrl-c-ctrl-c-hook' for more information.")
15189 (defvar org-metaup-hook nil
15190 "Hook for functions attaching themselves to `M-up'.
15191 See `org-ctrl-c-ctrl-c-hook' for more information.")
15192 (defvar org-metadown-hook nil
15193 "Hook for functions attaching themselves to `M-down'.
15194 See `org-ctrl-c-ctrl-c-hook' for more information.")
15195 (defvar org-shiftmetaleft-hook nil
15196 "Hook for functions attaching themselves to `M-S-left'.
15197 See `org-ctrl-c-ctrl-c-hook' for more information.")
15198 (defvar org-shiftmetaright-hook nil
15199 "Hook for functions attaching themselves to `M-S-right'.
15200 See `org-ctrl-c-ctrl-c-hook' for more information.")
15201 (defvar org-shiftmetaup-hook nil
15202 "Hook for functions attaching themselves to `M-S-up'.
15203 See `org-ctrl-c-ctrl-c-hook' for more information.")
15204 (defvar org-shiftmetadown-hook nil
15205 "Hook for functions attaching themselves to `M-S-down'.
15206 See `org-ctrl-c-ctrl-c-hook' for more information.")
15207 (defvar org-metareturn-hook nil
15208 "Hook for functions attaching themselves to `M-RET'.
15209 See `org-ctrl-c-ctrl-c-hook' for more information.")
15211 (defun org-modifier-cursor-error ()
15212 "Throw an error, a modified cursor command was applied in wrong context."
15213 (error "This command is active in special context like tables, headlines or items"))
15215 (defun org-shiftselect-error ()
15216 "Throw an error because Shift-Cursor command was applied in wrong context."
15217 (if (and (boundp 'shift-select-mode) shift-select-mode)
15218 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15219 (error "This command works only in special context like headlines or timestamps")))
15221 (defun org-call-for-shift-select (cmd)
15222 (let ((this-command-keys-shift-translated t))
15223 (call-interactively cmd)))
15225 (defun org-shifttab (&optional arg)
15226 "Global visibility cycling or move to previous table field.
15227 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15228 on context.
15229 See the individual commands for more information."
15230 (interactive "P")
15231 (cond
15232 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15233 ((integerp arg)
15234 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15235 (message "Content view to level: %d" arg)
15236 (org-content (prefix-numeric-value arg2))
15237 (setq org-cycle-global-status 'overview)))
15238 (t (call-interactively 'org-global-cycle))))
15240 (defun org-shiftmetaleft ()
15241 "Promote subtree or delete table column.
15242 Calls `org-promote-subtree', `org-outdent-item',
15243 or `org-table-delete-column', depending on context.
15244 See the individual commands for more information."
15245 (interactive)
15246 (cond
15247 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15248 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15249 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15250 ((org-at-item-p) (call-interactively 'org-outdent-item))
15251 (t (org-modifier-cursor-error))))
15253 (defun org-shiftmetaright ()
15254 "Demote subtree or insert table column.
15255 Calls `org-demote-subtree', `org-indent-item',
15256 or `org-table-insert-column', depending on context.
15257 See the individual commands for more information."
15258 (interactive)
15259 (cond
15260 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15261 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15262 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15263 ((org-at-item-p) (call-interactively 'org-indent-item))
15264 (t (org-modifier-cursor-error))))
15266 (defun org-shiftmetaup (&optional arg)
15267 "Move subtree up or kill table row.
15268 Calls `org-move-subtree-up' or `org-table-kill-row' or
15269 `org-move-item-up' depending on context. See the individual commands
15270 for more information."
15271 (interactive "P")
15272 (cond
15273 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15274 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15275 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15276 ((org-at-item-p) (call-interactively 'org-move-item-up))
15277 (t (org-modifier-cursor-error))))
15279 (defun org-shiftmetadown (&optional arg)
15280 "Move subtree down or insert table row.
15281 Calls `org-move-subtree-down' or `org-table-insert-row' or
15282 `org-move-item-down', depending on context. See the individual
15283 commands for more information."
15284 (interactive "P")
15285 (cond
15286 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15287 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15288 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15289 ((org-at-item-p) (call-interactively 'org-move-item-down))
15290 (t (org-modifier-cursor-error))))
15292 (defun org-metaleft (&optional arg)
15293 "Promote heading or move table column to left.
15294 Calls `org-do-promote' or `org-table-move-column', depending on context.
15295 With no specific context, calls the Emacs default `backward-word'.
15296 See the individual commands for more information."
15297 (interactive "P")
15298 (cond
15299 ((run-hook-with-args-until-success 'org-metaleft-hook))
15300 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15301 ((or (org-on-heading-p)
15302 (and (org-region-active-p)
15303 (save-excursion
15304 (goto-char (region-beginning))
15305 (org-on-heading-p))))
15306 (call-interactively 'org-do-promote))
15307 ((or (org-at-item-p)
15308 (and (org-region-active-p)
15309 (save-excursion
15310 (goto-char (region-beginning))
15311 (org-at-item-p))))
15312 (call-interactively 'org-outdent-item))
15313 (t (call-interactively 'backward-word))))
15315 (defun org-metaright (&optional arg)
15316 "Demote subtree or move table column to right.
15317 Calls `org-do-demote' or `org-table-move-column', depending on context.
15318 With no specific context, calls the Emacs default `forward-word'.
15319 See the individual commands for more information."
15320 (interactive "P")
15321 (cond
15322 ((run-hook-with-args-until-success 'org-metaright-hook))
15323 ((org-at-table-p) (call-interactively 'org-table-move-column))
15324 ((or (org-on-heading-p)
15325 (and (org-region-active-p)
15326 (save-excursion
15327 (goto-char (region-beginning))
15328 (org-on-heading-p))))
15329 (call-interactively 'org-do-demote))
15330 ((or (org-at-item-p)
15331 (and (org-region-active-p)
15332 (save-excursion
15333 (goto-char (region-beginning))
15334 (org-at-item-p))))
15335 (call-interactively 'org-indent-item))
15336 (t (call-interactively 'forward-word))))
15338 (defun org-metaup (&optional arg)
15339 "Move subtree up or move table row up.
15340 Calls `org-move-subtree-up' or `org-table-move-row' or
15341 `org-move-item-up', depending on context. See the individual commands
15342 for more information."
15343 (interactive "P")
15344 (cond
15345 ((run-hook-with-args-until-success 'org-metaup-hook))
15346 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15347 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15348 ((org-at-item-p) (call-interactively 'org-move-item-up))
15349 (t (transpose-lines 1) (beginning-of-line -1))))
15351 (defun org-metadown (&optional arg)
15352 "Move subtree down or move table row down.
15353 Calls `org-move-subtree-down' or `org-table-move-row' or
15354 `org-move-item-down', depending on context. See the individual
15355 commands for more information."
15356 (interactive "P")
15357 (cond
15358 ((run-hook-with-args-until-success 'org-metadown-hook))
15359 ((org-at-table-p) (call-interactively 'org-table-move-row))
15360 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15361 ((org-at-item-p) (call-interactively 'org-move-item-down))
15362 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15364 (defun org-shiftup (&optional arg)
15365 "Increase item in timestamp or increase priority of current headline.
15366 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15367 depending on context. See the individual commands for more information."
15368 (interactive "P")
15369 (cond
15370 ((and org-support-shift-select (org-region-active-p))
15371 (org-call-for-shift-select 'previous-line))
15372 ((org-at-timestamp-p t)
15373 (call-interactively (if org-edit-timestamp-down-means-later
15374 'org-timestamp-down 'org-timestamp-up)))
15375 ((and (not (eq org-support-shift-select 'always))
15376 org-enable-priority-commands
15377 (org-on-heading-p))
15378 (call-interactively 'org-priority-up))
15379 ((and (not org-support-shift-select) (org-at-item-p))
15380 (call-interactively 'org-previous-item))
15381 ((org-clocktable-try-shift 'up arg))
15382 (org-support-shift-select
15383 (org-call-for-shift-select 'previous-line))
15384 (t (org-shiftselect-error))))
15386 (defun org-shiftdown (&optional arg)
15387 "Decrease item in timestamp or decrease priority of current headline.
15388 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15389 depending on context. See the individual commands for more information."
15390 (interactive "P")
15391 (cond
15392 ((and org-support-shift-select (org-region-active-p))
15393 (org-call-for-shift-select 'next-line))
15394 ((org-at-timestamp-p t)
15395 (call-interactively (if org-edit-timestamp-down-means-later
15396 'org-timestamp-up 'org-timestamp-down)))
15397 ((and (not (eq org-support-shift-select 'always))
15398 org-enable-priority-commands
15399 (org-on-heading-p))
15400 (call-interactively 'org-priority-down))
15401 ((and (not org-support-shift-select) (org-at-item-p))
15402 (call-interactively 'org-next-item))
15403 ((org-clocktable-try-shift 'down arg))
15404 (org-support-shift-select
15405 (org-call-for-shift-select 'next-line))
15406 (t (org-shiftselect-error))))
15408 (defun org-shiftright (&optional arg)
15409 "Cycle the thing at point or in the current line, depending on context.
15410 Depending on context, this does one of the following:
15412 - switch a timestamp at point one day into the future
15413 - on a headline, switch to the next TODO keyword.
15414 - on an item, switch entire list to the next bullet type
15415 - on a property line, switch to the next allowed value
15416 - on a clocktable definition line, move time block into the future"
15417 (interactive "P")
15418 (cond
15419 ((and org-support-shift-select (org-region-active-p))
15420 (org-call-for-shift-select 'forward-char))
15421 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15422 ((and (not (eq org-support-shift-select 'always))
15423 (org-on-heading-p))
15424 (let ((org-inhibit-logging
15425 (not org-treat-S-cursor-todo-selection-as-state-change))
15426 (org-inhibit-blocking
15427 (not org-treat-S-cursor-todo-selection-as-state-change)))
15428 (org-call-with-arg 'org-todo 'right)))
15429 ((or (and org-support-shift-select
15430 (not (eq org-support-shift-select 'always))
15431 (org-at-item-bullet-p))
15432 (and (not org-support-shift-select) (org-at-item-p)))
15433 (org-call-with-arg 'org-cycle-list-bullet nil))
15434 ((and (not (eq org-support-shift-select 'always))
15435 (org-at-property-p))
15436 (call-interactively 'org-property-next-allowed-value))
15437 ((org-clocktable-try-shift 'right arg))
15438 (org-support-shift-select
15439 (org-call-for-shift-select 'forward-char))
15440 (t (org-shiftselect-error))))
15442 (defun org-shiftleft (&optional arg)
15443 "Cycle the thing at point or in the current line, depending on context.
15444 Depending on context, this does one of the following:
15446 - switch a timestamp at point one day into the past
15447 - on a headline, switch to the previous TODO keyword.
15448 - on an item, switch entire list to the previous bullet type
15449 - on a property line, switch to the previous allowed value
15450 - on a clocktable definition line, move time block into the past"
15451 (interactive "P")
15452 (cond
15453 ((and org-support-shift-select (org-region-active-p))
15454 (org-call-for-shift-select 'backward-char))
15455 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15456 ((and (not (eq org-support-shift-select 'always))
15457 (org-on-heading-p))
15458 (let ((org-inhibit-logging
15459 (not org-treat-S-cursor-todo-selection-as-state-change))
15460 (org-inhibit-blocking
15461 (not org-treat-S-cursor-todo-selection-as-state-change)))
15462 (org-call-with-arg 'org-todo 'left)))
15463 ((or (and org-support-shift-select
15464 (not (eq org-support-shift-select 'always))
15465 (org-at-item-bullet-p))
15466 (and (not org-support-shift-select) (org-at-item-p)))
15467 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15468 ((and (not (eq org-support-shift-select 'always))
15469 (org-at-property-p))
15470 (call-interactively 'org-property-previous-allowed-value))
15471 ((org-clocktable-try-shift 'left arg))
15472 (org-support-shift-select
15473 (org-call-for-shift-select 'backward-char))
15474 (t (org-shiftselect-error))))
15476 (defun org-shiftcontrolright ()
15477 "Switch to next TODO set."
15478 (interactive)
15479 (cond
15480 ((and org-support-shift-select (org-region-active-p))
15481 (org-call-for-shift-select 'forward-word))
15482 ((and (not (eq org-support-shift-select 'always))
15483 (org-on-heading-p))
15484 (org-call-with-arg 'org-todo 'nextset))
15485 (org-support-shift-select
15486 (org-call-for-shift-select 'forward-word))
15487 (t (org-shiftselect-error))))
15489 (defun org-shiftcontrolleft ()
15490 "Switch to previous TODO set."
15491 (interactive)
15492 (cond
15493 ((and org-support-shift-select (org-region-active-p))
15494 (org-call-for-shift-select 'backward-word))
15495 ((and (not (eq org-support-shift-select 'always))
15496 (org-on-heading-p))
15497 (org-call-with-arg 'org-todo 'previousset))
15498 (org-support-shift-select
15499 (org-call-for-shift-select 'backward-word))
15500 (t (org-shiftselect-error))))
15502 (defun org-ctrl-c-ret ()
15503 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15504 (interactive)
15505 (cond
15506 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15507 (t (call-interactively 'org-insert-heading))))
15509 (defun org-copy-special ()
15510 "Copy region in table or copy current subtree.
15511 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15512 See the individual commands for more information."
15513 (interactive)
15514 (call-interactively
15515 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15517 (defun org-cut-special ()
15518 "Cut region in table or cut current subtree.
15519 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15520 See the individual commands for more information."
15521 (interactive)
15522 (call-interactively
15523 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15525 (defun org-paste-special (arg)
15526 "Paste rectangular region into table, or past subtree relative to level.
15527 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15528 See the individual commands for more information."
15529 (interactive "P")
15530 (if (org-at-table-p)
15531 (org-table-paste-rectangle)
15532 (org-paste-subtree arg)))
15534 (defun org-edit-special ()
15535 "Call a special editor for the stuff at point.
15536 When at a table, call the formula editor with `org-table-edit-formulas'.
15537 When at the first line of an src example, call `org-edit-src-code'.
15538 When in an #+include line, visit the include file. Otherwise call
15539 `ffap' to visit the file at point."
15540 (interactive)
15541 (cond
15542 ((org-at-table-p)
15543 (call-interactively 'org-table-edit-formulas))
15544 ((save-excursion
15545 (beginning-of-line 1)
15546 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15547 (find-file (org-trim (match-string 1))))
15548 ((org-edit-src-code))
15549 ((org-edit-fixed-width-region))
15550 (t (call-interactively 'ffap))))
15553 (defun org-ctrl-c-ctrl-c (&optional arg)
15554 "Set tags in headline, or update according to changed information at point.
15556 This command does many different things, depending on context:
15558 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15559 this is what we do.
15561 - If the cursor is on a statistics cookie, update it.
15563 - If the cursor is in a headline, prompt for tags and insert them
15564 into the current line, aligned to `org-tags-column'. When called
15565 with prefix arg, realign all tags in the current buffer.
15567 - If the cursor is in one of the special #+KEYWORD lines, this
15568 triggers scanning the buffer for these lines and updating the
15569 information.
15571 - If the cursor is inside a table, realign the table. This command
15572 works even if the automatic table editor has been turned off.
15574 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15575 the entire table.
15577 - If the cursor is at a footnote reference or definition, jump to
15578 the corresponding definition or references, respectively.
15580 - If the cursor is a the beginning of a dynamic block, update it.
15582 - If the cursor is inside a table created by the table.el package,
15583 activate that table.
15585 - If the current buffer is a remember buffer, close note and file
15586 it. A prefix argument of 1 files to the default location
15587 without further interaction. A prefix argument of 2 files to
15588 the currently clocking task.
15590 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15591 links in this buffer.
15593 - If the cursor is on a numbered item in a plain list, renumber the
15594 ordered list.
15596 - If the cursor is on a checkbox, toggle it."
15597 (interactive "P")
15598 (let ((org-enable-table-editor t))
15599 (cond
15600 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15601 org-occur-highlights
15602 org-latex-fragment-image-overlays)
15603 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15604 (org-remove-occur-highlights)
15605 (org-remove-latex-fragment-image-overlays)
15606 (message "Temporary highlights/overlays removed from current buffer"))
15607 ((and (local-variable-p 'org-finish-function (current-buffer))
15608 (fboundp org-finish-function))
15609 (funcall org-finish-function))
15610 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15611 ((org-at-property-p)
15612 (call-interactively 'org-property-action))
15613 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15614 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15615 (or (org-on-heading-p) (org-at-item-p)))
15616 (call-interactively 'org-update-statistics-cookies))
15617 ((org-on-heading-p) (call-interactively 'org-set-tags))
15618 ((org-at-table.el-p)
15619 (require 'table)
15620 (beginning-of-line 1)
15621 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15622 (call-interactively 'table-recognize-table))
15623 ((org-at-table-p)
15624 (org-table-maybe-eval-formula)
15625 (if arg
15626 (call-interactively 'org-table-recalculate)
15627 (org-table-maybe-recalculate-line))
15628 (call-interactively 'org-table-align))
15629 ((or (org-footnote-at-reference-p)
15630 (org-footnote-at-definition-p))
15631 (call-interactively 'org-footnote-action))
15632 ((org-at-item-checkbox-p)
15633 (call-interactively 'org-toggle-checkbox))
15634 ((org-at-item-p)
15635 (if arg
15636 (call-interactively 'org-toggle-checkbox)
15637 (call-interactively 'org-maybe-renumber-ordered-list)))
15638 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15639 ;; Dynamic block
15640 (beginning-of-line 1)
15641 (save-excursion (org-update-dblock)))
15642 ((save-excursion
15643 (beginning-of-line 1)
15644 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15645 (cond
15646 ((equal (match-string 1) "TBLFM")
15647 ;; Recalculate the table before this line
15648 (save-excursion
15649 (beginning-of-line 1)
15650 (skip-chars-backward " \r\n\t")
15651 (if (org-at-table-p)
15652 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15654 ; (org-set-regexps-and-options)
15655 ; (org-restart-font-lock)
15656 (let ((org-inhibit-startup t)) (org-mode-restart))
15657 (message "Local setup has been refreshed"))))
15658 ((org-clock-update-time-maybe))
15659 (t (error "C-c C-c can do nothing useful at this location")))))
15661 (defun org-mode-restart ()
15662 "Restart Org-mode, to scan again for special lines.
15663 Also updates the keyword regular expressions."
15664 (interactive)
15665 (org-mode)
15666 (message "Org-mode restarted"))
15668 (defun org-kill-note-or-show-branches ()
15669 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15670 (interactive)
15671 (if (not org-finish-function)
15672 (call-interactively 'show-branches)
15673 (let ((org-note-abort t))
15674 (funcall org-finish-function))))
15676 (defun org-return (&optional indent)
15677 "Goto next table row or insert a newline.
15678 Calls `org-table-next-row' or `newline', depending on context.
15679 See the individual commands for more information."
15680 (interactive)
15681 (cond
15682 ((bobp) (if indent (newline-and-indent) (newline)))
15683 ((org-at-table-p)
15684 (org-table-justify-field-maybe)
15685 (call-interactively 'org-table-next-row))
15686 ((and org-return-follows-link
15687 (eq (get-text-property (point) 'face) 'org-link))
15688 (call-interactively 'org-open-at-point))
15689 ((and (org-at-heading-p)
15690 (looking-at
15691 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15692 (org-show-entry)
15693 (end-of-line 1)
15694 (newline))
15695 (t (if indent (newline-and-indent) (newline)))))
15697 (defun org-return-indent ()
15698 "Goto next table row or insert a newline and indent.
15699 Calls `org-table-next-row' or `newline-and-indent', depending on
15700 context. See the individual commands for more information."
15701 (interactive)
15702 (org-return t))
15704 (defun org-ctrl-c-star ()
15705 "Compute table, or change heading status of lines.
15706 Calls `org-table-recalculate' or `org-toggle-heading',
15707 depending on context."
15708 (interactive)
15709 (cond
15710 ((org-at-table-p)
15711 (call-interactively 'org-table-recalculate))
15713 ;; Convert all lines in region to list items
15714 (call-interactively 'org-toggle-heading))))
15716 (defun org-ctrl-c-minus ()
15717 "Insert separator line in table or modify bullet status of line.
15718 Also turns a plain line or a region of lines into list items.
15719 Calls `org-table-insert-hline', `org-toggle-item', or
15720 `org-cycle-list-bullet', depending on context."
15721 (interactive)
15722 (cond
15723 ((org-at-table-p)
15724 (call-interactively 'org-table-insert-hline))
15725 ((org-region-active-p)
15726 (call-interactively 'org-toggle-item))
15727 ((org-in-item-p)
15728 (call-interactively 'org-cycle-list-bullet))
15730 (call-interactively 'org-toggle-item))))
15732 (defun org-toggle-item ()
15733 "Convert headings or normal lines to items, items to normal lines.
15734 If there is no active region, only the current line is considered.
15736 If the first line in the region is a headline, convert all headlines to items.
15738 If the first line in the region is an item, convert all items to normal lines.
15740 If the first line is normal text, add an item bullet to each line."
15741 (interactive)
15742 (let (l2 l beg end)
15743 (if (org-region-active-p)
15744 (setq beg (region-beginning) end (region-end))
15745 (setq beg (point-at-bol)
15746 end (min (1+ (point-at-eol)) (point-max))))
15747 (save-excursion
15748 (goto-char end)
15749 (setq l2 (org-current-line))
15750 (goto-char beg)
15751 (beginning-of-line 1)
15752 (setq l (1- (org-current-line)))
15753 (if (org-at-item-p)
15754 ;; We already have items, de-itemize
15755 (while (< (setq l (1+ l)) l2)
15756 (when (org-at-item-p)
15757 (goto-char (match-beginning 2))
15758 (delete-region (match-beginning 2) (match-end 2))
15759 (and (looking-at "[ \t]+") (replace-match "")))
15760 (beginning-of-line 2))
15761 (if (org-on-heading-p)
15762 ;; Headings, convert to items
15763 (while (< (setq l (1+ l)) l2)
15764 (if (looking-at org-outline-regexp)
15765 (replace-match "- " t t))
15766 (beginning-of-line 2))
15767 ;; normal lines, turn them into items
15768 (while (< (setq l (1+ l)) l2)
15769 (unless (org-at-item-p)
15770 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15771 (replace-match "\\1- \\2")))
15772 (beginning-of-line 2)))))))
15774 (defun org-toggle-heading (&optional nstars)
15775 "Convert headings to normal text, or items or text to headings.
15776 If there is no active region, only the current line is considered.
15778 If the first line is a heading, remove the stars from all headlines
15779 in the region.
15781 If the first line is a plain list item, turn all plain list items
15782 into headings.
15784 If the first line is a normal line, turn each and every line in the
15785 region into a heading.
15787 When converting a line into a heading, the number of stars is chosen
15788 such that the lines become children of the current entry. However,
15789 when a prefix argument is given, its value determines the number of
15790 stars to add."
15791 (interactive "P")
15792 (let (l2 l itemp beg end)
15793 (if (org-region-active-p)
15794 (setq beg (region-beginning) end (region-end))
15795 (setq beg (point-at-bol)
15796 end (min (1+ (point-at-eol)) (point-max))))
15797 (save-excursion
15798 (goto-char end)
15799 (setq l2 (org-current-line))
15800 (goto-char beg)
15801 (beginning-of-line 1)
15802 (setq l (1- (org-current-line)))
15803 (if (org-on-heading-p)
15804 ;; We already have headlines, de-star them
15805 (while (< (setq l (1+ l)) l2)
15806 (when (org-on-heading-p t)
15807 (and (looking-at outline-regexp) (replace-match "")))
15808 (beginning-of-line 2))
15809 (setq itemp (org-at-item-p))
15810 (let* ((stars
15811 (if nstars
15812 (make-string (prefix-numeric-value current-prefix-arg)
15814 (save-excursion
15815 (if (re-search-backward org-complex-heading-regexp nil t)
15816 (match-string 1) ""))))
15817 (add-stars (cond (nstars "")
15818 ((equal stars "") "*")
15819 (org-odd-levels-only "**")
15820 (t "*")))
15821 (rpl (concat stars add-stars " ")))
15822 (while (< (setq l (1+ l)) l2)
15823 (if itemp
15824 (and (org-at-item-p) (replace-match rpl t t))
15825 (unless (org-on-heading-p)
15826 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15827 (replace-match (concat rpl (match-string 2))))))
15828 (beginning-of-line 2)))))))
15830 (defun org-meta-return (&optional arg)
15831 "Insert a new heading or wrap a region in a table.
15832 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15833 See the individual commands for more information."
15834 (interactive "P")
15835 (cond
15836 ((run-hook-with-args-until-success 'org-metareturn-hook))
15837 ((org-at-table-p)
15838 (call-interactively 'org-table-wrap-region))
15839 (t (call-interactively 'org-insert-heading))))
15841 ;;; Menu entries
15843 ;; Define the Org-mode menus
15844 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15845 '("Tbl"
15846 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15847 ["Next Field" org-cycle (org-at-table-p)]
15848 ["Previous Field" org-shifttab (org-at-table-p)]
15849 ["Next Row" org-return (org-at-table-p)]
15850 "--"
15851 ["Blank Field" org-table-blank-field (org-at-table-p)]
15852 ["Edit Field" org-table-edit-field (org-at-table-p)]
15853 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15854 "--"
15855 ("Column"
15856 ["Move Column Left" org-metaleft (org-at-table-p)]
15857 ["Move Column Right" org-metaright (org-at-table-p)]
15858 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15859 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15860 ("Row"
15861 ["Move Row Up" org-metaup (org-at-table-p)]
15862 ["Move Row Down" org-metadown (org-at-table-p)]
15863 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15864 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15865 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15866 "--"
15867 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15868 ("Rectangle"
15869 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15870 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15871 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15872 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15873 "--"
15874 ("Calculate"
15875 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15876 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15877 ["Edit Formulas" org-edit-special (org-at-table-p)]
15878 "--"
15879 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15880 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15881 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15882 "--"
15883 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15884 "--"
15885 ["Sum Column/Rectangle" org-table-sum
15886 (or (org-at-table-p) (org-region-active-p))]
15887 ["Which Column?" org-table-current-column (org-at-table-p)])
15888 ["Debug Formulas"
15889 org-table-toggle-formula-debugger
15890 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15891 ["Show Col/Row Numbers"
15892 org-table-toggle-coordinate-overlays
15893 :style toggle
15894 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15895 "--"
15896 ["Create" org-table-create (and (not (org-at-table-p))
15897 org-enable-table-editor)]
15898 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15899 ["Import from File" org-table-import (not (org-at-table-p))]
15900 ["Export to File" org-table-export (org-at-table-p)]
15901 "--"
15902 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15904 (easy-menu-define org-org-menu org-mode-map "Org menu"
15905 '("Org"
15906 ("Show/Hide"
15907 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15908 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15909 ["Sparse Tree..." org-sparse-tree t]
15910 ["Reveal Context" org-reveal t]
15911 ["Show All" show-all t]
15912 "--"
15913 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15914 "--"
15915 ["New Heading" org-insert-heading t]
15916 ("Navigate Headings"
15917 ["Up" outline-up-heading t]
15918 ["Next" outline-next-visible-heading t]
15919 ["Previous" outline-previous-visible-heading t]
15920 ["Next Same Level" outline-forward-same-level t]
15921 ["Previous Same Level" outline-backward-same-level t]
15922 "--"
15923 ["Jump" org-goto t])
15924 ("Edit Structure"
15925 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15926 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15927 "--"
15928 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15929 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15930 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15931 "--"
15932 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15933 "--"
15934 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15935 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15936 ["Demote Heading" org-metaright (not (org-at-table-p))]
15937 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15938 "--"
15939 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15940 "--"
15941 ["Convert to odd levels" org-convert-to-odd-levels t]
15942 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15943 ("Editing"
15944 ["Emphasis..." org-emphasize t]
15945 ["Edit Source Example" org-edit-special t]
15946 "--"
15947 ["Footnote new/jump" org-footnote-action t]
15948 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15949 ("Archive"
15950 ["Archive (default method)" org-archive-subtree-default t]
15951 "--"
15952 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
15953 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15954 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
15956 "--"
15957 ("Hyperlinks"
15958 ["Store Link (Global)" org-store-link t]
15959 ["Find existing link to here" org-occur-link-in-agenda-files t]
15960 ["Insert Link" org-insert-link t]
15961 ["Follow Link" org-open-at-point t]
15962 "--"
15963 ["Next link" org-next-link t]
15964 ["Previous link" org-previous-link t]
15965 "--"
15966 ["Descriptive Links"
15967 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15968 :style radio
15969 :selected (member '(org-link) buffer-invisibility-spec)]
15970 ["Literal Links"
15971 (progn
15972 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15973 :style radio
15974 :selected (not (member '(org-link) buffer-invisibility-spec))])
15975 "--"
15976 ("TODO Lists"
15977 ["TODO/DONE/-" org-todo t]
15978 ("Select keyword"
15979 ["Next keyword" org-shiftright (org-on-heading-p)]
15980 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15981 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15982 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15983 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15984 ["Show TODO Tree" org-show-todo-tree t]
15985 ["Global TODO list" org-todo-list t]
15986 "--"
15987 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15988 :selected org-enforce-todo-dependencies :style toggle :active t]
15989 "Settings for tree at point"
15990 ["Do Children sequentially" org-toggle-ordered-property :style radio
15991 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15992 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15993 ["Do Children parallel" org-toggle-ordered-property :style radio
15994 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15995 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15996 "--"
15997 ["Set Priority" org-priority t]
15998 ["Priority Up" org-shiftup t]
15999 ["Priority Down" org-shiftdown t]
16000 "--"
16001 ["Get news from all feeds" org-feed-update-all t]
16002 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16003 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16004 ("TAGS and Properties"
16005 ["Set Tags" org-set-tags-command t]
16006 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16007 "--"
16008 ["Set property" org-set-property t]
16009 ["Column view of properties" org-columns t]
16010 ["Insert Column View DBlock" org-insert-columns-dblock t])
16011 ("Dates and Scheduling"
16012 ["Timestamp" org-time-stamp t]
16013 ["Timestamp (inactive)" org-time-stamp-inactive t]
16014 ("Change Date"
16015 ["1 Day Later" org-shiftright t]
16016 ["1 Day Earlier" org-shiftleft t]
16017 ["1 ... Later" org-shiftup t]
16018 ["1 ... Earlier" org-shiftdown t])
16019 ["Compute Time Range" org-evaluate-time-range t]
16020 ["Schedule Item" org-schedule t]
16021 ["Deadline" org-deadline t]
16022 "--"
16023 ["Custom time format" org-toggle-time-stamp-overlays
16024 :style radio :selected org-display-custom-times]
16025 "--"
16026 ["Goto Calendar" org-goto-calendar t]
16027 ["Date from Calendar" org-date-from-calendar t]
16028 "--"
16029 ["Start/Restart Timer" org-timer-start t]
16030 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16031 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16032 ["Insert Timer String" org-timer t]
16033 ["Insert Timer Item" org-timer-item t])
16034 ("Logging work"
16035 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16036 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16037 ["Clock out" org-clock-out t]
16038 ["Clock cancel" org-clock-cancel t]
16039 "--"
16040 ["Mark as default task" org-clock-mark-default-task t]
16041 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16042 ["Goto running clock" org-clock-goto t]
16043 "--"
16044 ["Display times" org-clock-display t]
16045 ["Create clock table" org-clock-report t]
16046 "--"
16047 ["Record DONE time"
16048 (progn (setq org-log-done (not org-log-done))
16049 (message "Switching to %s will %s record a timestamp"
16050 (car org-done-keywords)
16051 (if org-log-done "automatically" "not")))
16052 :style toggle :selected org-log-done])
16053 "--"
16054 ["Agenda Command..." org-agenda t]
16055 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16056 ("File List for Agenda")
16057 ("Special views current file"
16058 ["TODO Tree" org-show-todo-tree t]
16059 ["Check Deadlines" org-check-deadlines t]
16060 ["Timeline" org-timeline t]
16061 ["Tags/Property tree" org-match-sparse-tree t])
16062 "--"
16063 ["Export/Publish..." org-export t]
16064 ("LaTeX"
16065 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16066 :selected org-cdlatex-mode]
16067 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16068 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16069 ["Modify math symbol" org-cdlatex-math-modify
16070 (org-inside-LaTeX-fragment-p)]
16071 ["Insert citation" org-reftex-citation t]
16072 "--"
16073 ["Export LaTeX fragments as images"
16074 (if (featurep 'org-exp)
16075 (setq org-export-with-LaTeX-fragments
16076 (not org-export-with-LaTeX-fragments))
16077 (require 'org-exp))
16078 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16079 org-export-with-LaTeX-fragments)])
16080 "--"
16081 ("MobileOrg"
16082 ["Push Files and Views" org-mobile-push t]
16083 ["Get Captured and Flagged" org-mobile-pull t]
16084 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16085 "--"
16086 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16087 "--"
16088 ("Documentation"
16089 ["Show Version" org-version t]
16090 ["Info Documentation" org-info t])
16091 ("Customize"
16092 ["Browse Org Group" org-customize t]
16093 "--"
16094 ["Expand This Menu" org-create-customize-menu
16095 (fboundp 'customize-menu-create)])
16096 ["Send bug report" org-submit-bug-report t]
16097 "--"
16098 ("Refresh/Reload"
16099 ["Refresh setup current buffer" org-mode-restart t]
16100 ["Reload Org (after update)" org-reload t]
16101 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16104 (defun org-info (&optional node)
16105 "Read documentation for Org-mode in the info system.
16106 With optional NODE, go directly to that node."
16107 (interactive)
16108 (info (format "(org)%s" (or node ""))))
16110 ;;;###autoload
16111 (defun org-submit-bug-report ()
16112 "Submit a bug report on Org-mode via mail.
16114 Don't hesitate to report any problems or inaccurate documentation.
16116 If you don't have setup sending mail from (X)Emacs, please copy the
16117 output buffer into your mail program, as it gives us important
16118 information about your Org-mode version and configuration."
16119 (interactive)
16120 (require 'reporter)
16121 (org-load-modules-maybe)
16122 (org-require-autoloaded-modules)
16123 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16124 (reporter-submit-bug-report
16125 "emacs-orgmode@gnu.org"
16126 (org-version)
16127 (let (list)
16128 (save-window-excursion
16129 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16130 (delete-other-windows)
16131 (erase-buffer)
16132 (insert "You are about to submit a bug report to the Org-mode mailing list.
16134 We would like to add your full Org-mode and Outline configuration to the
16135 bug report. This greatly simplifies the work of the maintainer and
16136 other experts on the mailing list.
16138 HOWEVER, some variables you have customized may contain private
16139 information. The names of customers, colleagues, or friends, might
16140 appear in the form of file names, tags, todo states, or search strings.
16141 If you answer yes to the prompt, you might want to check and remove
16142 such private information before sending the email.")
16143 (add-text-properties (point-min) (point-max) '(face org-warning))
16144 (when (yes-or-no-p "Include your Org-mode configuration ")
16145 (mapatoms
16146 (lambda (v)
16147 (and (boundp v)
16148 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16149 (or (and (symbol-value v)
16150 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16151 (and
16152 (get v 'custom-type) (get v 'standard-value)
16153 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16154 (push v list)))))
16155 (kill-buffer (get-buffer "*Warn about privacy*"))
16156 list))
16157 nil nil
16158 "Remember to cover the basics, that is, what you expected to happen and
16159 what in fact did happen. You don't know how to make a good report? See
16161 http://orgmode.org/manual/Feedback.html#Feedback
16163 Your bug report will be posted to the Org-mode mailing list.
16164 ------------------------------------------------------------------------")
16165 (save-excursion
16166 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16167 (replace-match "\\1Bug: \\3 [\\2]")))))
16170 (defun org-install-agenda-files-menu ()
16171 (let ((bl (buffer-list)))
16172 (save-excursion
16173 (while bl
16174 (set-buffer (pop bl))
16175 (if (org-mode-p) (setq bl nil)))
16176 (when (org-mode-p)
16177 (easy-menu-change
16178 '("Org") "File List for Agenda"
16179 (append
16180 (list
16181 ["Edit File List" (org-edit-agenda-file-list) t]
16182 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16183 ["Remove Current File from List" org-remove-file t]
16184 ["Cycle through agenda files" org-cycle-agenda-files t]
16185 ["Occur in all agenda files" org-occur-in-agenda-files t]
16186 "--")
16187 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16189 ;;;; Documentation
16191 ;;;###autoload
16192 (defun org-require-autoloaded-modules ()
16193 (interactive)
16194 (mapc 'require
16195 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16196 org-docbook org-exp org-html org-icalendar
16197 org-id org-latex
16198 org-publish org-remember org-table
16199 org-timer org-xoxo)))
16201 ;;;###autoload
16202 (defun org-reload (&optional uncompiled)
16203 "Reload all org lisp files.
16204 With prefix arg UNCOMPILED, load the uncompiled versions."
16205 (interactive "P")
16206 (require 'find-func)
16207 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16208 (dir-org (file-name-directory (org-find-library-name "org")))
16209 (dir-org-contrib (ignore-errors
16210 (file-name-directory
16211 (org-find-library-name "org-contribdir"))))
16212 (files
16213 (append (directory-files dir-org t file-re)
16214 (and dir-org-contrib
16215 (directory-files dir-org-contrib t file-re))))
16216 (remove-re (concat (if (featurep 'xemacs)
16217 "org-colview" "org-colview-xemacs")
16218 "\\'")))
16219 (setq files (mapcar 'file-name-sans-extension files))
16220 (setq files (mapcar
16221 (lambda (x) (if (string-match remove-re x) nil x))
16222 files))
16223 (setq files (delq nil files))
16224 (mapc
16225 (lambda (f)
16226 (when (featurep (intern (file-name-nondirectory f)))
16227 (if (and (not uncompiled)
16228 (file-exists-p (concat f ".elc")))
16229 (load (concat f ".elc") nil nil t)
16230 (load (concat f ".el") nil nil t))))
16231 files))
16232 (org-version))
16234 ;;;###autoload
16235 (defun org-customize ()
16236 "Call the customize function with org as argument."
16237 (interactive)
16238 (org-load-modules-maybe)
16239 (org-require-autoloaded-modules)
16240 (customize-browse 'org))
16242 (defun org-create-customize-menu ()
16243 "Create a full customization menu for Org-mode, insert it into the menu."
16244 (interactive)
16245 (org-load-modules-maybe)
16246 (org-require-autoloaded-modules)
16247 (if (fboundp 'customize-menu-create)
16248 (progn
16249 (easy-menu-change
16250 '("Org") "Customize"
16251 `(["Browse Org group" org-customize t]
16252 "--"
16253 ,(customize-menu-create 'org)
16254 ["Set" Custom-set t]
16255 ["Save" Custom-save t]
16256 ["Reset to Current" Custom-reset-current t]
16257 ["Reset to Saved" Custom-reset-saved t]
16258 ["Reset to Standard Settings" Custom-reset-standard t]))
16259 (message "\"Org\"-menu now contains full customization menu"))
16260 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16262 ;;;; Miscellaneous stuff
16264 ;;; Generally useful functions
16266 (defun org-get-at-bol (property)
16267 "Get text property PROPERTY at beginning of line."
16268 (get-text-property (point-at-bol) property))
16270 (defun org-find-text-property-in-string (prop s)
16271 "Return the first non-nil value of property PROP in string S."
16272 (or (get-text-property 0 prop s)
16273 (get-text-property (or (next-single-property-change 0 prop s) 0)
16274 prop s)))
16276 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16277 "Display the given MESSAGE as a warning."
16278 (if (fboundp 'display-warning)
16279 (display-warning 'org message
16280 (if (featurep 'xemacs)
16281 'warning
16282 :warning))
16283 (let ((buf (get-buffer-create "*Org warnings*")))
16284 (with-current-buffer buf
16285 (goto-char (point-max))
16286 (insert "Warning (Org): " message)
16287 (unless (bolp)
16288 (newline)))
16289 (display-buffer buf)
16290 (sit-for 0))))
16292 (defun org-in-commented-line ()
16293 "Is point in a line starting with `#'?"
16294 (equal (char-after (point-at-bol)) ?#))
16296 (defun org-in-verbatim-emphasis ()
16297 (save-match-data
16298 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16300 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16301 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16302 (if (and marker (marker-buffer marker)
16303 (buffer-live-p (marker-buffer marker)))
16304 (progn
16305 (switch-to-buffer (marker-buffer marker))
16306 (if (or (> marker (point-max)) (< marker (point-min)))
16307 (widen))
16308 (goto-char marker)
16309 (org-show-context 'org-goto))
16310 (if bookmark
16311 (bookmark-jump bookmark)
16312 (error "Cannot find location"))))
16314 (defun org-quote-csv-field (s)
16315 "Quote field for inclusion in CSV material."
16316 (if (string-match "[\",]" s)
16317 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16320 (defun org-plist-delete (plist property)
16321 "Delete PROPERTY from PLIST.
16322 This is in contrast to merely setting it to 0."
16323 (let (p)
16324 (while plist
16325 (if (not (eq property (car plist)))
16326 (setq p (plist-put p (car plist) (nth 1 plist))))
16327 (setq plist (cddr plist)))
16330 (defun org-force-self-insert (N)
16331 "Needed to enforce self-insert under remapping."
16332 (interactive "p")
16333 (self-insert-command N))
16335 (defun org-string-width (s)
16336 "Compute width of string, ignoring invisible characters.
16337 This ignores character with invisibility property `org-link', and also
16338 characters with property `org-cwidth', because these will become invisible
16339 upon the next fontification round."
16340 (let (b l)
16341 (when (or (eq t buffer-invisibility-spec)
16342 (assq 'org-link buffer-invisibility-spec))
16343 (while (setq b (text-property-any 0 (length s)
16344 'invisible 'org-link s))
16345 (setq s (concat (substring s 0 b)
16346 (substring s (or (next-single-property-change
16347 b 'invisible s) (length s)))))))
16348 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16349 (setq s (concat (substring s 0 b)
16350 (substring s (or (next-single-property-change
16351 b 'org-cwidth s) (length s))))))
16352 (setq l (string-width s) b -1)
16353 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16354 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16357 (defun org-get-indentation (&optional line)
16358 "Get the indentation of the current line, interpreting tabs.
16359 When LINE is given, assume it represents a line and compute its indentation."
16360 (if line
16361 (if (string-match "^ *" (org-remove-tabs line))
16362 (match-end 0))
16363 (save-excursion
16364 (beginning-of-line 1)
16365 (skip-chars-forward " \t")
16366 (current-column))))
16368 (defun org-remove-tabs (s &optional width)
16369 "Replace tabulators in S with spaces.
16370 Assumes that s is a single line, starting in column 0."
16371 (setq width (or width tab-width))
16372 (while (string-match "\t" s)
16373 (setq s (replace-match
16374 (make-string
16375 (- (* width (/ (+ (match-beginning 0) width) width))
16376 (match-beginning 0)) ?\ )
16377 t t s)))
16380 (defun org-fix-indentation (line ind)
16381 "Fix indentation in LINE.
16382 IND is a cons cell with target and minimum indentation.
16383 If the current indentation in LINE is smaller than the minimum,
16384 leave it alone. If it is larger than ind, set it to the target."
16385 (let* ((l (org-remove-tabs line))
16386 (i (org-get-indentation l))
16387 (i1 (car ind)) (i2 (cdr ind)))
16388 (if (>= i i2) (setq l (substring line i2)))
16389 (if (> i1 0)
16390 (concat (make-string i1 ?\ ) l)
16391 l)))
16393 (defun org-remove-indentation (code &optional n)
16394 "Remove the maximum common indentation from the lines in CODE.
16395 N may optionally be the number of spaces to remove."
16396 (with-temp-buffer
16397 (insert code)
16398 (org-do-remove-indentation n)
16399 (buffer-string)))
16401 (defun org-do-remove-indentation (&optional n)
16402 "Remove the maximum common indentation from the buffer."
16403 (untabify (point-min) (point-max))
16404 (let ((min 10000) re)
16405 (if n
16406 (setq min n)
16407 (goto-char (point-min))
16408 (while (re-search-forward "^ *[^ \n]" nil t)
16409 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16410 (unless (or (= min 0) (= min 10000))
16411 (setq re (format "^ \\{%d\\}" min))
16412 (goto-char (point-min))
16413 (while (re-search-forward re nil t)
16414 (replace-match "")
16415 (end-of-line 1))
16416 min)))
16418 (defun org-fill-template (template alist)
16419 "Find each %key of ALIST in TEMPLATE and replace it."
16420 (let (entry key value)
16421 (setq alist (sort (copy-sequence alist)
16422 (lambda (a b) (< (length (car a)) (length (car b))))))
16423 (while (setq entry (pop alist))
16424 (setq template
16425 (replace-regexp-in-string
16426 (concat "%" (regexp-quote (car entry)))
16427 (cdr entry) template t t)))
16428 template))
16430 (defun org-base-buffer (buffer)
16431 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16432 (if (not buffer)
16433 buffer
16434 (or (buffer-base-buffer buffer)
16435 buffer)))
16437 (defun org-trim (s)
16438 "Remove whitespace at beginning and end of string."
16439 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16440 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16443 (defun org-wrap (string &optional width lines)
16444 "Wrap string to either a number of lines, or a width in characters.
16445 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16446 that costs. If there is a word longer than WIDTH, the text is actually
16447 wrapped to the length of that word.
16448 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16449 many lines, whatever width that takes.
16450 The return value is a list of lines, without newlines at the end."
16451 (let* ((words (org-split-string string "[ \t\n]+"))
16452 (maxword (apply 'max (mapcar 'org-string-width words)))
16453 w ll)
16454 (cond (width
16455 (org-do-wrap words (max maxword width)))
16456 (lines
16457 (setq w maxword)
16458 (setq ll (org-do-wrap words maxword))
16459 (if (<= (length ll) lines)
16461 (setq ll words)
16462 (while (> (length ll) lines)
16463 (setq w (1+ w))
16464 (setq ll (org-do-wrap words w)))
16465 ll))
16466 (t (error "Cannot wrap this")))))
16468 (defun org-do-wrap (words width)
16469 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16470 (let (lines line)
16471 (while words
16472 (setq line (pop words))
16473 (while (and words (< (+ (length line) (length (car words))) width))
16474 (setq line (concat line " " (pop words))))
16475 (setq lines (push line lines)))
16476 (nreverse lines)))
16478 (defun org-split-string (string &optional separators)
16479 "Splits STRING into substrings at SEPARATORS.
16480 No empty strings are returned if there are matches at the beginning
16481 and end of string."
16482 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16483 (start 0)
16484 notfirst
16485 (list nil))
16486 (while (and (string-match rexp string
16487 (if (and notfirst
16488 (= start (match-beginning 0))
16489 (< start (length string)))
16490 (1+ start) start))
16491 (< (match-beginning 0) (length string)))
16492 (setq notfirst t)
16493 (or (eq (match-beginning 0) 0)
16494 (and (eq (match-beginning 0) (match-end 0))
16495 (eq (match-beginning 0) start))
16496 (setq list
16497 (cons (substring string start (match-beginning 0))
16498 list)))
16499 (setq start (match-end 0)))
16500 (or (eq start (length string))
16501 (setq list
16502 (cons (substring string start)
16503 list)))
16504 (nreverse list)))
16506 (defun org-quote-vert (s)
16507 "Replace \"|\" with \"\\vert\"."
16508 (while (string-match "|" s)
16509 (setq s (replace-match "\\vert" t t s)))
16512 (defun org-uuidgen-p (s)
16513 "Is S an ID created by UUIDGEN?"
16514 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16516 (defun org-context ()
16517 "Return a list of contexts of the current cursor position.
16518 If several contexts apply, all are returned.
16519 Each context entry is a list with a symbol naming the context, and
16520 two positions indicating start and end of the context. Possible
16521 contexts are:
16523 :headline anywhere in a headline
16524 :headline-stars on the leading stars in a headline
16525 :todo-keyword on a TODO keyword (including DONE) in a headline
16526 :tags on the TAGS in a headline
16527 :priority on the priority cookie in a headline
16528 :item on the first line of a plain list item
16529 :item-bullet on the bullet/number of a plain list item
16530 :checkbox on the checkbox in a plain list item
16531 :table in an org-mode table
16532 :table-special on a special filed in a table
16533 :table-table in a table.el table
16534 :link on a hyperlink
16535 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16536 :target on a <<target>>
16537 :radio-target on a <<<radio-target>>>
16538 :latex-fragment on a LaTeX fragment
16539 :latex-preview on a LaTeX fragment with overlayed preview image
16541 This function expects the position to be visible because it uses font-lock
16542 faces as a help to recognize the following contexts: :table-special, :link,
16543 and :keyword."
16544 (let* ((f (get-text-property (point) 'face))
16545 (faces (if (listp f) f (list f)))
16546 (p (point)) clist o)
16547 ;; First the large context
16548 (cond
16549 ((org-on-heading-p t)
16550 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16551 (when (progn
16552 (beginning-of-line 1)
16553 (looking-at org-todo-line-tags-regexp))
16554 (push (org-point-in-group p 1 :headline-stars) clist)
16555 (push (org-point-in-group p 2 :todo-keyword) clist)
16556 (push (org-point-in-group p 4 :tags) clist))
16557 (goto-char p)
16558 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16559 (if (looking-at "\\[#[A-Z0-9]\\]")
16560 (push (org-point-in-group p 0 :priority) clist)))
16562 ((org-at-item-p)
16563 (push (org-point-in-group p 2 :item-bullet) clist)
16564 (push (list :item (point-at-bol)
16565 (save-excursion (org-end-of-item) (point)))
16566 clist)
16567 (and (org-at-item-checkbox-p)
16568 (push (org-point-in-group p 0 :checkbox) clist)))
16570 ((org-at-table-p)
16571 (push (list :table (org-table-begin) (org-table-end)) clist)
16572 (if (memq 'org-formula faces)
16573 (push (list :table-special
16574 (previous-single-property-change p 'face)
16575 (next-single-property-change p 'face)) clist)))
16576 ((org-at-table-p 'any)
16577 (push (list :table-table) clist)))
16578 (goto-char p)
16580 ;; Now the small context
16581 (cond
16582 ((org-at-timestamp-p)
16583 (push (org-point-in-group p 0 :timestamp) clist))
16584 ((memq 'org-link faces)
16585 (push (list :link
16586 (previous-single-property-change p 'face)
16587 (next-single-property-change p 'face)) clist))
16588 ((memq 'org-special-keyword faces)
16589 (push (list :keyword
16590 (previous-single-property-change p 'face)
16591 (next-single-property-change p 'face)) clist))
16592 ((org-on-target-p)
16593 (push (org-point-in-group p 0 :target) clist)
16594 (goto-char (1- (match-beginning 0)))
16595 (if (looking-at org-radio-target-regexp)
16596 (push (org-point-in-group p 0 :radio-target) clist))
16597 (goto-char p))
16598 ((setq o (car (delq nil
16599 (mapcar
16600 (lambda (x)
16601 (if (memq x org-latex-fragment-image-overlays) x))
16602 (org-overlays-at (point))))))
16603 (push (list :latex-fragment
16604 (org-overlay-start o) (org-overlay-end o)) clist)
16605 (push (list :latex-preview
16606 (org-overlay-start o) (org-overlay-end o)) clist))
16607 ((org-inside-LaTeX-fragment-p)
16608 ;; FIXME: positions wrong.
16609 (push (list :latex-fragment (point) (point)) clist)))
16611 (setq clist (nreverse (delq nil clist)))
16612 clist))
16614 ;; FIXME: Compare with at-regexp-p Do we need both?
16615 (defun org-in-regexp (re &optional nlines visually)
16616 "Check if point is inside a match of regexp.
16617 Normally only the current line is checked, but you can include NLINES extra
16618 lines both before and after point into the search.
16619 If VISUALLY is set, require that the cursor is not after the match but
16620 really on, so that the block visually is on the match."
16621 (catch 'exit
16622 (let ((pos (point))
16623 (eol (point-at-eol (+ 1 (or nlines 0))))
16624 (inc (if visually 1 0)))
16625 (save-excursion
16626 (beginning-of-line (- 1 (or nlines 0)))
16627 (while (re-search-forward re eol t)
16628 (if (and (<= (match-beginning 0) pos)
16629 (>= (+ inc (match-end 0)) pos))
16630 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16632 (defun org-at-regexp-p (regexp)
16633 "Is point inside a match of REGEXP in the current line?"
16634 (catch 'exit
16635 (save-excursion
16636 (let ((pos (point)) (end (point-at-eol)))
16637 (beginning-of-line 1)
16638 (while (re-search-forward regexp end t)
16639 (if (and (<= (match-beginning 0) pos)
16640 (>= (match-end 0) pos))
16641 (throw 'exit t)))
16642 nil))))
16644 (defun org-occur-in-agenda-files (regexp &optional nlines)
16645 "Call `multi-occur' with buffers for all agenda files."
16646 (interactive "sOrg-files matching: \np")
16647 (let* ((files (org-agenda-files))
16648 (tnames (mapcar 'file-truename files))
16649 (extra org-agenda-text-search-extra-files)
16651 (when (eq (car extra) 'agenda-archives)
16652 (setq extra (cdr extra))
16653 (setq files (org-add-archive-files files)))
16654 (while (setq f (pop extra))
16655 (unless (member (file-truename f) tnames)
16656 (add-to-list 'files f 'append)
16657 (add-to-list 'tnames (file-truename f) 'append)))
16658 (multi-occur
16659 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
16660 regexp)))
16662 (if (boundp 'occur-mode-find-occurrence-hook)
16663 ;; Emacs 23
16664 (add-hook 'occur-mode-find-occurrence-hook
16665 (lambda ()
16666 (when (org-mode-p)
16667 (org-reveal))))
16668 ;; Emacs 22
16669 (defadvice occur-mode-goto-occurrence
16670 (after org-occur-reveal activate)
16671 (and (org-mode-p) (org-reveal)))
16672 (defadvice occur-mode-goto-occurrence-other-window
16673 (after org-occur-reveal activate)
16674 (and (org-mode-p) (org-reveal)))
16675 (defadvice occur-mode-display-occurrence
16676 (after org-occur-reveal activate)
16677 (when (org-mode-p)
16678 (let ((pos (occur-mode-find-occurrence)))
16679 (with-current-buffer (marker-buffer pos)
16680 (save-excursion
16681 (goto-char pos)
16682 (org-reveal)))))))
16684 (defun org-occur-link-in-agenda-files ()
16685 "Create a link and search for it in the agendas.
16686 The link is not stored in `org-stored-links', it is just created
16687 for the search purpose."
16688 (interactive)
16689 (let ((link (condition-case nil
16690 (org-store-link nil)
16691 (error "Unable to create a link to here"))))
16692 (org-occur-in-agenda-files (regexp-quote link))))
16694 (defun org-uniquify (list)
16695 "Remove duplicate elements from LIST."
16696 (let (res)
16697 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16698 res))
16700 (defun org-delete-all (elts list)
16701 "Remove all elements in ELTS from LIST."
16702 (while elts
16703 (setq list (delete (pop elts) list)))
16704 list)
16706 (defun org-back-over-empty-lines ()
16707 "Move backwards over whitespace, to the beginning of the first empty line.
16708 Returns the number of empty lines passed."
16709 (let ((pos (point)))
16710 (skip-chars-backward " \t\n\r")
16711 (beginning-of-line 2)
16712 (goto-char (min (point) pos))
16713 (count-lines (point) pos)))
16715 (defun org-skip-whitespace ()
16716 (skip-chars-forward " \t\n\r"))
16718 (defun org-point-in-group (point group &optional context)
16719 "Check if POINT is in match-group GROUP.
16720 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16721 match. If the match group does ot exist or point is not inside it,
16722 return nil."
16723 (and (match-beginning group)
16724 (>= point (match-beginning group))
16725 (<= point (match-end group))
16726 (if context
16727 (list context (match-beginning group) (match-end group))
16728 t)))
16730 (defun org-switch-to-buffer-other-window (&rest args)
16731 "Switch to buffer in a second window on the current frame.
16732 In particular, do not allow pop-up frames."
16733 (let (pop-up-frames special-display-buffer-names special-display-regexps
16734 special-display-function)
16735 (apply 'switch-to-buffer-other-window args)))
16737 (defun org-combine-plists (&rest plists)
16738 "Create a single property list from all plists in PLISTS.
16739 The process starts by copying the first list, and then setting properties
16740 from the other lists. Settings in the last list are the most significant
16741 ones and overrule settings in the other lists."
16742 (let ((rtn (copy-sequence (pop plists)))
16743 p v ls)
16744 (while plists
16745 (setq ls (pop plists))
16746 (while ls
16747 (setq p (pop ls) v (pop ls))
16748 (setq rtn (plist-put rtn p v))))
16749 rtn))
16751 (defun org-move-line-down (arg)
16752 "Move the current line down. With prefix argument, move it past ARG lines."
16753 (interactive "p")
16754 (let ((col (current-column))
16755 beg end pos)
16756 (beginning-of-line 1) (setq beg (point))
16757 (beginning-of-line 2) (setq end (point))
16758 (beginning-of-line (+ 1 arg))
16759 (setq pos (move-marker (make-marker) (point)))
16760 (insert (delete-and-extract-region beg end))
16761 (goto-char pos)
16762 (org-move-to-column col)))
16764 (defun org-move-line-up (arg)
16765 "Move the current line up. With prefix argument, move it past ARG lines."
16766 (interactive "p")
16767 (let ((col (current-column))
16768 beg end pos)
16769 (beginning-of-line 1) (setq beg (point))
16770 (beginning-of-line 2) (setq end (point))
16771 (beginning-of-line (- arg))
16772 (setq pos (move-marker (make-marker) (point)))
16773 (insert (delete-and-extract-region beg end))
16774 (goto-char pos)
16775 (org-move-to-column col)))
16777 (defun org-replace-escapes (string table)
16778 "Replace %-escapes in STRING with values in TABLE.
16779 TABLE is an association list with keys like \"%a\" and string values.
16780 The sequences in STRING may contain normal field width and padding information,
16781 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16782 so values can contain further %-escapes if they are define later in TABLE."
16783 (let ((case-fold-search nil)
16784 e re rpl)
16785 (while (setq e (pop table))
16786 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16787 (while (string-match re string)
16788 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16789 (cdr e)))
16790 (setq string (replace-match rpl t t string))))
16791 string))
16794 (defun org-sublist (list start end)
16795 "Return a section of LIST, from START to END.
16796 Counting starts at 1."
16797 (let (rtn (c start))
16798 (setq list (nthcdr (1- start) list))
16799 (while (and list (<= c end))
16800 (push (pop list) rtn)
16801 (setq c (1+ c)))
16802 (nreverse rtn)))
16804 (defun org-find-base-buffer-visiting (file)
16805 "Like `find-buffer-visiting' but always return the base buffer and
16806 not an indirect buffer."
16807 (let ((buf (or (get-file-buffer file)
16808 (find-buffer-visiting file))))
16809 (if buf
16810 (or (buffer-base-buffer buf) buf)
16811 nil)))
16813 (defun org-image-file-name-regexp (&optional extensions)
16814 "Return regexp matching the file names of images.
16815 If EXTENSIONS is given, only match these."
16816 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16817 (image-file-name-regexp)
16818 (let ((image-file-name-extensions
16819 (or extensions
16820 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16821 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16822 (concat "\\."
16823 (regexp-opt (nconc (mapcar 'upcase
16824 image-file-name-extensions)
16825 image-file-name-extensions)
16827 "\\'"))))
16829 (defun org-file-image-p (file &optional extensions)
16830 "Return non-nil if FILE is an image."
16831 (save-match-data
16832 (string-match (org-image-file-name-regexp extensions) file)))
16834 (defun org-get-cursor-date ()
16835 "Return the date at cursor in as a time.
16836 This works in the calendar and in the agenda, anywhere else it just
16837 returns the current time."
16838 (let (date day defd)
16839 (cond
16840 ((eq major-mode 'calendar-mode)
16841 (setq date (calendar-cursor-to-date)
16842 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16843 ((eq major-mode 'org-agenda-mode)
16844 (setq day (get-text-property (point) 'day))
16845 (if day
16846 (setq date (calendar-gregorian-from-absolute day)
16847 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
16848 (nth 2 date))))))
16849 (or defd (current-time))))
16851 (defvar org-agenda-action-marker (make-marker)
16852 "Marker pointing to the entry for the next agenda action.")
16854 (defun org-mark-entry-for-agenda-action ()
16855 "Mark the current entry as target of an agenda action.
16856 Agenda actions are actions executed from the agenda with the key `k',
16857 which make use of the date at the cursor."
16858 (interactive)
16859 (move-marker org-agenda-action-marker
16860 (save-excursion (org-back-to-heading t) (point))
16861 (current-buffer))
16862 (message
16863 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16865 ;;; Paragraph filling stuff.
16866 ;; We want this to be just right, so use the full arsenal.
16868 (defun org-indent-line-function ()
16869 "Indent line like previous, but further if previous was headline or item."
16870 (interactive)
16871 (let* ((pos (point))
16872 (itemp (org-at-item-p))
16873 (case-fold-search t)
16874 (org-drawer-regexp (or org-drawer-regexp "\000"))
16875 column bpos bcol tpos tcol bullet btype bullet-type)
16876 ;; Find the previous relevant line
16877 (beginning-of-line 1)
16878 (cond
16879 ((looking-at "#") (setq column 0))
16880 ((looking-at "\\*+ ") (setq column 0))
16881 ((and (looking-at "[ \t]*:END:")
16882 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16883 (save-excursion
16884 (goto-char (1- (match-beginning 1)))
16885 (setq column (current-column))))
16886 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
16887 (save-excursion
16888 (re-search-backward
16889 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
16890 (setq column (org-get-indentation (match-string 0))))
16892 (beginning-of-line 0)
16893 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16894 (not (looking-at "[ \t]*:END:"))
16895 (not (looking-at org-drawer-regexp)))
16896 (beginning-of-line 0))
16897 (cond
16898 ((looking-at "\\*+[ \t]+")
16899 (if (not org-adapt-indentation)
16900 (setq column 0)
16901 (goto-char (match-end 0))
16902 (setq column (current-column))))
16903 ((looking-at org-drawer-regexp)
16904 (goto-char (1- (match-beginning 1)))
16905 (setq column (current-column)))
16906 ((looking-at "\\([ \t]*\\):END:")
16907 (goto-char (match-end 1))
16908 (setq column (current-column)))
16909 ((org-in-item-p)
16910 (org-beginning-of-item)
16911 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16912 (setq bpos (match-beginning 1) tpos (match-end 0)
16913 bcol (progn (goto-char bpos) (current-column))
16914 tcol (progn (goto-char tpos) (current-column))
16915 bullet (match-string 1)
16916 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16917 (if (> tcol (+ bcol org-description-max-indent))
16918 (setq tcol (+ bcol 5)))
16919 (if (not itemp)
16920 (setq column tcol)
16921 (goto-char pos)
16922 (beginning-of-line 1)
16923 (if (looking-at "\\S-")
16924 (progn
16925 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16926 (setq bullet (match-string 1)
16927 btype (if (string-match "[0-9]" bullet) "n" bullet))
16928 (setq column (if (equal btype bullet-type) bcol tcol)))
16929 (setq column (org-get-indentation)))))
16930 (t (setq column (org-get-indentation))))))
16931 (goto-char pos)
16932 (if (<= (current-column) (current-indentation))
16933 (org-indent-line-to column)
16934 (save-excursion (org-indent-line-to column)))
16935 (setq column (current-column))
16936 (beginning-of-line 1)
16937 (if (looking-at
16938 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16939 (replace-match (concat (match-string 1)
16940 (format org-property-format
16941 (match-string 2) (match-string 3)))
16942 t t))
16943 (org-move-to-column column)))
16945 (defun org-set-autofill-regexps ()
16946 (interactive)
16947 ;; In the paragraph separator we include headlines, because filling
16948 ;; text in a line directly attached to a headline would otherwise
16949 ;; fill the headline as well.
16950 (org-set-local 'comment-start-skip "^#+[ \t]*")
16951 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
16952 ;; The paragraph starter includes hand-formatted lists.
16953 (org-set-local
16954 'paragraph-start
16955 (concat
16956 "\f" "\\|"
16957 "[ ]*$" "\\|"
16958 "\\*+ " "\\|"
16959 "[ \t]*#" "\\|"
16960 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16961 "[ \t]*[:|]" "\\|"
16962 "\\$\\$" "\\|"
16963 "\\\\\\(begin\\|end\\|[][]\\)"))
16964 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16965 ;; But only if the user has not turned off tables or fixed-width regions
16966 (org-set-local
16967 'auto-fill-inhibit-regexp
16968 (concat "\\*+ \\|#\\+"
16969 "\\|[ \t]*" org-keyword-time-regexp
16970 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16971 (concat
16972 "\\|[ \t]*["
16973 (if org-enable-table-editor "|" "")
16974 (if org-enable-fixed-width-editor ":" "")
16975 "]"))))
16976 ;; We use our own fill-paragraph function, to make sure that tables
16977 ;; and fixed-width regions are not wrapped. That function will pass
16978 ;; through to `fill-paragraph' when appropriate.
16979 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16980 ; Adaptive filling: To get full control, first make sure that
16981 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16982 (org-set-local 'adaptive-fill-regexp "\000")
16983 (org-set-local 'adaptive-fill-function
16984 'org-adaptive-fill-function)
16985 (org-set-local
16986 'align-mode-rules-list
16987 '((org-in-buffer-settings
16988 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16989 (modes . '(org-mode))))))
16991 (defun org-fill-paragraph (&optional justify)
16992 "Re-align a table, pass through to fill-paragraph if no table."
16993 (let ((table-p (org-at-table-p))
16994 (table.el-p (org-at-table.el-p)))
16995 (cond ((and (equal (char-after (point-at-bol)) ?*)
16996 (save-excursion (goto-char (point-at-bol))
16997 (looking-at outline-regexp)))
16998 t) ; skip headlines
16999 (table.el-p t) ; skip table.el tables
17000 (table-p (org-table-align) t) ; align org-mode tables
17001 (t nil)))) ; call paragraph-fill
17003 ;; For reference, this is the default value of adaptive-fill-regexp
17004 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17006 (defun org-adaptive-fill-function ()
17007 "Return a fill prefix for org-mode files.
17008 In particular, this makes sure hanging paragraphs for hand-formatted lists
17009 work correctly."
17010 (cond ((looking-at "#[ \t]+")
17011 (match-string 0))
17012 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17013 (save-excursion
17014 (if (> (match-end 1) (+ (match-beginning 1)
17015 org-description-max-indent))
17016 (goto-char (+ (match-beginning 1) 5))
17017 (goto-char (match-end 0)))
17018 (make-string (current-column) ?\ )))
17019 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
17020 (save-excursion
17021 (goto-char (match-end 0))
17022 (make-string (current-column) ?\ )))
17023 (t nil)))
17025 ;;; Other stuff.
17027 (defun org-toggle-fixed-width-section (arg)
17028 "Toggle the fixed-width export.
17029 If there is no active region, the QUOTE keyword at the current headline is
17030 inserted or removed. When present, it causes the text between this headline
17031 and the next to be exported as fixed-width text, and unmodified.
17032 If there is an active region, this command adds or removes a colon as the
17033 first character of this line. If the first character of a line is a colon,
17034 this line is also exported in fixed-width font."
17035 (interactive "P")
17036 (let* ((cc 0)
17037 (regionp (org-region-active-p))
17038 (beg (if regionp (region-beginning) (point)))
17039 (end (if regionp (region-end)))
17040 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17041 (case-fold-search nil)
17042 (re "[ \t]*\\(: \\)")
17043 off)
17044 (if regionp
17045 (save-excursion
17046 (goto-char beg)
17047 (setq cc (current-column))
17048 (beginning-of-line 1)
17049 (setq off (looking-at re))
17050 (while (> nlines 0)
17051 (setq nlines (1- nlines))
17052 (beginning-of-line 1)
17053 (cond
17054 (arg
17055 (org-move-to-column cc t)
17056 (insert ": \n")
17057 (forward-line -1))
17058 ((and off (looking-at re))
17059 (replace-match "" t t nil 1))
17060 ((not off) (org-move-to-column cc t) (insert ": ")))
17061 (forward-line 1)))
17062 (save-excursion
17063 (org-back-to-heading)
17064 (if (looking-at (concat outline-regexp
17065 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17066 (replace-match "" t t nil 1)
17067 (if (looking-at outline-regexp)
17068 (progn
17069 (goto-char (match-end 0))
17070 (insert org-quote-string " "))))))))
17072 (defun org-reftex-citation ()
17073 "Use reftex-citation to insert a citation into the buffer.
17074 This looks for a line like
17076 #+BIBLIOGRAPHY: foo plain option:-d
17078 and derives from it that foo.bib is the bibliography file relevant
17079 for this document. It then installs the necessary environment for RefTeX
17080 to work in this buffer and calls `reftex-citation' to insert a citation
17081 into the buffer.
17083 Export of such citations to both LaTeX and HTML is handled by the contributed
17084 package org-exp-bibtex by Taru Karttunen."
17085 (interactive)
17086 (let ((reftex-docstruct-symbol 'rds)
17087 (reftex-cite-format "\\cite{%l}")
17088 rds bib)
17089 (save-excursion
17090 (save-restriction
17091 (widen)
17092 (let ((case-fold-search t)
17093 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17094 (if (not (save-excursion
17095 (or (re-search-forward re nil t)
17096 (re-search-backward re nil t))))
17097 (error "No bibliography defined in file")
17098 (setq bib (concat (match-string 1) ".bib")
17099 rds (list (list 'bib bib)))))))
17100 (call-interactively 'reftex-citation)))
17102 ;;;; Functions extending outline functionality
17104 (defun org-beginning-of-line (&optional arg)
17105 "Go to the beginning of the current line. If that is invisible, continue
17106 to a visible line beginning. This makes the function of C-a more intuitive.
17107 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17108 first attempt, and only move to after the tags when the cursor is already
17109 beyond the end of the headline."
17110 (interactive "P")
17111 (let ((pos (point))
17112 (special (if (consp org-special-ctrl-a/e)
17113 (car org-special-ctrl-a/e)
17114 org-special-ctrl-a/e))
17115 refpos)
17116 (if (org-bound-and-true-p line-move-visual)
17117 (beginning-of-visual-line 1)
17118 (beginning-of-line 1))
17119 (if (and arg (fboundp 'move-beginning-of-line))
17120 (call-interactively 'move-beginning-of-line)
17121 (if (bobp)
17123 (backward-char 1)
17124 (if (org-invisible-p)
17125 (while (and (not (bobp)) (org-invisible-p))
17126 (backward-char 1)
17127 (beginning-of-line 1))
17128 (forward-char 1))))
17129 (when special
17130 (cond
17131 ((and (looking-at org-complex-heading-regexp)
17132 (= (char-after (match-end 1)) ?\ ))
17133 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17134 (point-at-eol)))
17135 (goto-char
17136 (if (eq special t)
17137 (cond ((> pos refpos) refpos)
17138 ((= pos (point)) refpos)
17139 (t (point)))
17140 (cond ((> pos (point)) (point))
17141 ((not (eq last-command this-command)) (point))
17142 (t refpos)))))
17143 ((org-at-item-p)
17144 (goto-char
17145 (if (eq special t)
17146 (cond ((> pos (match-end 4)) (match-end 4))
17147 ((= pos (point)) (match-end 4))
17148 (t (point)))
17149 (cond ((> pos (point)) (point))
17150 ((not (eq last-command this-command)) (point))
17151 (t (match-end 4))))))))
17152 (org-no-warnings
17153 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17155 (defun org-end-of-line (&optional arg)
17156 "Go to the end of the line.
17157 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17158 first attempt, and only move to after the tags when the cursor is already
17159 beyond the end of the headline."
17160 (interactive "P")
17161 (let ((special (if (consp org-special-ctrl-a/e)
17162 (cdr org-special-ctrl-a/e)
17163 org-special-ctrl-a/e)))
17164 (if (or (not special)
17165 (not (org-on-heading-p))
17166 arg)
17167 (call-interactively
17168 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17169 ((fboundp 'move-end-of-line) 'move-end-of-line)
17170 (t 'end-of-line)))
17171 (let ((pos (point)))
17172 (beginning-of-line 1)
17173 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17174 (if (eq special t)
17175 (if (or (< pos (match-beginning 1))
17176 (= pos (match-end 0)))
17177 (goto-char (match-beginning 1))
17178 (goto-char (match-end 0)))
17179 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17180 (goto-char (match-end 0))
17181 (goto-char (match-beginning 1))))
17182 (call-interactively (if (fboundp 'move-end-of-line)
17183 'move-end-of-line
17184 'end-of-line)))))
17185 (org-no-warnings
17186 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17188 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17189 (define-key org-mode-map "\C-e" 'org-end-of-line)
17190 (define-key org-mode-map [home] 'org-beginning-of-line)
17191 (define-key org-mode-map [end] 'org-end-of-line)
17193 (defun org-backward-sentence (&optional arg)
17194 "Go to beginning of sentence, or beginning of table field.
17195 This will call `backward-sentence' or `org-table-beginning-of-field',
17196 depending on context."
17197 (interactive "P")
17198 (cond
17199 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17200 (t (call-interactively 'backward-sentence))))
17202 (defun org-forward-sentence (&optional arg)
17203 "Go to end of sentence, or end of table field.
17204 This will call `forward-sentence' or `org-table-end-of-field',
17205 depending on context."
17206 (interactive "P")
17207 (cond
17208 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17209 (t (call-interactively 'forward-sentence))))
17211 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17212 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17214 (defun org-kill-line (&optional arg)
17215 "Kill line, to tags or end of line."
17216 (interactive "P")
17217 (cond
17218 ((or (not org-special-ctrl-k)
17219 (bolp)
17220 (not (org-on-heading-p)))
17221 (call-interactively 'kill-line))
17222 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17223 (kill-region (point) (match-beginning 1))
17224 (org-set-tags nil t))
17225 (t (kill-region (point) (point-at-eol)))))
17227 (define-key org-mode-map "\C-k" 'org-kill-line)
17229 (defun org-yank (&optional arg)
17230 "Yank. If the kill is a subtree, treat it specially.
17231 This command will look at the current kill and check if is a single
17232 subtree, or a series of subtrees[1]. If it passes the test, and if the
17233 cursor is at the beginning of a line or after the stars of a currently
17234 empty headline, then the yank is handled specially. How exactly depends
17235 on the value of the following variables, both set by default.
17237 org-yank-folded-subtrees
17238 When set, the subtree(s) will be folded after insertion, but only
17239 if doing so would now swallow text after the yanked text.
17241 org-yank-adjusted-subtrees
17242 When set, the subtree will be promoted or demoted in order to
17243 fit into the local outline tree structure, which means that the level
17244 will be adjusted so that it becomes the smaller one of the two
17245 *visible* surrounding headings.
17247 Any prefix to this command will cause `yank' to be called directly with
17248 no special treatment. In particular, a simple `C-u' prefix will just
17249 plainly yank the text as it is.
17251 \[1] The test checks if the first non-white line is a heading
17252 and if there are no other headings with fewer stars."
17253 (interactive "P")
17254 (org-yank-generic 'yank arg))
17256 (defun org-yank-generic (command arg)
17257 "Perform some yank-like command.
17259 This function implements the behavior described in the `org-yank'
17260 documentation. However, it has been generalized to work for any
17261 interactive command with similar behavior."
17263 ;; pretend to be command COMMAND
17264 (setq this-command command)
17266 (if arg
17267 (call-interactively command)
17269 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17270 (and (org-kill-is-subtree-p)
17271 (or (bolp)
17272 (and (looking-at "[ \t]*$")
17273 (string-match
17274 "\\`\\*+\\'"
17275 (buffer-substring (point-at-bol) (point)))))))
17276 swallowp)
17277 (cond
17278 ((and subtreep org-yank-folded-subtrees)
17279 (let ((beg (point))
17280 end)
17281 (if (and subtreep org-yank-adjusted-subtrees)
17282 (org-paste-subtree nil nil 'for-yank)
17283 (call-interactively command))
17285 (setq end (point))
17286 (goto-char beg)
17287 (when (and (bolp) subtreep
17288 (not (setq swallowp
17289 (org-yank-folding-would-swallow-text beg end))))
17290 (or (looking-at outline-regexp)
17291 (re-search-forward (concat "^" outline-regexp) end t))
17292 (while (and (< (point) end) (looking-at outline-regexp))
17293 (hide-subtree)
17294 (org-cycle-show-empty-lines 'folded)
17295 (condition-case nil
17296 (outline-forward-same-level 1)
17297 (error (goto-char end)))))
17298 (when swallowp
17299 (message
17300 "Inserted text not folded because that would swallow text"))
17302 (goto-char end)
17303 (skip-chars-forward " \t\n\r")
17304 (beginning-of-line 1)
17305 (push-mark beg 'nomsg)))
17306 ((and subtreep org-yank-adjusted-subtrees)
17307 (let ((beg (point-at-bol)))
17308 (org-paste-subtree nil nil 'for-yank)
17309 (push-mark beg 'nomsg)))
17311 (call-interactively command))))))
17313 (defun org-yank-folding-would-swallow-text (beg end)
17314 "Would hide-subtree at BEG swallow any text after END?"
17315 (let (level)
17316 (save-excursion
17317 (goto-char beg)
17318 (when (or (looking-at outline-regexp)
17319 (re-search-forward (concat "^" outline-regexp) end t))
17320 (setq level (org-outline-level)))
17321 (goto-char end)
17322 (skip-chars-forward " \t\r\n\v\f")
17323 (if (or (eobp)
17324 (and (bolp) (looking-at org-outline-regexp)
17325 (<= (org-outline-level) level)))
17326 nil ; Nothing would be swallowed
17327 t)))) ; something would swallow
17329 (define-key org-mode-map "\C-y" 'org-yank)
17331 (defun org-invisible-p ()
17332 "Check if point is at a character currently not visible."
17333 ;; Early versions of noutline don't have `outline-invisible-p'.
17334 (if (fboundp 'outline-invisible-p)
17335 (outline-invisible-p)
17336 (get-char-property (point) 'invisible)))
17338 (defun org-invisible-p2 ()
17339 "Check if point is at a character currently not visible."
17340 (save-excursion
17341 (if (and (eolp) (not (bobp))) (backward-char 1))
17342 ;; Early versions of noutline don't have `outline-invisible-p'.
17343 (if (fboundp 'outline-invisible-p)
17344 (outline-invisible-p)
17345 (get-char-property (point) 'invisible))))
17347 (defun org-back-to-heading (&optional invisible-ok)
17348 "Call `outline-back-to-heading', but provide a better error message."
17349 (condition-case nil
17350 (outline-back-to-heading invisible-ok)
17351 (error (error "Before first headline at position %d in buffer %s"
17352 (point) (current-buffer)))))
17354 (defun org-before-first-heading-p ()
17355 "Before first heading?"
17356 (save-excursion
17357 (null (re-search-backward "^\\*+ " nil t))))
17359 (defun org-on-heading-p (&optional ignored)
17360 (outline-on-heading-p t))
17361 (defun org-at-heading-p (&optional ignored)
17362 (outline-on-heading-p t))
17364 (defun org-at-heading-or-item-p ()
17365 (or (org-on-heading-p) (org-at-item-p)))
17367 (defun org-on-target-p ()
17368 (or (org-in-regexp org-radio-target-regexp)
17369 (org-in-regexp org-target-regexp)))
17371 (defun org-up-heading-all (arg)
17372 "Move to the heading line of which the present line is a subheading.
17373 This function considers both visible and invisible heading lines.
17374 With argument, move up ARG levels."
17375 (if (fboundp 'outline-up-heading-all)
17376 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17377 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17379 (defun org-up-heading-safe ()
17380 "Move to the heading line of which the present line is a subheading.
17381 This version will not throw an error. It will return the level of the
17382 headline found, or nil if no higher level is found.
17384 Also, this function will be a lot faster than `outline-up-heading',
17385 because it relies on stars being the outline starters. This can really
17386 make a significant difference in outlines with very many siblings."
17387 (let (start-level re)
17388 (org-back-to-heading t)
17389 (setq start-level (funcall outline-level))
17390 (if (equal start-level 1)
17392 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17393 (if (re-search-backward re nil t)
17394 (funcall outline-level)))))
17396 (defun org-first-sibling-p ()
17397 "Is this heading the first child of its parents?"
17398 (interactive)
17399 (let ((re (concat "^" outline-regexp))
17400 level l)
17401 (unless (org-at-heading-p t)
17402 (error "Not at a heading"))
17403 (setq level (funcall outline-level))
17404 (save-excursion
17405 (if (not (re-search-backward re nil t))
17407 (setq l (funcall outline-level))
17408 (< l level)))))
17410 (defun org-goto-sibling (&optional previous)
17411 "Goto the next sibling, even if it is invisible.
17412 When PREVIOUS is set, go to the previous sibling instead. Returns t
17413 when a sibling was found. When none is found, return nil and don't
17414 move point."
17415 (let ((fun (if previous 're-search-backward 're-search-forward))
17416 (pos (point))
17417 (re (concat "^" outline-regexp))
17418 level l)
17419 (when (condition-case nil (org-back-to-heading t) (error nil))
17420 (setq level (funcall outline-level))
17421 (catch 'exit
17422 (or previous (forward-char 1))
17423 (while (funcall fun re nil t)
17424 (setq l (funcall outline-level))
17425 (when (< l level) (goto-char pos) (throw 'exit nil))
17426 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17427 (goto-char pos)
17428 nil))))
17430 (defun org-show-siblings ()
17431 "Show all siblings of the current headline."
17432 (save-excursion
17433 (while (org-goto-sibling) (org-flag-heading nil)))
17434 (save-excursion
17435 (while (org-goto-sibling 'previous)
17436 (org-flag-heading nil))))
17438 (defun org-show-hidden-entry ()
17439 "Show an entry where even the heading is hidden."
17440 (save-excursion
17441 (org-show-entry)))
17443 (defun org-flag-heading (flag &optional entry)
17444 "Flag the current heading. FLAG non-nil means make invisible.
17445 When ENTRY is non-nil, show the entire entry."
17446 (save-excursion
17447 (org-back-to-heading t)
17448 ;; Check if we should show the entire entry
17449 (if entry
17450 (progn
17451 (org-show-entry)
17452 (save-excursion
17453 (and (outline-next-heading)
17454 (org-flag-heading nil))))
17455 (outline-flag-region (max (point-min) (1- (point)))
17456 (save-excursion (outline-end-of-heading) (point))
17457 flag))))
17459 (defun org-get-next-sibling ()
17460 "Move to next heading of the same level, and return point.
17461 If there is no such heading, return nil.
17462 This is like outline-next-sibling, but invisible headings are ok."
17463 (let ((level (funcall outline-level)))
17464 (outline-next-heading)
17465 (while (and (not (eobp)) (> (funcall outline-level) level))
17466 (outline-next-heading))
17467 (if (or (eobp) (< (funcall outline-level) level))
17469 (point))))
17471 (defun org-get-last-sibling ()
17472 "Move to previous heading of the same level, and return point.
17473 If there is no such heading, return nil."
17474 (let ((opoint (point))
17475 (level (funcall outline-level)))
17476 (outline-previous-heading)
17477 (when (and (/= (point) opoint) (outline-on-heading-p t))
17478 (while (and (> (funcall outline-level) level)
17479 (not (bobp)))
17480 (outline-previous-heading))
17481 (if (< (funcall outline-level) level)
17483 (point)))))
17485 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17486 ;; This contains an exact copy of the original function, but it uses
17487 ;; `org-back-to-heading', to make it work also in invisible
17488 ;; trees. And is uses an invisible-OK argument.
17489 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17490 ;; Furthermore, when used inside Org, finding the end of a large subtree
17491 ;; with many children and grandchildren etc, this can be much faster
17492 ;; than the outline version.
17493 (org-back-to-heading invisible-OK)
17494 (let ((first t)
17495 (level (funcall outline-level)))
17496 (if (and (org-mode-p) (< level 1000))
17497 ;; A true heading (not a plain list item), in Org-mode
17498 ;; This means we can easily find the end by looking
17499 ;; only for the right number of stars. Using a regexp to do
17500 ;; this is so much faster than using a Lisp loop.
17501 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17502 (forward-char 1)
17503 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17504 ;; something else, do it the slow way
17505 (while (and (not (eobp))
17506 (or first (> (funcall outline-level) level)))
17507 (setq first nil)
17508 (outline-next-heading)))
17509 (unless to-heading
17510 (if (memq (preceding-char) '(?\n ?\^M))
17511 (progn
17512 ;; Go to end of line before heading
17513 (forward-char -1)
17514 (if (memq (preceding-char) '(?\n ?\^M))
17515 ;; leave blank line before heading
17516 (forward-char -1))))))
17517 (point))
17519 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17520 "Use Org version in org-mode, for dramatic speed-up."
17521 (if (eq major-mode 'org-mode)
17522 (progn
17523 (org-end-of-subtree nil t)
17524 (unless (eobp) (backward-char 1)))
17525 ad-do-it))
17527 (defun org-forward-same-level (arg &optional invisible-ok)
17528 "Move forward to the arg'th subheading at same level as this one.
17529 Stop at the first and last subheadings of a superior heading."
17530 (interactive "p")
17531 (org-back-to-heading invisible-ok)
17532 (org-on-heading-p)
17533 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17534 (re (format "^\\*\\{1,%d\\} " level))
17536 (forward-char 1)
17537 (while (> arg 0)
17538 (while (and (re-search-forward re nil 'move)
17539 (setq l (- (match-end 0) (match-beginning 0) 1))
17540 (= l level)
17541 (not invisible-ok)
17542 (org-invisible-p))
17543 (if (< l level) (setq arg 1)))
17544 (setq arg (1- arg)))
17545 (beginning-of-line 1)))
17547 (defun org-backward-same-level (arg &optional invisible-ok)
17548 "Move backward to the arg'th subheading at same level as this one.
17549 Stop at the first and last subheadings of a superior heading."
17550 (interactive "p")
17551 (org-back-to-heading)
17552 (org-on-heading-p)
17553 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17554 (re (format "^\\*\\{1,%d\\} " level))
17556 (while (> arg 0)
17557 (while (and (re-search-backward re nil 'move)
17558 (setq l (- (match-end 0) (match-beginning 0) 1))
17559 (= l level)
17560 (not invisible-ok)
17561 (org-invisible-p))
17562 (if (< l level) (setq arg 1)))
17563 (setq arg (1- arg)))))
17565 (defun org-show-subtree ()
17566 "Show everything after this heading at deeper levels."
17567 (outline-flag-region
17568 (point)
17569 (save-excursion
17570 (org-end-of-subtree t t))
17571 nil))
17573 (defun org-show-entry ()
17574 "Show the body directly following this heading.
17575 Show the heading too, if it is currently invisible."
17576 (interactive)
17577 (save-excursion
17578 (condition-case nil
17579 (progn
17580 (org-back-to-heading t)
17581 (outline-flag-region
17582 (max (point-min) (1- (point)))
17583 (save-excursion
17584 (if (re-search-forward
17585 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17586 (match-beginning 1)
17587 (point-max)))
17588 nil)
17589 (org-cycle-hide-drawers 'children))
17590 (error nil))))
17592 (defun org-make-options-regexp (kwds &optional extra)
17593 "Make a regular expression for keyword lines."
17594 (concat
17596 "#?[ \t]*\\+\\("
17597 (mapconcat 'regexp-quote kwds "\\|")
17598 (if extra (concat "\\|" extra))
17599 "\\):[ \t]*"
17600 "\\(.*\\)"))
17602 ;; Make isearch reveal the necessary context
17603 (defun org-isearch-end ()
17604 "Reveal context after isearch exits."
17605 (when isearch-success ; only if search was successful
17606 (if (featurep 'xemacs)
17607 ;; Under XEmacs, the hook is run in the correct place,
17608 ;; we directly show the context.
17609 (org-show-context 'isearch)
17610 ;; In Emacs the hook runs *before* restoring the overlays.
17611 ;; So we have to use a one-time post-command-hook to do this.
17612 ;; (Emacs 22 has a special variable, see function `org-mode')
17613 (unless (and (boundp 'isearch-mode-end-hook-quit)
17614 isearch-mode-end-hook-quit)
17615 ;; Only when the isearch was not quitted.
17616 (org-add-hook 'post-command-hook 'org-isearch-post-command
17617 'append 'local)))))
17619 (defun org-isearch-post-command ()
17620 "Remove self from hook, and show context."
17621 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17622 (org-show-context 'isearch))
17625 ;;;; Integration with and fixes for other packages
17627 ;;; Imenu support
17629 (defvar org-imenu-markers nil
17630 "All markers currently used by Imenu.")
17631 (make-variable-buffer-local 'org-imenu-markers)
17633 (defun org-imenu-new-marker (&optional pos)
17634 "Return a new marker for use by Imenu, and remember the marker."
17635 (let ((m (make-marker)))
17636 (move-marker m (or pos (point)))
17637 (push m org-imenu-markers)
17640 (defun org-imenu-get-tree ()
17641 "Produce the index for Imenu."
17642 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17643 (setq org-imenu-markers nil)
17644 (let* ((n org-imenu-depth)
17645 (re (concat "^" outline-regexp))
17646 (subs (make-vector (1+ n) nil))
17647 (last-level 0)
17648 m level head)
17649 (save-excursion
17650 (save-restriction
17651 (widen)
17652 (goto-char (point-max))
17653 (while (re-search-backward re nil t)
17654 (setq level (org-reduced-level (funcall outline-level)))
17655 (when (<= level n)
17656 (looking-at org-complex-heading-regexp)
17657 (setq head (org-link-display-format
17658 (org-match-string-no-properties 4))
17659 m (org-imenu-new-marker))
17660 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17661 (if (>= level last-level)
17662 (push (cons head m) (aref subs level))
17663 (push (cons head (aref subs (1+ level))) (aref subs level))
17664 (loop for i from (1+ level) to n do (aset subs i nil)))
17665 (setq last-level level)))))
17666 (aref subs 1)))
17668 (eval-after-load "imenu"
17669 '(progn
17670 (add-hook 'imenu-after-jump-hook
17671 (lambda ()
17672 (if (eq major-mode 'org-mode)
17673 (org-show-context 'org-goto))))))
17675 (defun org-link-display-format (link)
17676 "Replace a link with either the description, or the link target
17677 if no description is present"
17678 (save-match-data
17679 (if (string-match org-bracket-link-analytic-regexp link)
17680 (replace-match (if (match-end 5)
17681 (match-string 5 link)
17682 (concat (match-string 1 link)
17683 (match-string 3 link)))
17684 nil t link)
17685 link)))
17687 ;; Speedbar support
17689 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17690 "Overlay marking the agenda restriction line in speedbar.")
17691 (org-overlay-put org-speedbar-restriction-lock-overlay
17692 'face 'org-agenda-restriction-lock)
17693 (org-overlay-put org-speedbar-restriction-lock-overlay
17694 'help-echo "Agendas are currently limited to this item.")
17695 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17697 (defun org-speedbar-set-agenda-restriction ()
17698 "Restrict future agenda commands to the location at point in speedbar.
17699 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17700 (interactive)
17701 (require 'org-agenda)
17702 (let (p m tp np dir txt)
17703 (cond
17704 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17705 'org-imenu t))
17706 (setq m (get-text-property p 'org-imenu-marker))
17707 (with-current-buffer (marker-buffer m)
17708 (goto-char m)
17709 (org-agenda-set-restriction-lock 'subtree)))
17710 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17711 'speedbar-function 'speedbar-find-file))
17712 (setq tp (previous-single-property-change
17713 (1+ p) 'speedbar-function)
17714 np (next-single-property-change
17715 tp 'speedbar-function)
17716 dir (speedbar-line-directory)
17717 txt (buffer-substring-no-properties (or tp (point-min))
17718 (or np (point-max))))
17719 (with-current-buffer (find-file-noselect
17720 (let ((default-directory dir))
17721 (expand-file-name txt)))
17722 (unless (org-mode-p)
17723 (error "Cannot restrict to non-Org-mode file"))
17724 (org-agenda-set-restriction-lock 'file)))
17725 (t (error "Don't know how to restrict Org-mode's agenda")))
17726 (org-move-overlay org-speedbar-restriction-lock-overlay
17727 (point-at-bol) (point-at-eol))
17728 (setq current-prefix-arg nil)
17729 (org-agenda-maybe-redo)))
17731 (eval-after-load "speedbar"
17732 '(progn
17733 (speedbar-add-supported-extension ".org")
17734 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17735 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17736 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17737 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17738 (add-hook 'speedbar-visiting-tag-hook
17739 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17742 ;;; Fixes and Hacks for problems with other packages
17744 ;; Make flyspell not check words in links, to not mess up our keymap
17745 (defun org-mode-flyspell-verify ()
17746 "Don't let flyspell put overlays at active buttons."
17747 (and (not (get-text-property (point) 'keymap))
17748 (not (get-text-property (point) 'org-no-flyspell))))
17750 (defun org-remove-flyspell-overlays-in (beg end)
17751 "Remove flyspell overlays in region."
17752 (and (org-bound-and-true-p flyspell-mode)
17753 (fboundp 'flyspell-delete-region-overlays)
17754 (flyspell-delete-region-overlays beg end))
17755 (add-text-properties beg end '(org-no-flyspell t)))
17757 ;; Make `bookmark-jump' shows the jump location if it was hidden.
17758 (eval-after-load "bookmark"
17759 '(if (boundp 'bookmark-after-jump-hook)
17760 ;; We can use the hook
17761 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17762 ;; Hook not available, use advice
17763 (defadvice bookmark-jump (after org-make-visible activate)
17764 "Make the position visible."
17765 (org-bookmark-jump-unhide))))
17767 ;; Make sure saveplace shows the location if it was hidden
17768 (eval-after-load "saveplace"
17769 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17770 "Make the position visible."
17771 (org-bookmark-jump-unhide)))
17773 ;; Make sure ecb shows the location if it was hidden
17774 (eval-after-load "ecb"
17775 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
17776 "Make hierarchy visible when jumping into location from ECB tree buffer."
17777 (if (eq major-mode 'org-mode)
17778 (org-show-context))))
17780 (defun org-bookmark-jump-unhide ()
17781 "Unhide the current position, to show the bookmark location."
17782 (and (org-mode-p)
17783 (or (org-invisible-p)
17784 (save-excursion (goto-char (max (point-min) (1- (point))))
17785 (org-invisible-p)))
17786 (org-show-context 'bookmark-jump)))
17788 ;; Make session.el ignore our circular variable
17789 (eval-after-load "session"
17790 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17792 ;;;; Experimental code
17794 (defun org-closed-in-range ()
17795 "Sparse tree of items closed in a certain time range.
17796 Still experimental, may disappear in the future."
17797 (interactive)
17798 ;; Get the time interval from the user.
17799 (let* ((time1 (org-float-time
17800 (org-read-date nil 'to-time nil "Starting date: ")))
17801 (time2 (org-float-time
17802 (org-read-date nil 'to-time nil "End date:")))
17803 ;; callback function
17804 (callback (lambda ()
17805 (let ((time
17806 (org-float-time
17807 (apply 'encode-time
17808 (org-parse-time-string
17809 (match-string 1))))))
17810 ;; check if time in interval
17811 (and (>= time time1) (<= time time2))))))
17812 ;; make tree, check each match with the callback
17813 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
17815 ;;;; Finish up
17817 (provide 'org)
17819 (run-hooks 'org-load-hook)
17821 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17823 ;;; org.el ends here